<template>
  <view>
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      title="备品备件登记"
      @clickLeft="back"
      right-icon="scan"
      @clickRight="handlscanCheck"
    >
    </uni-nav-bar>
    <view class="check-content">
      <uni-easyinput type="text" v-model="searchKey" placeholder="搜索关键字" />
      <view class="content-number">
        <span class="number-box">共 {{ allNumber }}</span>
        <span class="number-box">已选 {{ chooseNumber }}</span>
      </view>
      <checkbox-group
        v-for="(item, index) in showList"
        :key="index"
        @change="e => selectVal(e, item, index)"
      >
        <view class="groupbox">
          <view class="listBox">
            <view class="listBox-con">
              <view class="con-line">
                <view class="line-name">备件编码</view>
                <view class="line-value">{{ item.assetCode }}</view>
              </view>
              <view class="con-line">
                <view class="line-name">备件名称</view>
                <view class="line-value">{{ item.informationName }}</view>
              </view>
              <view class="con-line">
                <view class="line-name">单位</view>
                <view class="line-value">{{
                  item.isUnpack ? item.unit : item.minPackUnit
                }}</view>
              </view>
              <view class="con-line" v-if="!item.isUnpack">
                <view class="line-name">包装单元</view>
                <view class="line-value">
                  <uni-easyinput
                    type="number"
                    v-model.number="item.num"
                  ></uni-easyinput
                  >{{ item.unit }}/{{ item.minPackUnit }}</view
                >
              </view>
              <view class="con-line" v-if="!item.isUnpack">
                <view class="line-name">剩余</view>
                <view class="line-value">
                  {{ item.unusedNum }}
                  {{ item.unit }}</view
                >
              </view>
              <view class="con-line">
                <view class="line-name">规格/型号</view>
                <view class="line-value"
                  >{{ item.specification }}/{{ item.modelType }}</view
                >
              </view>
              <view class="con-line" v-if="item.selfDefinedParameter">
                <view
                  class="con-line"
                  v-for="(ite, ind) in JSON.parse(item.selfDefinedParameter)"
                  :key="ind"
                >
                  <view class="line-name">{{ ite.key }}</view>
                  <view class="line-value">{{ ite.value }}</view>
                </view>
              </view>
            </view>
            <view class="listBox-sel">
              <checkbox
                class="sel-checbox"
                :checked="item.status"
                color="#fff"
              />
            </view>
          </view>
        </view>
      </checkbox-group>
    </view>
    <view class="footer">
      <view class="btn" @click="back"> 取消 </view>
      <view class="btn primary" @click="handleSave"> 保存 </view>
    </view>
    <!-- <ScanCode @scancodedate="cbScancodedate" :model="'uni'"></ScanCode> -->
  </view>
</template>

<script>
import { get, post, postJ } from '@/utils/api.js'
import ScanCode from '@/components/ScanCode.vue'
export default {
  components: {
    ScanCode
  },
  data () {
    return {
      searchKey: '',
      listData: [],
      workOrderCode: '',
      workOrderId: '',
      equipmentCode: '',
      allNumber: 0,
      memoList: [],
      requestStatus: false,
      timer: null,
      originList: [],
      from: ''
    }
  },
  computed: {
    chooseNumber () {
      return this.memoList.length || 0
    },
    showList () {
      return this.listData.filter(
        ({ specification, modelType, assetCode, informationName }) => {
          if (this.searchKey) {
            return (
              (specification && specification.indexOf(this.searchKey) > -1) ||
              (modelType && modelType.indexOf(this.searchKey) > -1) ||
              (assetCode && assetCode.indexOf(this.searchKey) > -1) ||
              (informationName && informationName.indexOf(this.searchKey) > -1)
            )
          }

          return true
        }
      )
    }
  },
  onLoad (options) {
    this.from = options.from
    this.workOrderCode = options.workOrderCode
    this.workOrderId = options.workOrderId
    this.equipmentCode = options.equipmentCode
  },
  async onShow () {
    let _this = this
    if (this.from === 'maintain_service') {
      // 维修跳转
      await this.getUsedList()
    } else {
      this.originList = JSON.parse(
        this.$store.state.maintenance.sparePartsJson || '[]'
      ).map(item => {
        item.status = true
        return item
      })
      console.log(this.originList)
      this.memoList = uni.$u.deepClone(this.originList)
    }
    _this.getList()
    uni.$off('scancodedate') // 每次进来先 移除全局自定义事件监听器
    uni.$on('scancodedate', function (data) {
      _this.cbScancodedate(data)
    })
    // 如果有定时器，清除定时器
    if (this.timer) {
      clearTimeout(this.timer)
      this.timer = null
    }
  },
  onHide () {
    uni.$off('scancodedate')
  },
  onUnload () {
    uni.$off('scancodedate')
  },
  methods: {
    // 获取备品备件
    getUsedList () {
      let par = {
        sourceCode: this.workOrderCode
      }
      if (this.equipmentCode) {
        par.equipmentCode = this.equipmentCode
      }
      return postJ(
        this.apiUrl + `/sparePartsApply/getSparePartsExpendList`,
        par
      ).then(res => {
        if (res?.success) {
          this.originList = res.data.map(item => {
            item.status = true
            if (!item.isUnpack) {
              item.num = item.measurementUnit - item.unusedNum
            }
            return item
          })
          console.log(this.originList)
          this.memoList = uni.$u.deepClone(this.originList)
        }
      })
    },
    //勾选
    selectVal (e, val, index) {
      this.showList[index].status = !this.showList[index].status
      const idx = this.memoList.findIndex(
        item => item.assetCode === this.showList[index].assetCode
      )

      if (this.showList[index].status) {
        if (idx === -1) {
          this.memoList.push(this.showList[index])
        }
      } else {
        if (idx > -1) {
          this.memoList.splice(idx, 1)
        }
      }
    },
    handleSave () {
      let flag = false
      // 计算剩余
      const sparePartsExpendList = uni.$u
        .deepClone(this.listData)
        .map((item, index) => {
          item.status = !!this.memoList.find(i => i.id === item.id)
          if (!item.isUnpack) {
            if (item.status) {
              if (!item.num) {
                //  拆包输入
                uni.showToast({
                  title: `请输入${item.assetCode}登记数量`,
                  icon: 'none'
                })
                flag = true
                return false
              }
              item.unusedNum = item.unusedNum - item.num
              if (item.unusedNum < 0) {
                //  拆包输入
                uni.showToast({
                  title: `${item.assetCode}登记数量不能大院剩余数量`,
                  icon: 'none'
                })
                flag = true
                return false
              }
              item.status = item.unusedNum === 0
            } else {
              item.num = 0
              const obj = this.originList.find(i => i.id === item.id)
              if (obj) {
                // 保存过数据 退回
                item.unusedNum += obj.num
              }
            }
          }
          return item
        })
      if (flag) {
        return
      }
      this.memoList = sparePartsExpendList
        .filter(item => item.status || item.num)
        .map(item => {
          item.equipmentCode = this.equipmentCode

          return item
        })

      const params = {
        sparePartsExpendEquiList: [
          {
            equipmentCode: this.equipmentCode,
            sparePartsJson: JSON.stringify(this.memoList),
            workOrderId: +this.workOrderId
          }
        ],
        sparePartsExpendList
      }

      if (flag) {
        return
      }
      postJ(
        this.apiUrl + `/sparePartsApply/updateSparePartsExpend`,
        params
      ).then(res => {
        if (res?.success) {
          this.$store.commit(
            'maintenance/SET_SPAREPARTSJSON',
            params.sparePartsExpendEquiList[0].sparePartsJson
          )
          this.back()
        }
      })
    },
    back () {
      uni.navigateBack({
        delta: 1
      })
    },
    // 扫码
    /* HandlScanCode() {
				uni.navigateTo({
					url: '/pages/ScanCode/ScanCode'
				})
				//uni.$emit('scancode',{code:'null/w05000000130012/锤锤专用05-不拆-逐个/规格01/null/成型/null@_@0'})
			}, */
    // 扫码枪扫码
    cbScancodedate (data) {
      this.Scancodedate(data.code)
    },
    // 相机扫码
    handlscanCheck () {
      let _this = this
      uni.scanCode({
        success: function (res) {
          _this.Scancodedate(res.result)
        }
      })
    },
    Scancodedate (code) {
      this.qrContent = code.trim()
      //this.qrContent = 'null/w05000000130014/锤锤专用05-不拆-逐个/规格01/null/成型/null@_@0'
      this.barType = this.setBarType(this.qrContent)
      this.getData()
      //let res = await this.getScanCheckMate()
    },
    // 设置barType
    setBarType (val) {
      let arr = val.split('@_@')
      return (arr && arr[1]) || 0
    },
    // 根据条码请求设备数据
    getData () {
      let par = {
        barType: this.barType,
        qrContent: this.qrContent
      }
      console.log(par, 'par------------------')
      if (this.requestStatus) return
      postJ(this.apiUrl + '/scan/getAssetInfo', par).then(res => {
        let data = res.data
        let result = this.showList.find(item => {
          return item.assetCode == data.assetCode
        })
        console.log('匹配result', result)
        if (result) {
          if (result.status) {
            uni.showToast({
              title: '已选定，不可重复扫码！',
              icon: 'none',
              duration: 2000
            })
          } else {
            uni.showToast({
              title: '选定成功',
              icon: 'none',
              duration: 2000
            })

            result.status = true
            this.memoList.push(result)
          }
        } else {
          uni.showToast({
            title: '列表中无此备件！',
            icon: 'none',
            duration: 2000
          })
        }
        this.requestStatus = true
        this.timer = setTimeout(() => {
          this.requestStatus = false
        }, 500)
      })
    },

    getList (key) {
      let par = {
        sourceCode: this.workOrderCode
        // status: false ,
        // searchKey: key
        // equipmentCode: this.equipmentCode
      }
      postJ(this.apiUrl + `/sparePartsApply/getSparePartsExpend`, par).then(
        res => {
          if (res?.success) {
            this.listData = res.data
              .filter(i => !i.status)
              .map(i => {
                const obj = this.memoList.find(itm => itm.id == i.id)
                if (!i.isUnpack) {
                  return {
                    ...i,
                    num: obj?.num || '',
                    unusedNum: obj?.num ? i.unusedNum + obj?.num : i.unusedNum,
                    status: !!obj
                  }
                }
                return i
              })

            this.memoList.forEach(ele => {
              if (!this.listData.find(i => i.id === ele.id)) {
                this.listData.push({
                  ...ele,
                  unusedNum: ele.num,
                  num: ele.num
                })
              }
            })

            this.allNumber = res.data.length
            // this.listData.map(item => {
            //   if (item.status) {
            //     //this.chooseNumber = this.chooseNumber + 1
            //     this.memoList.push(item)
            //   }
            // })
          }
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.check-content {
  box-sizing: border-box;
  // height: calc(100vh - 88rpx);
  display: flex;
  flex-direction: column;
  padding: 20rpx 20rpx 120rpx;

  .content-number {
    width: 96%;
    text-align: right;
    margin: 16rpx auto;
    font-size: 28rpx;

    .number-box {
      display: inline-block;
      margin-left: 30rpx;
    }
  }

  .groupbox {
    border: 1rpx solid #ccc;
    display: block;
    padding: 20rpx 10rpx 20rpx 30rpx;
    margin-bottom: 20rpx;
  }

  .listBox {
    display: flex;
    justify-content: flex-start;
    position: relative;
    .listBox-sel {
      position: absolute;
      top: 0;
      right: 0;
    }

    .sel-checbox {
      zoom: 200%;
    }

    .listBox-con {
      width: 100%;

      .con-line {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        width: 100%;
        font-size: 28rpx;
        color: #666;

        .line-name {
          width: 180rpx;
          text-align: right;
          margin-right: 30rpx;
        }
        .uni-easyinput {
          display: inline-block;
          width: 200rpx;
          margin: 0 10rpx;
        }
      }

      .con-line:first-child {
        color: #000;
      }
    }
  }
}

.footer {
  height: 100rpx;
  display: flex;
  position: fixed;
  bottom: 0;
  width: 100vw;
  border: 1rpx solid $j-primary-border-green;
  background: #fff;

  .btn {
    display: flex;
    flex: 1;
    justify-content: center;
    align-items: center;
    border-radius: 0;

    &.primary {
      background-color: $j-primary-border-green;
      color: #fff;
    }
  }
}
</style>
