<template>
  <div>
    <p-modal
      title="扫描"
      :visible="modelVal"
      :dialogStyle="{ top: '50px' }"
      :draggable="true"
      :width="'98%'"
      @cancel="handleCancel"
      :destroyOnClose="true"
      :footer="null"
    >
      <div style="overflow-x: auto; winth: 100%">
        <p-grid-form ref="gridItems" :items="gridItems" :labelCol="{ span: 5 }" :span="4" @submit="hanlderIsLock">
        </p-grid-form>
        <p-grid-form ref="showFormItems" :items="showFormItems" :labelCol="{ span: 5 }" :span="4"> </p-grid-form>
      </div>

      <a-row>
        <div>
          <a-col :span="12" class="left-a">
            <p-grid-form :items="leftItems" ref="leftItems" :labelCol="{ span: 5 }" :span="4" @submit="hanlderSubmit">
            </p-grid-form>
            <p-table
              :columns="columns"
              :has-row-count="true"
              row-key="taskRqcId"
              :data-source.sync="tableA"
              :selectedRowKeys.sync="scanlist"
              @clickRow="clickRow"
              dragle
              auto-width
              :scroll="{ y: 200, x: 200 }"
              :rowSelectType="false"
              border
            >
            </p-table>
          </a-col>
        </div>

        <div>
          <a-col :span="2" class="left-a" style="overflow-x: auto; winth: 100%">
            <a-button style="margin: 10px" @click="radioBtn">重新选择规则</a-button>
            <div label="packLevel">
              <a-radio-group @change="radioPack" v-model="packLevel" :disabled="radioDisabled">
                <a-radio value="0" style="margin: 10px"> 大包装 </a-radio>
                <a-radio value="1" style="margin: 10px"> 中包装 </a-radio>
                <a-radio value="2" style="margin: 10px"> 小包装 </a-radio>
              </a-radio-group>
            </div>
          </a-col>
        </div>

        <div>
          <a-col :span="10" class="left-a">
            <p-grid-form
              ref="rightItems"
              :items="rightItems"
              :labelCol="{ span: 5 }"
              :span="4"
              @submit="hanlderSubmit"
              style="margin: 20px"
            >
            </p-grid-form>
            <p-table-edit-pro
              ref="tableB"
              :columns="tableColumns"
              :has-row-count="true"
              dragle
              auto-width
              :data-source.sync="tableB"
              rowKey="supervisionCode"
              :scroll="{ y: 200, x: 200 }"
              style="margin-top: 20px"
              :rowSelectType="false"
              border
            >
            </p-table-edit-pro>
          </a-col>
        </div>
      </a-row>
    </p-modal>
    <workerLogin
      :loginVisible="loginVisible"
      :isSupervisedData="isSupervisedData"
      @loginResult="loginResult"
      @handleCancel="handleCancels"
    ></workerLogin>
  </div>
</template>
<script>
import { setFormItems, showFormItems } from '../config/scanCode/gridform'
import { leftItems, tableColumnsConfig } from '../config/scanCode/lefttable'
import { rightItems, tableColumns } from '../config/scanCode/righttable'
import { addSupervisionCode, findCodesByBill } from '../api'
import workerLogin from '../components/workerLogin.vue'

export default {
  components: { workerLogin },

  props: {
    value: {
      type: Boolean,
      default: false,
    },
    scanTable: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      modelVal:false,
      gridItems: setFormItems,
      showFormItems: showFormItems,
      leftItems: leftItems(this),
      columns: tableColumnsConfig,
      rightItems: rightItems(this),
      tableColumns: tableColumns,
      tableA: [],
      tableB: [],
      scanlist: [],
      packLevel: '0',
      selectRow: {},
      loginVisible: false,
      radioDisabled: true,
      rows: {},
      stage: 0,
      isSupervisedData: {},
      complete: 0,
    }
  },
  created() {},
  mounted() {},
  watch: {
    value(bool) {
      if (bool) {
        this.modelVal = bool
        this.tableA = []
        if (this.scanTable.length === 0) {
          this.$message.error('该单所有商品，无需扫描药品追溯码')
        } else if (this.scanTable) {
          this.tableA = [...this.scanTable]
          this.$nextTick(() => {
            this.$refs.gridItems.form.setFieldsValue(this.tableA[0])
            this.$refs.gridItems.form.setFieldsValue({ refBillId: this.tableA[0].rcvHeaderId })
            this.$refs.gridItems.form.setFieldsValue({ refBillLineId: this.tableA[0].rcvLineId })
            this.clickRow(null, null, this.tableA[0])
            this.billNum()
            // 数量 < 大包装数 (规格取小包装数)
            let res = this.tableA[0]
            this.$nextTick(() => {
              if (+res.pieceQty < +res.maxSu) {
                this.packLevel = '2'
              } else {
                this.packLevel = '0'
              }
            })
          })
        }
      }
    },
    // // 监测剩余数量
    // customBillNum2(newVal) {
    //   if (newVal === 0) {
    //     this.$message.warning("商品已全部扫描完成")
    //   }
    // },
  },
  methods: {
    handleCancel(e) {
      this.modelVal = false 
      this.$emit('input', false)
      this.tableB = []
      // this.destroyOnClose = true
    },
    handleCancels() {
      this.loginVisible = false
    },
    loginResult(data, value) {
      this.loginVisible = false
      // this.loginVisible = data
      const params = {
        stage: this.stage,
        creator: data.userId,
        creatorName: data.username,
        refBillId: this.scanTable[0].rcvHeaderId,
        unlock: 1,
      }
      addSupervisionCode(params).then((res) => {
        if (res.success) {
          this.$message.success('解锁成功!')
          this.modelVal = false //关闭监管码弹窗
        } else {
          this.$message.error(message)
        }
      })
    },

    // 解锁
    hanlderIsLock(e, form) {
      e.preventDefault()
      this.loginVisible = true
      let warehouse = this.$store.state.user.warehouse
      this.isSupervisedData = {
        specialWorkType: '入库监管码解锁',
        warehouseId: warehouse.warehouseId,
      }
    },

    //回车事件
    //(warehouseAreaCategorys) businessType=0 (rcvType)billType=1
    hanlderSubmit(e, form) {
      e.preventDefault()
      let code = this.$refs.rightItems.form.getFieldsValue().supervisionCode
      let testCode = /^8\d{19}$/.test(code)
      if (!testCode) {
        this.$message.warning(this.$lang('请检查药品追溯码,格式必须是8开头并且长度为20位'))
        return
      }
      this.selectRow.packLevel = this.packLevel
      let forItem = this.$refs.showFormItems.form.getFieldsValue()
      const params = { supervisionCode: +code, ...this.selectRow, ...forItem }

      params.refBillId = this.selectRow.rcvHeaderId
      params.refBillLineId = this.selectRow.rcvLineId
      params.businessType = 0
      if (this.selectRow.packLevel === '0') {
        params.packSize = this.selectRow.maxSu
      } else {
        params.packSize = this.selectRow.middleSu
      }

      // 扫码阶段：0=入库质检 1=PC拣货 2=PC内复核 3=PC外复核 4=补录 5=PDA拣货 6=PDA内复核 7=PDA外复核
      params.stage = this.stage
      params.billType = this.selectRow.rcvType
      addSupervisionCode(params).then((res) => {
        this.$refs.rightItems.form.resetFields()
        if (!res.success) {
          this.$exception(res)
          return
        }
        if (!res.data) {
          return
        }
        //0大包装，1中包装，2小包装
        if (this.packLevel === '0') {
          this.$nextTick(() => {
            this.$refs.leftItems.form.setFieldsValue({
              maxSu: +this.$refs.leftItems.form.getFieldsValue().maxSu + 1,
              // customBillNum: +this.$refs.leftItems.form.getFieldsValue().customBillNum - 1,
            })
          })
        } else if (this.packLevel === '1') {
          this.$nextTick(() => {
            this.$refs.leftItems.form.setFieldsValue({
              middleSu: +this.$refs.leftItems.form.getFieldsValue().middleSu + 1,
              // customBillNum: +this.$refs.leftItems.form.getFieldsValue().customBillNum - 1,
            })
          })
        } else if (this.packLevel === '2') {
          this.$nextTick(() => {
            this.$refs.leftItems.form.setFieldsValue({
              minSu: +this.$refs.leftItems.form.getFieldsValue().minSu + 1,
              // customBillNum: +this.$refs.leftItems.form.getFieldsValue().customBillNum - 1,
            })
          })
        }
        this.billNum()
        this.$nextTick(() => {
          let customBillNum2 = this.$refs.leftItems.form.getFieldsValue().customBillNum
          // 监测剩余数量
          if (customBillNum2 === 0) {
            this.$message.warning('此商品已全部扫描完成')
          }
        })
        this.$refs.tableB.createRow(0, {
          supervisionCode: code,
          itemName: this.selectRow.itemName,
        })

        if (res.data.complete) {
          ++this.complete
        }
        if (this.complete === this.tableA.length) {
          this.$emit('input', false)
        }
      })
    },

    clickRow(selectedRowKeys, key, row) {
      this.rows = row
      this.$nextTick(() => {
        let val = +this.packLevel
        this.radioCheck(val)
        this.$refs.showFormItems.form.setFieldsValue(row)
      })
      this.selectRow = row

      //获取已扫码监管码列表
      findCodesByBill({
        refBillId: row.rcvHeaderId,
        refBillLineId: row.rcvLineId,
      }).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.tableB = []
        let _this = this
        // this.$nextTick(() => {
        if (!res.data) {
          return
        }
        if (res.data.packLevel === '0') {
          this.$nextTick(() => {
            this.$refs.leftItems.form.setFieldsValue({ maxSu: res.data.superviseCodes.length })
          })
        } else if (res.data.packLevel === '1') {
          this.$nextTick(() => {
            this.$refs.leftItems.form.setFieldsValue({ middleSu: res.data.superviseCodes.length })
          })
        } else if (res.data.packLevel === '2') {
          this.$nextTick(() => {
            this.$refs.leftItems.form.setFieldsValue({ minSu: res.data.superviseCodes.length })
          })
        }
        this.billNum()
        this.tableB = res.data.superviseCodes.map((tt) => ({ supervisionCode: tt, itemName: _this.selectRow.itemName }))
        // res.data.packLevel
        // console.log(this.tableB.length, 'this.tableB')
        // this.$refs.leftItems.form.setFieldsValue({
        //   customBillNum: +this.$refs.leftItems.form.getFieldsValue().customBillNum - this.tableB.length,
        // })
        // res.data.forEach((tt) => {
        //   //
        //   console.log(tt,'tt');

        //   this.$nextTick(() => {
        //     _this.$refs.tableB.createRow(0, {
        //       supervisionCode: tt,
        //       itemName: _this.selectRow.itemName,
        //     })
        //   })
        // })
      })
    },
    //规则
    radioPack(p1) {
      //（数量 pieceQty /大包装数 maxSu） +  数量 pieceQty % 大包装数 maxSu
      //（数量 pieceQty /中包装数 middleSu +  数量 pieceQty % 中包装数 middleSu
      if (p1.target.value) {
        this.radioDisabled = true
      }
      let val = +this.packLevel
      this.radioCheck(val)
    },
    //单选框校验规则
    radioCheck(val) {
      //大包装
      //应扫 shouldScanQty （数量 pieceQty /包装数 maxSu） +  数量 pieceQty % 包装数 maxSu
      //剩余 customBillNum (应扫-（应扫大包装 + 应扫中包装 + 应扫小包装）)
      this.$nextTick(() => {
        let ref = this.$refs.showFormItems.form.getFieldsValue()
        if (val === 0) {
          this.$refs.leftItems.form.setFieldsValue({
            shouldScanQty: parseInt(+(this.rows.pieceQty / ref.maxSu) + (+this.rows.pieceQty % ref.maxSu)),
          })
        } else if (val === 1) {
          this.$refs.leftItems.form.setFieldsValue({
            shouldScanQty: parseInt(+(this.rows.pieceQty / ref.middleSu) + (+this.rows.pieceQty % ref.middleSu)),
          })
        } else if (val === 2) {
          this.$refs.leftItems.form.setFieldsValue({
            shouldScanQty: parseInt(+(this.rows.pieceQty / 1) + (+this.rows.pieceQty % 1)),
          })
        }
      })
    },
    // 剩余数量取值
    billNum() {
      // 剩余= 应扫-（大包装+中包装+小包装）
      this.$nextTick(() => {
        setTimeout(() => {
          let result = this.$refs.leftItems.form.getFieldsValue()
          this.$refs.leftItems.form.setFieldsValue({
            customBillNum:
              parseInt(result.shouldScanQty) -
              (parseInt(result.maxSu) + parseInt(result.middleSu) + parseInt(result.minSu)),
          })
        }, 1000)
      })
    },
    //重新选择规则
    radioBtn() {
      this.radioDisabled = false
    },
  },
}
</script>
<style lang="less" scoped>
.left-a {
  border: 1px solid #dcdfe6;
  height: 400px;
}
</style>