<template>
  <div class="replenishment-start-set-stock-dialog  ">
    <van-popup v-model="value" close-on-popstate :close-on-click-overlay="false">
      <div class="plr15 ptb10 c-pr" style="width: 80vw">
        <div class="close fs-20"><van-icon @click="emitValue(false)" name="close" /></div>
        <div class="tc fs-14 c-333">
          <span>{{ bussiness == 1 ? '修改容量' : bussiness == 2 ? '矫正库存' : bussiness == 4 || bussiness == 5 ? '设置库存' : bussiness == 6 ? '新增' : '' }}</span>
        </div>
        <template v-if="bussiness == 1 || bussiness == 4 || bussiness == 5 || bussiness == 6">
          <div class="tc pt30 pb20"><van-stepper v-model="stock" min="1" :max="bussiness == 4 ? data.cargoCapacity : 99" button-size="36px" input-width="60px" /></div>
        </template>
        <div class="tc" v-else>
          <div class="pt10">
            <van-image radius="5px" :src="require('@/assets/images/drug_default.png')" />
          </div>
          <div class="pt10 c-333 fs-16">{{ data.drugName }}</div>
          <div class="pt10 c-999">软件显示库存：{{ data.qty }}</div>
          <div class="pt10 pb20 ipt plr50">
            <div class="tc  ">
              <van-stepper placeholder="实际库存" v-model="stock" min="1" :max="data.cargoCapacity" button-size="36px" input-width="60px" @change="changeStock" />
            </div>
          </div>
        </div>
        <div v-if="bussiness != 4">
          <div class="title mb8">
            <span>药品追溯码（</span>
            <span class="c-17b3ec">{{ fillNum }}</span>
            <span>/{{ stock }}）</span>
          </div>
          <div class="code-box">
            <codeList :codeList="newCodeList" :qty="data.qty" :stock="stock" :bussiness="bussiness" @scan="scan"></codeList>
          </div>
        </div>
        <div class="ptb10">
          <van-button type="info" @click="confirm" size="small" block>确认</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import medicineAbinetApi from '@/api/api-medicineAbinet'
import codeList from './codeList.vue'
export default {
  components: {
    codeList
  },
  props: {
    value: {},
    bussiness: {
      default: 1 //1修改容量 2矫正库存 4设置库存 5选择药品后 设置库存  6备药时选择药品
    },
    data: {
      default: function() {
        return {}
      }
    },
    trackId: { default: '' },
    deviceId: { default: '' },
    drugId: { default: '' },
    codeList: {
      type: Array,
      default: () => {
        return []
      }
    },
    inventoryObj: {
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      stock: 1,
      keyword: '',
      items: [],
      newCodeList: [],
      init: true
    }
  },
  computed: {
    fillNum() {
      let num = 0
      this.newCodeList.forEach(el => {
        if (el.code) {
          num++
        }
      })
      return num
    }
  },
  watch: {
    value: {
      handler(val) {
        if (this.init && val) {
          // 如果是初始化 则赋值。解决扫码回来这个地方重复调用的问题
          this.stock = this.bussiness == 1 ? this.data.cargoCapacity : this.data.qty
          console.log(this.codeList, 'this.codeList')
          this.newCodeList = JSON.parse(JSON.stringify(this.codeList))

          this.init = false
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.$EventBus.$on('getScanData', item => {
      this.newCodeList = item.codeList
    })
  },
  beforeDestroy() {
    this.$EventBus.$off('getScanData')
  },
  created() {},
  methods: {
    confirm() {
      const codeList = []
      this.newCodeList.forEach((el, index) => {
        codeList.push({
          code: el.code,
          sort: this.newCodeList.length - index
        })
      })
      let p = {
        id: this.trackId,
        userId: this.user.id,
        codeStr: JSON.stringify(codeList)
      }
      if (this.bussiness == 1) {
        //修改容量
        if (this.fillNum > this.stock) {
          this.$toast('追溯码数量不能大于容量')
          return
        }

        p.cargoCapacity = this.stock
        medicineAbinetApi.updateMediicinecabineInventoryInfoById(p).then(res => {
          this.emitValue(false)
          this.$toast.clear()
          this.$emitRefreshPage('replenishmentStartDeviceDetail')
          // history.back()
          this.$emit('refresh')
        })
      } else if (this.bussiness == 2) {
        // 矫正库存
        if (this.fillNum != this.stock * 1) {
          this.$toast('追溯码数量必须等于库存')
          return
        }
        p.drugId = this.drugId
        p.qty = this.stock
        medicineAbinetApi
          .updateMediicinecabineInventory(p)
          .then(res => {
            this.emitValue(false)
            this.$toast.clear()
            this.$emitRefreshPage('replenishmentStartDeviceDetail')
            // history.back()
            this.$emit('refresh')
          })
          .catch(err => {
            console.error(err)
          })
      } else {
        if (this.bussiness == 4) {
          // 更换商品
          this.$router.push({
            path: '/replenishment/start/traceability',
            query: {
              deviceId: this.deviceId,
              trackId: this.trackId,
              drugId: this.drugId,
              stock: this.stock,
              type: 3
            }
          })
          return
        }
        if (this.trackId) {
          this.updateMediicinecabineInventory()
          return
        }

        this.$emit('onConfirm', { stock: this.stock, codeList: this.newCodeList })
        this.emitValue(false)
      }
    },
    emitValue(show) {
      this.init = true
      this.$emit('input', show)
    },
    updateMediicinecabineInventory(data) {
      this.$loading('保存中..')
      const codeList = []
      this.newCodeList.forEach((el, index) => {
        codeList.push({
          code: el.code,
          sort: this.newCodeList.length - index
        })
      })
      let p = {
        id: this.trackId,
        drugId: this.drugId,
        qty: this.stock,
        userId: this.user.id,
        codeStr: JSON.stringify(codeList)
      }

      medicineAbinetApi
        .updateMediicinecabineInventory(p)
        .then(res => {
          this.setStockShow = false
          this.$toast.clear()
          this.$emitRefreshPage('replenishmentStartDeviceDetail')
          history.back()
        })
        .catch(err => {
          console.error(err)
        })
    },
    changeStock(val) {
      if (val > this.newCodeList.length) {
        this.newCodeList.push({
          code: ''
        })
      } else if (val < this.newCodeList.length) {
        if (!this.newCodeList[this.newCodeList.length - 1].code) {
          this.newCodeList.pop()
        }
      }
    },
    scan(data) {
      sessionStorage.setItem('scanData', JSON.stringify({ ...data, codeList: this.newCodeList, ...this.inventoryObj }))
      this.$router.push({
        path: '/replenishment/start/scan'
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.replenishment-start-set-stock-dialog {
  .close {
    position: absolute;
    right: 10px;
    top: 10px;
  }
  //   ::v-deep .van-field {
  //     padding: 0;
  //     .van-cell__value {
  //       border: 1px solid #e1e1e1;
  //       input {
  //         text-align: center;
  //       }
  //     }
  //   }
  .van-image {
    width: 200px;
    height: 150px;
  }
  .scan {
    position: absolute;
    right: 36px;
    top: 50%;
    transform: translateY(-50%);
  }
  .drag {
    width: 20px;
    height: 20px;
  }
}
::v-deep {
  .van-field__label {
    color: #999;
    width: 60px;
    margin-right: 0;
  }
  .van-field__control {
    padding-right: 15px;
  }
}
</style>
