<template>
  <zj-page-layout :hasFooter="true">
    <view class="all-container">
      <view class="type-container mt30">
        <view class="common-title"><text>*</text>反馈类型</view>
        <view class="list">
          <view
            class="item"
            v-for="(item, index) in typeList"
            :key="index"
            :class="typeVal === item.value ? 'active' : ''"
            @tap="changeType(item.value)"
            >{{ item.name }}</view
          >
        </view>
      </view>

      <view class="date-conteiner mt30" v-if="typeVal == '2'">
        <view class="item">
          <view class="label"><text>*</text>预约上门开始时间</view>
          <view class="picker" @tap="isShowDatePicker = true">
            <text class="value" v-if="date">{{ date }}</text>
            <text class="placeholder" v-else>请选择</text>
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>
      </view>

      <view class="date-conteiner mt30" v-if="typeVal == '2'">
        <view class="item">
          <view class="label"><text>*</text>预约上门结束时间</view>
          <view class="picker" @tap="setisShowDatePicker2">
            <text class="value" v-if="date2">{{ date2 }}</text>
            <text class="placeholder" v-else>请选择</text>
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>
      </view>

      <view class="over-container mt30" v-if="typeVal == '3'">
        <view class="row">
          <view class="label"><text>*</text>完工采集</view>
          <view class="btn"
            ><u-button
              type="primary"
              :text="orderDetail && orderDetail.isGather == 'YES' ? '查看采集' : '数据采集'"
              @click="toCollect"
            ></u-button>
          </view>
        </view>
        <view class="row">
          <view class="label"
            >收费项目<u-icon
              name="question-circle"
              color="#999999"
              @click="$tips('在服务过程中消耗的产品（配件）')"
            ></u-icon
          ></view>
          <view class="btn"><u-button type="primary" text="添加" @click="toCharge"></u-button></view>
        </view>
      </view>

      <view class="sign-container mt30" v-if="typeVal == '3'">
        <view class="common-title"><text>*</text>客户签名</view>
        <view class="empty" @tap="toSignName" v-if="!signNameUrl">点我签名</view>
        <view class="img" v-else>
          <image :src="signNameUrl" mode="widthFix" @tap="prevSignImg(signNameUrl)"></image>
          <text class="iconfont icon-guanbi1" @tap="signNameUrl = ''"></text>
        </view>
      </view>

      <view class="mt30 remark-container">
        <view class="common-title"><text v-if="typeVal == '1' || typeVal == '4'">*</text>备注信息</view>
        <u--textarea v-model="remarkVal" placeholder="请输入备注内容" fixed border="none" height="120"></u--textarea>
      </view>

      <view class="mt30 image-container" v-if="typeVal == '1' || typeVal == '4'">
        <view class="common-title">上传图片(最多6张)</view>
        <view class="images">
          <block v-for="(item, index) in imageList" :key="index">
            <view class="img">
              <image :src="item.url" mode="aspectFill" @tap="prevImg(item.url)"></image>
              <text class="iconfont icon-guanbi1" @tap="delImage(index)"></text>
            </view>
          </block>
          <view class="add" @tap="addImage" v-if="imageList.length < 6">
            <text class="iconfont icon-xiangji"></text>
            <text class="text">添加图片</text>
          </view>
        </view>
      </view>
    </view>

    <template slot="footer">
      <view class="footer-btn-group">
        <u-button text="确定" type="primary" size="large" @click="submitData"></u-button>
      </view>
    </template>

    <u-datetime-picker
      :show="isShowDatePicker"
      v-model="datePickerValue"
      type="datetime"
      placeholder="选择日期和时间"
      @confirm="confirmDate"
      @cancel="isShowDatePicker = false"
      @close="isShowDatePicker = false"
      :minDate="minDate"
      :formatter="formatter"
      :style="{ width: '100%' }"
    />
    <u-datetime-picker
      :show="isShowDatePicker2"
      v-model="datePickerValue2"
      type="datetime"
      placeholder="选择日期和时间"
      @confirm="confirmDate2"
      @cancel="isShowDatePicker2 = false"
      @close="isShowDatePicker2 = false"
      :minDate="minDate2"
      :formatter="formatter"
      :style="{ width: '100%' }"
    />
  </zj-page-layout>
</template>

<script>
import { uploadImgFull } from '@/common/utils/util.js'

export default {
  data() {
    return {
      datetime: null,
      limitDateTime: new Date('2024-07-19 12:23:36'),

      id: '',
      orderDetail: {},
      typeList: [
        { name: '其他', value: '1' },
        { name: '改约', value: '2' },
        { name: '完工反馈', value: '3' },
        { name: '异常反馈', value: '4' }
      ],
      typeVal: '1',
      minDate: new Date().getTime(),
      minDate2: null,
      date: '',
      datePickerValue: new Date().getTime(),
      isShowDatePicker: false,
      date2: '',
      datePickerValue2: new Date().getTime(),
      isShowDatePicker2: false,
      remarkVal: '', // 备注值
      imageList: [],
      signNameUrl: '',
      canClickBtn: true
    }
  },

  async onLoad({ id }) {
    this.id = id
    this.getOrderDetail()

    this.crossPage.$on('finishSign', async data => {
      // this.$showLoading();
      this.signNameUrl = data
    })

    this.crossPage.$on('refreshFeedbackForm', () => {
      this.getOrderDetail()
    })
  },

  onUnload() {
    this.crossPage.$off('finishSign')
    this.crossPage.$off('refreshFeedbackForm')
  },

  methods: {
    confirmDate(e) {
      this.isShowDatePicker = false
      this.date = ''
      this.$nextTick(() => {
        this.date = this.formatTimestamp(e.value)
        this.date2 = ''
        this.datePickerValue2 = new Date(e.value).getTime()
      })
    },

    confirmDate2(e) {
      this.isShowDatePicker2 = false
      this.date2 = this.formatTimestamp(e.value)
    },

    setisShowDatePicker2() {
      if (!this.date) {
        return this.$tips('请先选择预约开始时间')
      }
      this.minDate2 = Number(new Date(this.date))
      this.$nextTick(() => {
        this.isShowDatePicker2 = true
      })
    },

    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      if (type === 'day') {
        return `${value}日`
      }
      if (type === 'hour') {
        return `${value}时`
      }
      if (type === 'minute') {
        return `${value}分`
      }
      return value
    },

    // 获取详情
    getOrderDetail() {
      return new Promise((resolve, reject) => {
        this.$api
          .post('/pg/order/base/detail', {
            orderBaseId: this.id
          })
          .then(res => {
            this.orderDetail = res.data
            if (res.data.appointmentTime) {
              this.typeList[1].name = '改约'
            } else {
              this.typeList[1].name = '预约'
            }
            resolve(1)
          })
          .catch(res => {
            reject(0)
          })
      })
    },

    changeType(val) {
      if (!this.orderDetail.appointmentTime && val == 3) {
        return this.$tips('请先预约工单再完工反馈')
      }
      this.typeVal = val
    },

    // 去采集
    toCollect() {
      this.$navToPage({
        url: `/packageWorkorder/pages/infoCollect/list?id=${this.id}`
      })
    },

    confirmDate(e) {
      this.isShowDatePicker = false
      this.date = ''
      this.$nextTick(() => {
        this.date = this.formatTimestamp(e.value)
        this.date2 = ''
        this.datePickerValue2 = new Date(e.value).getTime()
      })
    },

    confirmDate2(e) {
      this.isShowDatePicker2 = false
      this.date2 = this.formatTimestamp(e.value)
    },

    formatTimestamp(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    // 添加图片
    async addImage() {
      uni.chooseImage({
        count: 6 - this.imageList.length,
        success: res => {
          uni.showLoading()
          res.tempFilePaths.forEach(async item => {
            let data = await uploadImgFull(item)
            this.imageList.push(data)
          })
          uni.hideLoading()
        },
        fail: err => {}
      })
    },

    // 删除图片
    delImage(index) {
      this.imageList.splice(index, 1)
    },

    //预览图片
    prevImg(current) {
      uni.previewImage({
        current,
        urls: this.imageList.map(item => {
          return item.url
        })
      })
    },

    prevSignImg(url) {
      uni.previewImage({
        current: url,
        urls: [url]
      })
    },

    // 去收费
    toCharge() {
      if (this.orderDetail.orderType == 'INSTALL') {
        this.$navToPage({
          url: `/packageMaterial/pages/sale/index?type=${this.orderDetail.orderType == 'INSTALL' ? 'M' : 'P'}&oid=${
            this.id
          }`
        })
      } else {
        this.$navToPage({
          url: `/packageMaterial/pages/newSale/index?type=${this.orderDetail.orderType == 'INSTALL' ? 'M' : 'P'}&oid=${
            this.id
          }`
        })
      }
    },

    toSignName() {
      this.$navToPage({
        url: `/packageWorkorder/pages/signName`
      })
    },

    // 提交
    async submitData() {
      if (!this.canClickBtn) return this.$toast('请勿频繁操作')
      this.canClickBtn = false
      setTimeout(() => {
        this.canClickBtn = true
      }, 3000)

      if (this.typeVal == '2' && !this.date) return this.$toast('请选择改约时间')
      if (this.typeVal == '2' && !this.date2) return this.$toast('请选择改约时间')
      if (this.typeVal == '3' && !this.signNameUrl) return this.$toast('请签名')
      if ((this.typeVal == '1' || this.typeVal == '4') && !this.remarkVal) return this.$toast('请填写备注信息')

      let params = {}

      if (this.typeVal == '2') {
        params.id = this.id
        params.appointmentTime = this.date
        params.appointmentEndTime = this.date2
        params.remark = this.remarkVal
      } else {
        params.orderBaseId = this.id
        params.content = this.remarkVal
      }

      if (this.typeVal == '1') {
        params.type = '其他'
        params.typeText = '其他'
      }
      if (this.typeVal == '4') {
        params.type = '异常反馈'
        params.typeText = '异常反馈'
      }
      if (this.typeVal == '1' || this.typeVal == '4') {
        params.imgSrc = this.imageList
          .map(item => {
            return item.url
          })
          .join(',')
      }

      if (this.typeVal == '3') {
        const lo = await this.$getAddress()

        params.orderBaseId = this.id
        params.overRemark = this.remarkVal
        params.userSign = this.signNameUrl
        params.address = lo.address || ''
      }

      // 其他/异常反馈
      if (this.typeVal == '1' || this.typeVal == '4') {
        this.$api
          .postJson('/pg/order/base/operator/add', {
            ...params
          })
          .then(res => {
            this.submitSuccess()
          })
      }
      // 改约
      else if (this.typeVal == '2') {
        this.$api
          .post('/changeOrder/changeAppointmentTime', {
            ...params
          })
          .then(res => {
            this.submitSuccess()
          })
      }
      // 完工反馈
      else if (this.typeVal == '3') {
        this.$api
          .post('/changeOrder/submitAll', {
            ...params
          })
          .then(res => {
            this.submitSuccess('YWG')
          })
      }
    },

    submitSuccess(tab = '') {
      this.$successToast('反馈成功')
      this.crossPage.$emit('refreshWorkorderList', { tab: tab })
      this.crossPage.$emit('refreshWorkorderDetail', '')
      setTimeout(() => {
        this.$navToPage(
          {
            delta: 1
          },
          'navigateBack'
        )
      }, 500)
    }
  }
}
</script>

<style lang="scss" scoped>
.all-container {
  padding-bottom: 30rpx;
}

.common-title {
  font-size: 32rpx;
  font-weight: 600;
  padding: 30rpx 0;

  text {
    color: $minor-color;
  }
}

.type-container {
  background: #ffffff;
  padding: 0 30rpx;

  .list {
    display: flex;
    flex-wrap: wrap;

    .item {
      width: calc((100% - 30rpx) / 2);
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 20rpx;
      background: #f4f5f9;
      margin-bottom: 30rpx;

      &:nth-child(2n) {
        margin-left: 30rpx;
      }

      &.active {
        background: $theme-color;
        color: #ffffff;
      }
    }
  }
}

.date-conteiner {
  background: #ffffff;
  padding: 30rpx 30rpx;

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50rpx;

    .label {
      margin-right: 30rpx;

      text {
        color: $error-color;
      }
    }

    .picker {
      .placeholder {
        color: $sec-font;
      }

      .iconfont {
        margin-left: 12rpx;
        color: $sec-font;
      }
    }
  }
}

.over-container {
  background: #ffffff;
  padding: 10rpx 30rpx;

  .row {
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .label {
      font-size: 32rpx;
      font-weight: 600;
      display: flex;
      align-items: center;

      text {
        color: $minor-color;
      }

      ::v-deep .u-icon {
        margin-left: 8rpx;
      }
    }

    .btn {
      ::v-deep .u-button {
        height: 60rpx;
      }
    }
  }
}

.sign-container {
  background: #ffffff;
  padding: 0 30rpx 30rpx;

  .empty {
    height: 200rpx;
    background: #f4f5f9;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12rpx;
    color: $sec-font;
  }

  .img {
    position: relative;

    image {
      width: 100%;
      height: 200rpx;
    }

    text {
      position: absolute;
      right: -10rpx;
      top: -10rpx;
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      background: #ff3f42;
      font-size: 24rpx;
      color: #ffffff;
      text-align: center;
      line-height: 40rpx;
      display: block;
    }
  }
}

.remark-container {
  padding: 1rpx 30rpx 30rpx;
  background: #ffffff;

  ::v-deep .u-textarea {
    background: #f4f5f9;
  }
}

.image-container {
  padding: 1rpx 30rpx 30rpx;
  background: #ffffff;

  .images {
    display: flex;
    flex-wrap: wrap;

    .add {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 146rpx;
      height: 146rpx;
      border: 2rpx dashed #dadada;
      border-radius: 10rpx;
      margin-top: 20rpx;

      .iconfont {
        font-size: 48rpx;
        color: #999999;
      }

      .text {
        font-size: 24rpx;
        color: #999999;
        margin-top: 10rpx;
      }
    }

    .img {
      position: relative;
      margin-right: 20rpx;
      margin-top: 20rpx;

      &:nth-child(4n) {
        margin-right: 0;
      }

      image {
        width: 150rpx;
        height: 150rpx;
        border-radius: 10rpx;
        overflow: hidden;
        display: block;
      }

      text {
        position: absolute;
        right: -10rpx;
        top: -10rpx;
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        background: #ff3f42;
        font-size: 24rpx;
        color: #ffffff;
        text-align: center;
        line-height: 40rpx;
        display: block;
      }
    }
  }
}
</style>
