<template>
  <view>
    <zj-page-layout :hasFooter="true" :isScroll="false">
      <view class="top-container" v-if="detail">
        <view class="row" style="margin-bottom: 30rpx">
          <view class="label">产品小类：</view>
          <view class="value">
            <!-- {{detail.smallName || ''}} -->
            <u--input placeholder="请输入产品小类" style="height: 30rpx" v-model="detail.smallName"></u--input>
          </view>
        </view>
        <view class="row">
          <view class="label">产品机型：</view>
          <view class="value">
            <!-- {{detail.productName || ''}} -->
            <u--input placeholder="请输入产品机型" style="height: 30rpx" v-model="detail.productName"></u--input>
          </view>
        </view>
        <view class="row">
          <view class="label">大工师傅：</view>
          <view class="value">{{
            detail.pgOrderWorkers
              .filter(t => t.isMaster == true)
              .map(o => o.workerName)
              .join(',')
          }}</view>
        </view>
        <view class="row">
          <view class="label">小工师傅：</view>
          <view class="value">{{
            detail.pgOrderWorkers
              .filter(t => t.isMaster == false)
              .map(o => o.workerName)
              .join(',')
          }}</view>
        </view>
      </view>

      <view class="card-container">
        <view class="common-title"><text class="star">*</text>采集图片<text class="tips">最少1张</text></view>
        <view class="imgs">
          <view class="it" v-for="(item, index) in collectImgList" :key="index">
            <block v-if="item.fileUrl">
              <text class="iconfont icon-guanbi1 close" @tap="delCollectImg(index)" v-if="!isView"></text>
              <image mode="aspectFill" :src="item.fileUrl" @tap="prevImg(item.fileUrl)"> </image>
            </block>
            <view class="empty" v-else @tap="isView ? '' : chooseCollectImg(index)">
              <text class="iconfont icon-xiangji"></text>
              <text class="text">{{ isView ? '暂无图片' : '添加图片' }}</text>
            </view>
            <view class="name">{{ item.fileName }}</view>
          </view>
        </view>
      </view>
      <!-- v-if="orderDetail.orderType == 'REPAIR'" -->
      <view class="card-container" v-if="orderDetail.orderType == 'REPAIR'">
        <view class="common-title">内机条码</view>
        <view class="code">
          <u--input placeholder="请输入内机条码" border="none" v-model="insideCode"></u--input>
          <view class="btn" @click="getScancode('insideCode')">扫描</view>
        </view>
        <view class="title mt20"><text class="star">*</text>故障现象</view>
        <u--textarea
          v-model="faultRemark"
          placeholder="请输入故障现象"
          fixed
          border="none"
          :disabled="isView"
        ></u--textarea>
        <view class="title mt20"><text class="star">*</text>故障图片<text class="tips">最少1张</text></view>
        <view class="imgs">
          <view class="it" v-for="(item, index) in faultImgList" :key="index">
            <block v-if="item.fileUrl">
              <text class="iconfont icon-guanbi1 close" @tap="delFaultImg(index)" v-if="!isView"></text>
              <image mode="aspectFill" :src="item.fileUrl" @tap="prevImg(item.fileUrl)"> </image>
            </block>
            <view class="empty" v-else @tap="isView ? '' : chooseFaultImg(index)">
              <text class="iconfont icon-xiangji"></text>
              <text class="text">{{ isView ? '暂无图片' : '添加图片' }}</text>
            </view>
            <view class="name">{{ item.fileName }}</view>
          </view>
        </view>
        <view class="row">
          <view class="title"><text class="star">*</text>是否保内</view>
          <view class="radio">
            <view class="item" :class="isBaoNei ? 'active' : ''" @tap="isView ? '' : (isBaoNei = true)">是</view>
            <view class="item" :class="!isBaoNei ? 'active' : ''" @tap="isView ? '' : (isBaoNei = false)">否</view>
          </view>
        </view>
      </view>

      <view class="card-container">
        <view class="common-title">备注</view>
        <u--textarea
          v-model="remarkVal"
          placeholder="请输入备注内容"
          fixed
          border="none"
          :disabled="isView"
        ></u--textarea>
      </view>

      <u-gap height="30"></u-gap>

      <template slot="footer">
        <view class="footer-btn-group" v-if="!isView">
          <u-button text="临时保存" size="large" @click="submitData(1)"></u-button>
          <u-button text="提交采集" type="primary" size="large" @click="submitData(2)"></u-button>
        </view>
        <view class="footer-btn-group" v-else>
          <u-button text="返回" size="large" @click="backPage()"></u-button>
        </view>
      </template>
    </zj-page-layout>
  </view>
</template>

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

export default {
  data() {
    return {
      oid: null, // 服务单id
      cid: null, // 采集id
      detail: null,
      orderDetail: {},
      isView: false, // 是否仅查看

      collectImgList: [],
      faultImgList: [],

      collectImgType: null,
      collectImgTypeList: [],
      isShowCollectImgTypeDialog: false,
      faultImgType: null,
      faultImgTypeList: [],
      isShowFaultImgTypeDialog: false,

      isBaoNei: true,
      faultRemark: '',
      remarkVal: '', // 采集备注

      address: '',
      isNeedSave: true,

      insideCode: ''
    }
  },

  async onLoad({ oid, cid, isView }) {
    this.oid = oid
    this.cid = cid
    this.isView = isView == 1 ? true : false

    await this.getOrderDetail()

    await this.getCollectImgTypeList()
    if (this.orderDetail.orderType == 'REPAIR') {
      await this.getFaultImgTypeList()
    }

    this.getDetail()

    const lo = await this.$getAddress()
    this.address = lo.address || ''
  },

  methods: {
    async getScancode(type) {
      var codeVal = await wxScanCode()
      this[type] = codeVal
    },

    getDetail() {
      this.$api
        .post('/changeOrder/productDetail', {
          id: this.cid
        })
        .then(res => {
          this.detail = res.data

          const data = res.data

          let collectImgList = data.pgOrderProductDetails.filter(o => o.type == 'INSTALL')
          let faultImgList = data.pgOrderProductDetails.filter(o => o.type == 'BUG')
          for (let i = 0; i < this.collectImgList.length; i++) {
            for (let j = 0; j < collectImgList.length; j++) {
              if (this.collectImgList[i].fileName == collectImgList[j].fileName) {
                let obj = this.collectImgList[j]
                obj.fileUrl = collectImgList[j].fileUrl
                this.collectImgList.splice(j, 1, obj)
              }
            }
          }
          for (let i = 0; i < this.faultImgList.length; i++) {
            for (let j = 0; j < faultImgList.length; j++) {
              if (this.faultImgList[i].fileName == faultImgList[j].fileName) {
                let obj = this.faultImgList[j]
                obj.fileUrl = faultImgList[j].fileUrl
                this.faultImgList.splice(j, 1, obj)
              }
            }
          }

          this.faultRemark = data.bugRemark
          this.isBaoNei = data.isDefend == 'YES' ? true : false
          this.remarkVal = data.detailRemark
          this.insideCode = data.insideCode
        })
    },

    // 获取工单详情
    async getOrderDetail() {
      return new Promise((resolve, reject) => {
        this.$api
          .post('/pg/order/base/detail', {
            orderBaseId: this.oid
          })
          .then(res => {
            this.orderDetail = res.data
          })
          .finally(res => {
            resolve(1)
          })
      })
    },

    // 获取采集图片类型列表
    async getCollectImgTypeList() {
      return new Promise((resolve, reject) => {
        this.$api
          .post('/changeOrder/sysDict', {
            dictType: 'GATHER_IMG'
          })
          .then(res => {
            this.collectImgList = res.data.map(item => {
              return {
                fileUrl: '',
                fileName: item.dictValue,
                type: 'INSTALL'
              }
            })
            resolve(1)
          })
      })
    },

    // 获取故障图片类型列表
    async getFaultImgTypeList() {
      return new Promise((resolve, reject) => {
        this.$api
          .post('/changeOrder/sysDict', {
            dictType: 'BUG_IMG'
          })
          .then(res => {
            this.faultImgList = res.data.map(item => {
              return {
                fileUrl: '',
                fileName: item.dictValue,
                type: 'BUG'
              }
            })
            resolve(1)
          })
      })
    },

    // 上传采集图片
    async chooseCollectImg(index) {
      if (!this.address) {
        // uni.showLoading()
        const lo = await this.$getAddress()
        this.address = lo.address || ''
        if (!this.address) {
          this.address = `${this.orderDetail.province}${this.orderDetail.city}${this.orderDetail.area}${this.orderDetail.street}`
        }
      }

      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async res => {
          let data = await uploadImgFull(res.tempFilePaths[0])
          this.$api
            .post('/changeOrder/submitPic', {
              patch: data.url,
              positionName: this.address,
              productDetailId: this.detail.id
            })
            .then(res => {
              let obj = this.collectImgList[index]
              obj.fileUrl = res.data
              this.collectImgList.splice(index, 1, obj)
              uni.hideLoading()
            })
        },
        fail: err => {
          uni.hideLoading()
          console.log(err)
        }
      })
    },

    // 选择故障图片
    async chooseFaultImg(index) {
      if (!this.address) {
        uni.showLoading()
        const lo = await this.$getAddress()
        this.address = lo.address || ''
        if (!this.address) {
          this.address = `${this.orderDetail.province}${this.orderDetail.city}${this.orderDetail.area}${this.orderDetail.street}`
        }
      }

      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async res => {
          let data = await uploadImgFull(res.tempFilePaths[0])
          this.$api
            .post('/changeOrder/submitPic', {
              patch: data.url,
              positionName: this.address,
              productDetailId: this.detail.id
            })
            .then(res => {
              let obj = this.faultImgList[index]
              obj.fileUrl = res.data
              this.faultImgList.splice(index, 1, obj)
              uni.hideLoading()
            })
        },
        fail: err => {
          uni.hideLoading()
          console.log(err)
        }
      })
    },

    delCollectImg(index) {
      let obj = this.collectImgList[index]
      obj.fileUrl = ''
      this.collectImgList.splice(index, 1, obj)
    },

    delFaultImg(index) {
      let obj = this.faultImgList[index]
      obj.fileUrl = ''
      this.faultImgList.splice(index, 1, obj)
    },

    // 预览图片
    prevImg(url) {
      uni.previewImage({
        current: url,
        urls: [url]
      })
    },

    // 提交（type: 1=临时保存 2=提交采集 0=本地缓存）
    async submitData(type) {
      let collectImgList = JSON.parse(JSON.stringify(this.collectImgList)).filter(o => o.fileUrl)
      let faultImgList = JSON.parse(JSON.stringify(this.faultImgList)).filter(o => o.fileUrl)

      if (type === 2) {
        if (collectImgList.length < 1) return this.$toast('请上传采集图片')

        if (this.orderDetail.orderType == 'REPAIR') {
          if (!this.faultRemark) return this.$toast('请填写故障现象')
          if (faultImgList.length < 1) return this.$toast('请上传故障图片')
        }
      }

      let params = {
        orderBaseId: this.oid,
        id: this.cid,
        bugRemark: this.faultRemark,
        isDefend: this.isBaoNei ? 'YES' : 'NO',
        detailRemark: this.remarkVal,
        pgOrderProductDetails: [...collectImgList, ...faultImgList],
        status: type == 2 ? 'OK' : 'WAIT_SAVE',
        giveAddress: this.address,
        insideCode: this.insideCode,
        productName: this?.detail?.productName,
        smallName: this?.detail?.smallName
      }

      // 本地缓存
      if (type === 0) {
        this.setStorage(params)
      }

      // 临时保存 / 提交采集
      else {
        this.$api
          .postJson('/changeOrder/submit', params)
          .then(res => {
            if (type === 1) {
              // this.setStorage(params);
              this.$successToast('保存成功')
            } else {
              // this.delStorage();
              // this.isNeedSave = false;
              this.$successToast('提交成功')
            }
            this.crossPage.$emit('refreshCollectList', type)
            setTimeout(() => {
              this.$navToPage(
                {
                  delta: 1
                },
                'navigateBack'
              )
            }, 500)
          })
          .catch(res => {
            // this.setStorage(params);
          })
      }
    },

    // 记录缓存
    setStorage(params) {
      let storageList = this.$getStorage('collectDataList') || []
      let index = storageList.findIndex(item => item['id'] === this.cid)
      // 如果有就替换  没有就添加
      if (index !== -1) {
        storageList.splice(index, 1, params)
      } else {
        storageList.push(params)
      }
      this.$removeStorage('collectDataList')
      this.$setStorage('collectDataList', storageList)
    },

    // 删除缓存
    delStorage() {
      let storageList = this.$getStorage('collectDataList') || []
      let index = storageList.findIndex(item => item['id'] === this.cid)
      storageList.splice(index, 1)
      this.$removeStorage('collectDataList')
      this.$setStorage('collectDataList', storageList)
    },

    backPage() {
      this.$navToPage(
        {
          delta: 1
        },
        'navigateBack'
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.top-container {
  background: #ffffff;
  padding: 30rpx;
  .row {
    height: 36rpx;
    display: flex;
    align-items: center;
    margin-top: 20rpx;
    &:first-child {
      margin-top: 0;
    }
    .label {
      color: $sec-font;
      flex-shrink: 0;
      font-size: 28rpx;
    }
    .value {
      font-size: 28rpx;
    }
  }
}

.common-title {
  font-weight: 500;
  .star {
    color: $minor-color;
  }
  .tips {
    color: $assist-color;
    font-weight: normal;
    margin-left: 12rpx;
    font-size: 28rpx;
  }
}

.card-container {
  background: #ffffff;
  padding: 30rpx;
  margin-top: 30rpx;

  .title {
    .star {
      color: $minor-color;
    }
    .tips {
      color: $assist-color;
      font-weight: normal;
      margin-left: 12rpx;
      font-size: 28rpx;
    }
  }

  .row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 30rpx;
    .label {
      flex-shrink: 0;
    }
    .radio {
      display: flex;
      .item {
        width: 176rpx;
        height: 64rpx;
        background: #f4f5f9;
        border-radius: 8rpx;
        text-align: center;
        line-height: 64rpx;
        font-size: 32rpx;
        margin-left: 26rpx;
        &.active {
          background: $theme-color;
          color: #ffffff;
        }
      }
      ::v-deep .u-button {
        width: 176rpx;
        height: 64rpx;
        font-size: 32rpx;
        border-radius: 8rpx;
      }
    }
  }

  ::v-deep .u-textarea {
    background: #f4f5f9;
    margin-top: 20rpx;
  }

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

    .it {
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;
      margin-top: 30rpx;
      margin-right: 30rpx;

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

      .close {
        position: absolute;
        right: -20rpx;
        top: -20rpx;
        z-index: 99;
        width: 42rpx;
        height: 42rpx;
        background: $minor-color;
        color: #ffffff;
        text-align: center;
        line-height: 42rpx;
        border-radius: 50%;
        font-size: 28rpx;
      }

      image {
        width: 190rpx;
        height: 190rpx;
        background: #f4f4f7;
        border-radius: 20rpx;
        overflow: hidden;
      }

      .empty {
        width: 190rpx;
        height: 190rpx;
        border: 1px dashed #e5e5e5;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        position: relative;
        border-radius: 20rpx;
        overflow: hidden;

        .iconfont {
          font-size: 52rpx;
          color: $sec-font;
        }

        .text {
          margin-top: 12rpx;
          font-size: 28rpx;
          color: $sec-font;
        }
      }

      .name {
        margin-top: 24rpx;
        color: $sec-font;

        text {
          color: $minor-color;
        }
      }
    }
  }
}
.code {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20rpx;
  background: #f4f5f9;
  box-sizing: border-box;
  padding: 10px;
  border-radius: 3px;
  .btn {
    font-size: 32rpx;
    color: $theme-color;
    margin-left: 16rpx;
  }
}
</style>
