<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="~['延误'].indexOf(typeVal)">
        <view class="item">
          <view class="label"><text>*</text>延误类型</view>
          <view class="picker" @tap="ywlxShow = true">
            <text class="value" v-if="ywlxValue">{{ ywlxValue }}</text>
            <text class="placeholder" v-else>请选择</text>
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>
      </view>

      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->

      <view class="date-conteiner mt30" v-if="~['待件'].indexOf(typeVal)">
        <view v-for="(item, index) in daijian" :key="index">
          <view style="display: flex; justify-content: space-between; align-items: center">
            <view class="common-title"><text>*</text>待件{{ index + 1 }}</view>
            <view>
              <text @tap="addDaijian" style="color: blue" v-if="index + 1 == daijian.length">添加</text>
              <text @tap="delDaijian(index)" style="margin-left: 10px; color: red" v-if="daijian.length > 1">删除</text>
            </view>
          </view>
          <view class="item">
            <view class="label"><text>*</text>待件-申请编号</view>
            <view class="picker">
              <u--input placeholder="请输入" style="height: 100%" v-model="item.val1"></u--input>
            </view>
          </view>
          <br />
          <view class="item">
            <view class="label"><text>*</text>待件-物料编号</view>
            <view class="picker">
              <u--input placeholder="请输入" style="height: 100%" v-model="item.val2"></u--input>
            </view>
          </view>
          <br />
        </view>
      </view>

      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->

      <block v-if="~['预约', '改约', '拉修', '不接电话', '延误', '待件'].indexOf(typeVal)">
        <view class="date-conteiner mt30">
          <view class="item">
            <view class="label"
              ><text>*</text
              >{{ ~['改约', '拉修', '不接电话', '延误', '待件'].indexOf(typeVal) ? '改约' : '预约' }}上门开始时间</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">
          <view class="item">
            <view class="label"
              ><text>*</text
              >{{ ~['改约', '拉修', '不接电话', '延误', '待件'].indexOf(typeVal) ? '改约' : '预约' }}上门结束时间</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>
      </block>

      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->

      <block v-if="~['异常反馈'].indexOf(typeVal)">
        <view class="date-conteiner mt30">
          <view class="item">
            <view class="label"><text>*</text>异常类型</view>
            <view class="picker" @tap="yclxShow = true">
              <text class="value" v-if="yclxValue">{{ yclxValue }}</text>
              <text class="placeholder" v-else>请选择</text>
              <text class="iconfont icon-jinru"></text>
            </view>
          </view>
        </view>
        <view class="date-conteiner mt30">
          <view class="item">
            <view class="label"><text>*</text>异常原因</view>
            <view class="picker" @tap="ycyyShow = true">
              <text class="value" v-if="ycyyValue">{{ ycyyValue }}</text>
              <text class="placeholder" v-else>请选择</text>
              <text class="iconfont icon-jinru"></text>
            </view>
          </view>
        </view>
      </block>

      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->

      <block v-if="~['完工反馈'].indexOf(typeVal)">
        <view class="over-container mt30">
          <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">
          <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>
      </block>

      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->

      <block v-if="~['质量信息'].indexOf(typeVal)">
        <view class="date-conteiner mt30">
          <view class="item">
            <view class="label"><text>*</text>质量反馈编号</view>
            <view class="picker">
              <u--input placeholder="请输入" style="height: 100%" v-model="zlfkbh"></u--input>
            </view>
          </view>
        </view>
        <view class="date-conteiner mt30">
          <view class="item">
            <view class="label"><text>*</text>反馈日期</view>
            <view class="picker" @tap="isShowDatePicker3 = true">
              <text class="value" v-if="date3">{{ date3 }}</text>
              <text class="placeholder" v-else>请选择</text>
              <text class="iconfont icon-jinru"></text>
            </view>
          </view>
        </view>
      </block>

      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->

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

      <view class="mt30 image-container">
        <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
      v-if="isShowDatePicker"
      :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
      v-if="isShowDatePicker2"
      :show="isShowDatePicker2"
      v-model="datePickerValue2"
      type="datetime"
      placeholder="选择日期和时间"
      @confirm="confirmDate2"
      @cancel="isShowDatePicker2 = false"
      @close="isShowDatePicker2 = false"
      :minDate="minDate2"
      :maxDate="maxDate2"
      :formatter="formatter"
      :style="{ width: '100%' }"
    />

    <zjDialogPicker
      ref="yclxList"
      :isShow="yclxShow"
      :multiple="false"
      :styleType="2"
      :title="'异常类型'"
      :list="yclxList"
      :keyName="'label'"
      @cancel="yclxShow = false"
      @confirm="confirmyClx"
    />

    <zjDialogPicker
      ref="ycyyList"
      :isShow="ycyyShow"
      :multiple="false"
      :styleType="2"
      :title="'异常原因'"
      :list="ycyyList"
      :keyName="'label'"
      @cancel="ycyyShow = false"
      @confirm="confirmYcyy"
    />

    <zjDialogPicker
      ref="ywlxList"
      :isShow="ywlxShow"
      :multiple="false"
      :styleType="2"
      :title="'延误类型'"
      :list="ywlxList"
      :keyName="'label'"
      @cancel="ywlxShow = false"
      @confirm="confirmYwlx"
    />

    <u-datetime-picker
      :show="isShowDatePicker3"
      v-model="datePickerValue3"
      type="datetime"
      placeholder="选择日期和时间"
      @confirm="confirmDate3"
      @cancel="isShowDatePicker3 = false"
      @close="isShowDatePicker3 = false"
      :formatter="formatter"
      :style="{ width: '100%' }"
    />
  </zj-page-layout>
</template>

<script>
import { uploadImgFull } from '@/common/utils/util.js'
import zjDialogPicker from '@/components/zj-dialog/zj-dialog-picker.vue'
export default {
  components: {
    zjDialogPicker
  },
  data() {
    return {
      typeVal: '备注',
      typeList: [
        { name: '备注', value: '备注' },
        { name: '预约', value: '预约' },
        { name: '改约', value: '改约' },
        { name: '异常反馈', value: '异常反馈' },
        { name: '完工反馈', value: '完工反馈' },
        { name: '待件', value: '待件' },
        { name: '拉修', value: '拉修' },
        { name: '不接电话', value: '不接电话' },
        { name: '延误', value: '延误' },
        { name: '质量信息', value: '质量信息' }
      ],
      ywlxList: [
        { label: '无人接听', value: '无人接听' },
        { label: '天气原因', value: '天气原因' },
        { label: '配件未到货', value: '配件未到货' },
        { label: '异常工单', value: '异常工单' }
      ],
      yclxShow: false,
      ycyyShow: false,
      ywlxShow: false,
      abnormalList: [],
      isShowDatePicker3: false,
      datePickerValue3: new Date().getTime(),
      minDate: new Date().getTime(),
      minDate2: null,
      maxDate2: null,
      datePickerValue: new Date().getTime(),
      isShowDatePicker: false,
      datePickerValue2: new Date().getTime(),
      isShowDatePicker2: false,
      canClickBtn: true,
      //
      id: '',
      yclxValue: '', //异常类型
      ycyyValue: '', //异常原因
      ywlxValue: '', //延误类型
      zlfkbh: '', //质量反馈编号
      date3: '', // 反馈日期时间
      date: '', //预约改约上门开始时间
      date2: '', //预约改约上门结束时间
      remarkVal: '', // 备注值
      imageList: [], //上传的文件数据
      signNameUrl: '', //签名
      daijian: [{ val1: '', val2: '' }], // 待件信息
      orderDetail: {}
    }
  },

  async onLoad({ id }) {
    this.id = id
    this.getOrderDetail()
    this.crossPage.$on('finishSign', async data => {
      this.signNameUrl = data
    })
    this.crossPage.$on('refreshFeedbackForm', () => {
      this.getOrderDetail()
    })
    this.$api
      .post('/pg/order/base/abnormalList', { exType: '' })
      .then(res => {
        this.abnormalList = res.data
      })
      .catch(res => {})
  },

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

  computed: {
    yclxList() {
      return [...new Set(this.abnormalList.map(item => item.exType))]?.map(v => ({ label: v, value: v })) || []
    },
    ycyyList() {
      return this.yclxValue
        ? this.abnormalList
            ?.filter(item => item.exType === this.yclxValue)
            ?.map(v => ({ label: v.exNote, value: v.exNote }))
        : []
    }
  },

  methods: {
    // 添加待件
    addDaijian() {
      this.daijian.push({ val1: '', val2: '' })
    },
    // 删除待件
    delDaijian(index) {
      this.daijian.splice(index, 1)
    },
    // 异常类型
    confirmyClx([index]) {
      this.yclxValue = this.yclxList?.[index]?.label || ''
      this.ycyyValue = ''
      this.yclxShow = false
    },
    // 异常原因
    confirmYcyy([index]) {
      this.ycyyValue = this.ycyyList?.[index]?.label || ''
      this.ycyyShow = false
    },
    // 延误类型
    confirmYwlx([index]) {
      this.ywlxValue = this.ywlxList?.[index]?.label || ''
      this.ywlxShow = false
    },
    // 赋值预约改约开始时间
    confirmDate(e) {
      this.isShowDatePicker = false
      this.date = ''
      this.$nextTick(() => {
        this.date = this.formatTimestamp(e.value)
        this.date2 = ''
        this.datePickerValue2 = new Date(e.value).getTime()
      })
    },
    // 校验预约改约开始时间是否已选择
    setisShowDatePicker2() {
      if (!this.date) {
        return this.$tips(`请先选择${this.typeVal}开始时间`)
      }
      this.minDate2 = Number(new Date(this.date.split(' ').join('T')))
      this.maxDate2 = Number(this.getEndOfDayTimestamp(this.minDate2))
      this.$nextTick(() => {
        this.isShowDatePicker2 = true
      })
    },
    getEndOfDayTimestamp(timestamp) {
      // 创建一个日期对象
      const date = new Date(timestamp)

      // 设置为当天的 23:59:59
      date.setHours(23, 59, 59, 999)

      // 返回时间戳
      return date.getTime()
    },
    // 赋值预约改约结束时间
    confirmDate2(e) {
      this.isShowDatePicker2 = false
      this.date2 = this.formatTimestamp(e.value)
    },
    // 赋值反馈日期
    confirmDate3(e) {
      this.isShowDatePicker3 = false
      this.date3 = this.formatTimestamp(e.value)
    },

    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
            resolve(1)
          })
          .catch(res => {
            reject(0)
          })
      })
    },

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

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

    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)

      let params = {
        id: this.id,
        orderBaseId: this.id,
        type: this.typeVal,
        typeText: this.typeVal,
        imgSrc: this.imageList
          .map(item => {
            return item.url
          })
          .join(',')
      }

      if (~['延误'].indexOf(this.typeVal)) {
        if (!this.ywlxValue) {
          return this.$toast('请选择延误类型')
        }
        params.ywType = this.ywlxValue
      }

      if (~['待件'].indexOf(this.typeVal)) {
        if (!this.daijian.length) {
          return this.$toast('请填写待件信息')
        }
        for (var item of this.daijian) {
          if (!item.val1 || !item.val2) {
            return this.$toast('请填写完整待件信息')
          }
        }
        params.applyNum = this.daijian.map(item => `${item.val1}|${item.val2}`).join(',')
      }

      if (~['预约', '改约', '拉修', '不接电话', '延误', '待件'].indexOf(this.typeVal)) {
        if (!this.date) {
          return this.$toast('请选择开始时间')
        }
        if (!this.date2) {
          return this.$toast('请选择结束时间')
        }
        params.appointmentTime = this.date
        params.appointmentEndTime = this.date2
      }

      if (~['异常反馈'].indexOf(this.typeVal)) {
        if (!this.yclxValue) {
          return this.$toast('请选择异常类型')
        }
        if (!this.ycyyValue) {
          return this.$toast('请选择异常原因')
        }
        params.exType = this.yclxValue
        params.exNote = this.ycyyValue
      }

      if (~['完工反馈'].indexOf(this.typeVal)) {
        if (!this.signNameUrl) {
          return this.$toast('请签名')
        }
        const lo = await this.$getAddress()

        params.userSign = this.signNameUrl
        params.address = lo.address || ''
      }

      if (~['质量信息'].indexOf(this.typeVal)) {
        if (!this.zlfkbh) {
          return this.$toast('请输入质量反馈编号')
        }
        if (!this.date3) {
          return this.$toast('请选择反馈日期')
        }
        params.zlNumber = this.zlfkbh
        params.fkTime = this.date3
      }

      if (!this.remarkVal) {
        return this.$toast('请填写备注信息')
      } else {
        params.remark = this.remarkVal
        params.content = this.remarkVal
        params.overRemark = this.remarkVal
      }

      // ------------------------------------------------------------------

      // 改约
      if (~['预约', '改约'].indexOf(this.typeVal)) {
        this.$api
          .post('/changeOrder/changeAppointmentTime', {
            ...params
          })
          .then(res => {
            this.submitSuccess()
          })
      }
      // 完工反馈
      else if (~['完工反馈'].indexOf(this.typeVal)) {
        this.$api
          .post('/changeOrder/submitAll', {
            ...params
          })
          .then(res => {
            this.submitSuccess('YWG')
          })
      } else {
        this.$api
          .postJson('/pg/order/base/operator/add', {
            ...params
          })
          .then(res => {
            this.submitSuccess()
          })
      }
    },

    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;
    justify-content: space-between;

    .item {
      width: calc((100% - 30rpx) / 3);
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 20rpx;
      background: #f4f5f9;
      margin-bottom: 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>
