<template>
  <div>
    <p-modal title="序列号扫描" :visible="value" draggable destroyOnClose width="98%" :dialogStyle="{top:'50px'}"
             @cancel="unLockCancel" :footer="null">
      <a-row>
        <a-col :span="24">
          <!--订单表单-->
          <p-form-model :label-col='{ span: 8 }' :model='billForm'
                        :wrapper-col='{ span: 16 }' class='plg-grid-from'>
            <a-row>
              <a-col :span='6'>
                <p-form-model-item label='单据编号'>
                  <p-input v-model="billForm.refBillId" allowClear/>
                </p-form-model-item>
              </a-col>
              <a-col :span='6'>
                <p-form-model-item :wrapper-col='{ span: 16, offset: 8 }'>
                  <p-button type='primary' icon='search' @click='showUnLock'>解锁</p-button>
                  <p-button class='ml-10' icon='redo' @click='resetBillForm'>重置</p-button>
                </p-form-model-item>
              </a-col>
            </a-row>
          </p-form-model>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <!--明细表单-->
          <p-form-model :label-col='{ span: 8 }' :model='itemForm'
                        :wrapper-col='{ span: 16 }' class='plg-grid-from'>
            <a-row>
              <a-col :span='6'>
                <p-form-model-item label='明细编号'>
                  <p-input :value="itemForm.refBillLineId" disabled/>
                </p-form-model-item>
              </a-col>
              <a-col :span='6'>
                <p-form-model-item label='容器号'>
                  <p-input :value="itemForm.containerCode" disabled/>
                </p-form-model-item>
              </a-col>
              <a-col :span='6'>
                <p-form-model-item label='商品名称'>
                  <p-input :value="itemForm.itemName" disabled/>
                </p-form-model-item>
              </a-col>
              <a-col :span='6'>
                <p-form-model-item label='生产厂家'>
                  <p-input :value="itemForm.manufacturerName" disabled/>
                </p-form-model-item>
              </a-col>
              <a-col :span='6'>
                <p-form-model-item label='大包装数'>
                  <p-input :value="itemForm.maxSu" disabled/>
                </p-form-model-item>
              </a-col>
              <a-col :span='6'>
                <p-form-model-item label='中包装数'>
                  <p-input :value="itemForm.middleSu" disabled/>
                </p-form-model-item>
              </a-col>
            </a-row>
          </p-form-model>
        </a-col>
      </a-row>
      <a-row type="flex" :gutter="14">
        <a-col :span="14">
          <div class="panel-box">
            <!--待扫提醒-->
            <p-form-model :label-col='{ span: 12 }' :model='remindForm'
                          :wrapper-col='{ span: 12 }' class='plg-grid-from'>
              <a-row>
                <a-col :span='8'>
                  <p-form-model-item label='大包装个数'>
                    <p-input :value="remindForm.maxSu" disabled/>
                  </p-form-model-item>
                </a-col>
                <a-col :span='8'>
                  <p-form-model-item label='中包装个数'>
                    <p-input :value="remindForm.middleSu" disabled/>
                  </p-form-model-item>
                </a-col>
                <a-col :span='8'>
                  <p-form-model-item label='应扫'>
                    <p-input :value="remindForm.shouldScanQty" disabled/>
                  </p-form-model-item>
                </a-col>
                <a-col :span='8'>
                  <p-form-model-item label='实扫大包装数'>
                    <p-input :value="remindForm.maxScanedQty" disabled/>
                  </p-form-model-item>
                </a-col>
                <a-col :span='8'>
                  <p-form-model-item label='实扫中包装数'>
                    <p-input :value="remindForm.middleScanedQty" disabled/>
                  </p-form-model-item>
                </a-col>
                <a-col :span='8'>
                  <p-form-model-item label='实扫小包装数'>
                    <p-input :value="remindForm.minScanedQty" disabled/>
                  </p-form-model-item>
                </a-col>
                <a-col :span='8'>
                  <p-form-model-item label='剩余'>
                    <p-input :value="remindForm.customBillNum" disabled/>
                  </p-form-model-item>
                </a-col>
              </a-row>
            </p-form-model>
            <p-table
                ref="itemTableRef"
                :columns="itemColumns"
                :loading="loading"
                hasRowCount
                rowKey="refBillLineId"
                :rowClassName="rowClassName"
                :dataSource="itemDataSource"
                @clickRow="clickRow"
                dragle
                :scroll="{ y: 200, x: true }"
                :rowSelectType="false"
                border
            >
            </p-table>
          </div>
        </a-col>
        <a-col :span="2">
          <div class="panel-box panel-box-gap">
            <a-button @click="packLevelDisabledChange">重新选择规则</a-button>
            <a-radio-group @change="packLevelChange" v-model="packLevel" :disabled="packLevelDisabled">
              <!-- <a-radio value="0" style="margin: 10px" class="radio-item">大包装</a-radio>
              <a-radio value="1" style="margin: 10px" class="radio-item">中包装</a-radio> -->
              <a-radio value="2" style="margin: 10px" class="radio-item">小包装</a-radio>
            </a-radio-group>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="panel-box">
            <div class="scan-box">
              <p-input class="scan-box-input" placeholder='请扫描序列号' v-model="scanSupervisedCode"
                       size="large"
                       @pressEnter="handlerSubmit('', 'ipt')">
                <a-icon slot="prefix" type="scan"/>
              </p-input>
              <p-button type="primary" icon="scan" size="large" @click="handlerSubmit('', 'ipt')">
                确认扫码
              </p-button>
            </div>
            <p-table
                :columns="supervisedColumns"
                :loading="loading"
                hasRowCount
                dragle
                :dataSource="supervisedDataSource"
                rowKey="supervisionCode"
                :scroll="{ y: 200, x: true }"
                :rowSelectType="false"
                border
            />
          </div>
        </a-col>
      </a-row>
    </p-modal>
    <!-- 解锁 -->
    <p-modal title="解锁" :visible="unlockVisible" enlargeable draggable destroyOnClose
             @ok="unLockOk"
             @cancel="unLockCancel">
      <p-grid-form ref="gridUnlock" :span="24" :labelCol="{ span: 8 }" :items="unLockFormItems"/>
    </p-modal>
    <!-- 解锁账号校验 -->
    <!-- <workerLogin :loginVisible="loginVisible" @loginResult="loginResult" @handleCancel="handleCancels"/>-->
  </div>
</template>
<script>
import {tableColumnsConfig,tableColumns,itemsUnlock} from "../api/scanCode/lefttable";
import {addSupervisionCode, findCodesByBill, unlock} from "../api/scanCode";
import {extractSelectedRqcTask} from "../api/api";
// import workerLogin from './workerLogin.vue'

export default {
  components: {},
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    scanTable: {
      type: Array,
      default: () => [],
    },
    stage: {
      type: Number,
      required: true,
    },
    stagePackLevel: {
      type: String,
      default: '2'
    }
  },
  data() {
    return {
      loading: false,
      // 订单表单(解锁用)
      billForm: {},
      // 明细表单
      itemForm: {},
      // 待扫提醒表单
      remindForm: {},

      // 序列号扫描框
      scanSupervisedCode: '',
      // 当前扫描明细
      scanRecord: {},

      // 待扫明细列配置
      itemDataSource: [],
      itemColumns: tableColumnsConfig,
      // 已扫序列号列配置
      supervisedColumns: tableColumns,
      supervisedDataSource: [],

      // 解锁弹窗表单
      unLockFormItems: itemsUnlock,
      // 修改包装级别禁用
      packLevelDisabled: true,

      tableAIndex: 0,
      row_count: 0,
      packLevel: "2",
      packSize: 1,

      // 解锁账号校验弹窗
      loginVisible: false,
      // 解锁弹窗
      unlockVisible: false,
    };
  },
  computed: {
    warehouseId() {
      return this.$store.state?.user?.warehouse?.warehouseId || ''
    },
  },
  created() {
    this.getPendingScanData();
  },
  watch: {
    value(bool) {
      if (!bool) return;
      // 清空数据
      this.resetState()
      if (!this.scanTable?.length) {
        this.$message.error("该单所有商品,无需扫描药品追溯码")
        return
      }
      this.getPendingScanData()
    },
  },
  methods: {
    resetState() {
      this.supervisedDataSource = [];
      this.itemDataSource = [];
      this.scanRecord = {}
      this.billForm = {}
      this.itemForm = {}
      this.remindForm = {}
      this.scanSupervisedCode = ''
    },
    // 重置订单表单
    resetBillForm() {
      this.billForm = {}
    },
    rowClassName(record) {
      // 高亮样式
      if (this.tableAIndex > this.itemDataSource.length) return;
      return record.refBillLineId === this.itemDataSource[this.tableAIndex]?.refBillLineId ? "clickRowStyle" : "";
    },
    // 更新待扫明细数据
    getPendingScanData() {
      // 传入的待扫明细为空,清空数据
      if (!this.scanTable?.length) {
        this.itemDataSource = []
        return
      }
      this.loading = true
      extractSelectedRqcTask([...this.scanTable]).then(res => {
        if (res.success) {
          this.updateTable(res.data.list, this.scanTable);
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    updateTable(pendingScanList = [], scanTable) {
      //更新序列号最新数据
      const itemDataSource = [];
      pendingScanList.forEach((item) => {
        const hitItem = scanTable.find(_ => _.refBillLineId === item.refBillLineId)
        if (!hitItem) return
        item.pieceQty = hitItem.pieceQty
        item.packLevel = hitItem.packLevel || this.stagePackLevel
        item.uom = hitItem.uom
        item.manufacturerName = hitItem.manufacturerName || hitItem.manufacturerId
        item.specification = hitItem.itemSpecs
        item.caseQty = hitItem.uomQty
        item.oddPieceQty = hitItem.pickQty
        itemDataSource.push(item)
      });
      if (itemDataSource.length === 0) {
        this.$message.info('所选明细序列号已扫描完成!')
        return
      }
      this.itemDataSource = itemDataSource;
      this.billForm = {...this.itemDataSource[0]}
      this.clickRow(null, null, this.itemDataSource[0])
    },
    handleCancels() {
      this.loginVisible = false;
    },
    // 解锁弹窗回调
    showUnLock() {
      this.unlockVisible = true;
    },
    unLockOk() {
      this.$refs.gridUnlock.form.validateFields((err, values) => {
        if (err) return;
        unlock({...values, warehouseId: this.warehouseId}).then((res) => {
          if (res.success) {
            this.unlockVisible = false; //关闭解锁弹窗
            this.$emit("input", false);
            const params = {
              stage: this.stage,
              creator: values.workercode,
              creatorName: values.workercode,
              refBillId: this.scanTable[0].refBillId,
              unlock: 1,
              // 是否解锁插入
              isUnlock: 1,
            };
            addSupervisionCode(params).then((res) => {
              console.log(res);
              if (res.success) {
                this.$message.success("解锁成功!");
                // this.value = false //关闭序列号弹窗
                this.$emit("input", false);
              } else {
                this.$message.error(message);
              }
            });
            // if(this.$route.name=="零货拣货"){
            this.$bus.$emit("refreshData");
            // }
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    unLockCancel(e) {
      this.unlockVisible = false; //关闭解锁弹窗
      this.tableAIndex = 0;
      this.$emit("input", false);
    },
    // 扫描序列号
    handlerSubmit() {
      const scanSupervisedCode = this.scanSupervisedCode
      console.log('this.scanSupervisedCode', this.scanSupervisedCode)
    //   if (scanSupervisedCode?.length !== 20) {
    //     this.scanSupervisedCode = ''
    //     this.$message.warning('序列号长度需要为20位!')
    //     return
    //   }
      if (!this.scanRecord.pieceQty) {
        this.scanSupervisedCode = ''
        this.$message.warning('当前商品不需要扫描序列号！');
        return;
      }
      const packLevel = this.packLevel;
      const packSize = this.packSize;
      const params = {
        ...this.scanRecord,
        packLevel,
        packSize,
        supervisionCode: scanSupervisedCode,
      };
      const {refBillId, refBillLineId} = this.scanRecord
      params.refBillId = refBillId
      params.refBillLineId = refBillLineId
      // 业务类型：businessType 0采购入库， 1 销售退货 ，2 销售出库， 3 采购退货，4货主转换"
      params.businessType = 2;
      params.packSize = '1'
      params.stage = this.stage;
      params.codeType='3'
      console.log(params, "params");
      addSupervisionCode(params).then((res) => {
        this.scanSupervisedCode = ''
        if (!res.success) {
          this.$exception(res);
          return;
        }
        if (res.data.complete) {
          if (this.itemDataSource.length == 1 || this.row_count == this.itemDataSource.length) {
            // this.$message.warn('序列号已全部扫描完毕！',5);
            this.$emit("input", false);
          }
          // 当前行商品已经扫描完成
          this.tableAIndex += 1;
          if (this.tableAIndex < this.itemDataSource.length) {
            this.$message.warning(`第${this.tableAIndex}行商品已扫描完成！`);
            this.clickRow(null, null, this.itemDataSource[this.tableAIndex]);
            return;
          }
        }
        // 录入成功,更新待扫数量
        // 0大包装，1中包装，2小包装
        this.packLevel = res.data.packLevel || this.stagePackLevel
        this.supervisedDataSource = res.data?.superviseCodesModal || []

        this.calculateRemind();
        // 扫码剩余为0，表示全部扫完
        const {customBillNum} = this.remindForm
        if (!customBillNum) {
          this.$message.warn("序列号已全部扫描完毕！", 5);
          this.$emit('input', false)
        }
        console.log("序列号this.supervisedDataSource.push:", this.supervisedDataSource);
      });
    },
    clickRow(selectedRowKeys, key, record) {
      const tableAIndex = this.itemDataSource.findIndex(_ => _.refBillLineId === key)
      this.tableAIndex = tableAIndex !== -1 ? tableAIndex : this.tableAIndex
      this.$refs.itemTableRef.reload(); //更新高亮
      const {packLevel} = record
      this.scanRecord = record;
      this.itemForm = {...record}
      this.row_count = record._row_count;
      this.scanRecord = record;
      // 获取已扫码序列号列表
      this.loading = true
      findCodesByBill({refBillId: record.refBillId, refBillLineId: record.refBillLineId,}).then((res) => {
        if (res.success) {
          let {
            maxScanedQty = 0,
            middleScanedQty = 0,
            minScanedQty = 0,
            superviseCodesModal = [],
          } = res.data || {}
          this.supervisedDataSource = superviseCodesModal || []

          this.remindForm = {...this.remindForm, maxScanedQty, middleScanedQty, minScanedQty}
          this.packLevel = this.stagePackLevel
          console.log('stagePackLevel', this.stagePackLevel)
          this.calculateRemind()
        } else {
          this.$exception(res);
        }
      }).finally(() => {
        this.loading = false
      })
    },
    // 修改包装级别
    packLevelChange(e) {
      if (e.target.value) {
        this.packLevelDisabled = true
      }
      this.calculateRemind();
    },
    // 修改包装级别禁用
    packLevelDisabledChange() {
      this.packLevelDisabled = false;
    },
    // 修改包装级别,更新待扫量
    calculateRemind() {
      const packLevel = String(this.packLevel || this.stagePackLevel)
      let {pieceQty, maxSu, middleSu, minSu} = this.scanRecord
      const supervisedDataSource = this.supervisedDataSource
      maxSu = Number(maxSu || 0)
      minSu = Number(minSu || 0)
      middleSu = Number(middleSu || 0)
      let maxScanedQty = 0
      let middleScanedQty = 0
      let minScanedQty = 0
      supervisedDataSource?.forEach(item => {
        if (item.packLevel === '0') {
          maxScanedQty++
          return
        }
        if (item.packLevel === '1') {
          middleScanedQty++
          return
        }
        if (item.packLevel === '2') {
          minScanedQty++
          return
        }
      })
      pieceQty = Number(pieceQty || 0)
      if (packLevel === '0') this.packSize = maxSu
      if (packLevel === '1') this.packSize = middleSu
      if (packLevel === '2') this.packSize = minSu

      const shouldScanQty = pieceQty
      // console.log('this.remindForm', this.remindForm)
      const customBillNum = pieceQty - (maxSu * maxScanedQty + middleSu * middleScanedQty + minScanedQty * minSu);
      this.remindForm = {
        ...this.remindForm,
        maxSu,
        middleSu,
        minSu,
        maxScanedQty,
        middleScanedQty,
        minScanedQty,
        customBillNum,
        shouldScanQty
      }
      return
    }
  },
};
</script>
<style lang="less" scoped>
.scan-box {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px 0;

  .scan-box-input {
    width: 260px;
    margin-right: 10px;
  }
}

.panel-box {
  border: 1px solid #dcdfe6;
  height: 400px;
  padding: 12px;

  &.panel-box-gap {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-direction: column;
  }

  .radio-item {
    display: block
  }
}

/deep/ .clickRowStyle, /deep/ .p-table tr.active {
  td {
    background-color: #00b4ed !important;
  }
}
</style>
