<template>
  <div>
    <el-form :model="filterQuery" class="order-el-form" ref="formData" label-width="120px" @submit.native.prevent>
      <el-card>

        <!--  <el-alert-->
        <!--  style="margin-top: 15px"-->
        <!--  :title="msgTip"-->
        <!--  :closable="false"-->
        <!--  type="warning">-->
        <!--</el-alert>-->

        <el-row :gutter="0" style="margin-top: 15px">
          <el-col :span="24" align="right">
            <el-button-group>
              <el-button
                type="primary"
                :disabled="orderData.billNo"
                @click.native="selectPrescribe()"
              >选单
              </el-button>
              <el-button
                type="primary"
                :disabled="!orderData.billNo"
                @click.native="cancelOrder()"
              >放弃
              </el-button>
              <el-button
                type="primary"
                :disabled="!orderData.billNo"
                @click.native="confirmCheckOrder()"
              >完成
              </el-button>

              <!--              <el-dropdown @command="handleCommand">-->
              <!--                <el-button type="primary">-->
              <!--                  更多功能<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
              <!--                </el-button>-->
              <!--                <el-dropdown-menu slot="dropdown">-->
              <!--                  <el-dropdown-item divided @click.native="handleClickOut('IoCreateOrderBlank')">工位上货</el-dropdown-item>-->
              <!--                  <el-dropdown-item divided @click.native="handleClickReturn('IoCreateOrderBlank')">工位退货-->
              <!--                  </el-dropdown-item>-->
              <!--                  <el-dropdown-item divided @click.native="handleClick('ioSplitFifoCodeBlank')">工位存量</el-dropdown-item>-->
              <!--                  <el-dropdown-item divided @click.native="handleClick('CollectOrderAllotBlank')">待处理单-->
              <!--                  </el-dropdown-item>-->
              <!--                  <el-dropdown-item divided @click.native="handleClick('CollectOrderEndBlank')">已完成单</el-dropdown-item>-->
              <!--                </el-dropdown-menu>-->
              <!--              </el-dropdown>-->
            </el-button-group>
          </el-col>
        </el-row>


        <div style="border: 1px solid #ebeef5;border-radius: 2px;margin-top: 15px;padding: 15px"
             v-loading="this.loading">
          <el-row :gutter="0" style="margin-top: 5px">
            <el-col :span="20">
              <el-form-item prop="code" :label="scanTip" label-width="80px">
                <el-input
                  id="inputer"
                  @focus="getInputFocus($event)"
                  @keypress.enter.native="enterKey($event)"
                  ref="inputRef"
                  style="ime-mode: disabled"
                  type="tel"
                  :placeholder="this.placeholder"
                  v-model="scanCode"
                ></el-input>
                <!--                       :disabled="scanDisabled"-->
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button-group style="display: flex;">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-search"
                  @click.native.stop="enterKey($event)"
                  style="margin-left: 15px"
                >
                </el-button>
                <!-- :disabled="!formData.billNo ||  (this.formDataVisible != null &&  this.formDataVisible.scanType == 1)"-->
                <el-button type="primary"
                           @click="addGs"
                >ALT+29
                </el-button>
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-delete"
                  @click.native.stop="init()"
                >清空
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
          <el-alert
            v-if="successVisible"
            :title="scanTitle"
            :type="scanResultType"
            :closable="false"
            :dangerouslyUseHTMLString="true"
            :description="result"
          >
          </el-alert>
          <!--<el-alert-->
          <!--  v-if="warnVisible"-->
          <!--  title="警告信息:"-->
          <!--  type="warning"-->
          <!--  :closable="true"-->
          <!--  :dangerouslyUseHTMLString="true"-->
          <!--  :description="warnResult">-->
          <!--</el-alert>-->
          <el-alert
            v-if="errVisible"
            title="错误信息:"
            type="error"
            :closable="false"
            :dangerouslyUseHTMLString="true"
            :description="errResult"
          >
          </el-alert>

        </div>
        <el-descriptions title="单据信息" :column="4" border style="margin-top: 15px">
          <el-descriptions-item label="业务单号">{{ orderData.billNo }}</el-descriptions-item>
          <el-descriptions-item label="发货方">{{ orderData.shipperName }}</el-descriptions-item>
          <el-descriptions-item label="收货方">{{ orderData.fromCorpName }}</el-descriptions-item>
          <el-descriptions-item label="单据类型">{{ orderData.busTypeName }}</el-descriptions-item>
          <el-descriptions-item label="来源系统">{{ orderData.fromType }}</el-descriptions-item>
          <el-descriptions-item label="单据时间">{{ orderData.billTime }}</el-descriptions-item>
          <el-descriptions-item label="单据备注">{{ orderData.remark }}</el-descriptions-item>
        </el-descriptions>
      </el-card>


      <el-tabs type="border-card" style="margin: 15px">
        <!--单据业务详情-->

        <el-tab-pane>
          <span slot="label">单据 {{ orderData.billNo }}-业务详情</span>
          <el-table :data="busDataList" style="width: 100%;" highlight-current-row="true" border ref="multipleTable"
                    :row-style="rowStyleBiz"
          >
            <el-table-column label="序号" type="index"></el-table-column>
            <el-table-column label="产品通用名" prop="cpmctymc" width="160"></el-table-column>
            <el-table-column label="制剂规格" prop="prepnSpec" width="160"></el-table-column>
            <el-table-column label="包装规格" prop="spec" width="100"></el-table-column>
            <!--            <el-table-column label="扫码数量" prop="scanActCount" width="80"></el-table-column>-->
            <!--            <el-table-column label="单据数量" prop="count" width="80"></el-table-column>-->
            <!-- 扫码数量列 -->
            <el-table-column label="扫码实际数量" width="100">
              <template slot-scope="scope">
        <span :style="getScanActCountStyle(scope.row)">
          <strong>{{ scope.row.scanActCount }}</strong>
        </span>
              </template>
            </el-table-column>
            <!-- 单据数量列 -->
            <el-table-column label="单据数量" prop="count" width="80">
              <template slot-scope="scope">
                <strong>{{ scope.row.count }}</strong>
              </template>
            </el-table-column>

            <el-table-column label="批次号" prop="batchNo"></el-table-column>
            <el-table-column label="生产日期" prop="productDate" width="80"></el-table-column>
            <el-table-column label="失效日期" prop="expireDate" width="80"></el-table-column>
            <el-table-column label="批准文号" prop="zczbhhzbapzbh"></el-table-column>
            <el-table-column label="生产厂家" prop="manufactory"></el-table-column>
            <el-table-column label="医保编码" prop="ybbm"></el-table-column>
            <el-table-column label="药品编码" prop="nameCode"></el-table-column>
          </el-table>
          <el-row style="text-align: right;font-size: 12px;margin-top: 10px">
            <el-col span="24">
              <div style="float: right">
                <td>
                  <div style="background-color: #F56C6C;width: 10px;height: 10px;"></div>
                </td>
                <td>
                  <span style="color: #6d6d6d; "><pre>未扫码  </pre></span>
                </td>
                <td>
                  <div style="background-color: #E6A23C;width: 10px;height: 10px;"></div>
                </td>
                <td>
                  <span style="color: #6d6d6d;"><pre>部分扫码  </pre></span>
                </td>


                <td>
                  <div style="background-color: #67C23A;width: 10px;height: 10px;"></div>
                </td>
                <td>
                  <span style="color: #6d6d6d;"><pre>已完全扫码</pre></span>
                </td>
              </div>
            </el-col>
          </el-row>
          <pagination
            v-show="busDataTotal>0"
            :total="busDataTotal"
            :limit.sync="busQuery.limit"
            :page.sync="busQuery.page"
            @pagination="getBizDetailList"
          ></pagination>
        </el-tab-pane>


        <el-tab-pane>
          <span slot="label">单据 {{ orderData.billNo }}-追溯码详情</span>
          <el-table :data="detailList" style="width: 100%;" highlight-current-row="true" border ref="multipleTable"
                    :row-style="rowStyle"
          >
            <el-table-column label="序号" type="index"></el-table-column>
            <el-table-column label="追溯码" prop="udiCode" width="160"></el-table-column>
            <el-table-column label="药品编码" prop="nameCode"></el-table-column>
            <el-table-column label="药品通用名称" prop="cpmctymc" width="110"></el-table-column>
            <el-table-column label="包装规格" prop="ggxh" width="110"></el-table-column>
            <el-table-column label="扫码数量" prop="scanCount" width="110"></el-table-column>
            <el-table-column label="批次号" prop="batchNo"></el-table-column>
            <el-table-column label="生产日期" prop="productDate"></el-table-column>
            <el-table-column label="失效日期" prop="expireDate"></el-table-column>
            <el-table-column label="序列号" prop="serialNo"></el-table-column>
            <!--<el-table-column label="扫码数量" prop="scanActCount"></el-table-column>-->
            <el-table-column label="批准文号" prop="zczbhhzbapzbh"></el-table-column>
          </el-table>
          <pagination
            v-show="resultTotal>0"
            :total="resultTotal"
            :limit.sync="codeQuery.limit"
            :page.sync="codeQuery.page"
            @pagination="getCodeList"
          ></pagination>
        </el-tab-pane>

      </el-tabs>


    </el-form>

    <el-dialog
      title="选入业务单据"
      :visible.sync="selectPrescriptionVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      v-if="selectPrescriptionVisible"
      width="65%"
      append-to-body
    >
      <selectPrescribeDialog
        ref="childRef"
        :workPlaceCode="null"
        :busType="this.$route.query.busType"
        :fromCorp="this.orderData.fromCorp"
        :confirmSelect="this.confirmSelect"
        :closeDialog="this.closeDialog"
        :viewType="viewType"
        :isAudit="true"
      ></selectPrescribeDialog>
    </el-dialog>
  </div>
</template>

<script>
import {isBlank} from '@/utils/strUtil'
import {getCodeEndList} from '@/api/collect/IoCollectCodeSelect'
import {enterCodeBillNo, enterCodeWeb} from '@/api/inout/order'
import {
  autoCodeResult,
  findByBill,
  manualCodeDetail,
  orderDetail,
  abandonOrder,
  getCurOrder
} from '@/api/collect/collectOrder'
import {checkCollectOrderManCode, draftOrder, finishCheckOrder, updateOrder} from '@/api/collect/splitCreateOrder'
import selectPrescribeDialog from "@/views/collect/selectCollectOrderDialog";
import {getSet} from '@/api/collect/collectSet'

export default {
  name: 'IocCollectOrderCheckCode',
  props: {
    resetKey: {
      type: Function,
      required: true
    }
  },
  components: {selectPrescribeDialog},
  data() {
    return {
      detailList: [],
      resultTotal: 0,
      scanTip: '扫码审核:',
      placeholder: '请输入单据号进行扫码审核',
      scanTitle: '扫码结果:',
      scanResultType: 'success',
      result: '\n',
      errVisible: false,
      loading: false,
      successVisible: true,
      errResult: '',
      scanCode: '',
      codeQuery: {
        fifoSplit: 3,
        billNo: null,
        orderIdFk: null,
        code: null,
        page: 1,
        limit: 10
      },
      busQuery: {
        billNo: null,
        orderIdFk: null,
        code: null,
        page: 1,
        limit: 10
      },
      filterQuery: {
        code: '',
        billNo: null,
        codeList: [],
        busType: null,
        workPlaceCode: '',

        //
        orderIdFk: null,
        udiCode: '',
        udiCodeList: []
      },

      workplaceId: null,
      orderData: {},
      curRow: null,
      codeList: [],

      checkCodeList: [],
      busDataList: [],
      busDataTotal: 0,
      //用于校验扫码数量
      codeCount: 0,
      selectPrescriptionVisible: false,
      viewType: 1,
      collectSet: {}
    }
  },
  methods: {
    getScanActCountStyle(row) {
      // const progress = row.scanActCount / row.count;
      // let color;
      // if (progress < 0.5) {
      //   color = 'red'; // 进度小于50%为红色
      // } else if (progress < 1.0) {
      //   color = 'orange'; // 进度在50%到100%之间为橙色
      // } else {
      //   color = 'green'; // 进度达到或超过100%为绿色
      // }
      return {
        // color,
        fontWeight: 'bold', // 字号加粗
      };
    },
    enterKey() {
      // this.result = "\n"
      this.errResult = ''
      // this.errVisible = false
      // this.successVisible = true

      if (this.scanCode.includes("DMOENTER")) {
        if (this.orderData.billNo == null) {
          this.$message.error('请先选择单据')
        } else {
          this.confirmCheckOrder()
        }
        this.scanCode = ''
        return
      } else if (this.scanCode.includes("DMOCANCEL")) {
        if (this.orderData.billNo == null) {
          this.$message.error('请先选择单据')
        } else {
          this.cancelOrder()
        }
        this.scanCode = ''
        return
      } else if (this.scanCode.includes("DMODEL")) {
        // this.deleteCode()
        this.scanCode = ''
        return
      }


      //是否已经有单据
      if (this.orderData.billNo == null) {
        this.enterBillNoKey()
        return
      }

      this.filterQuery.udiCode = this.scanCode.trim()
      if (this.filterQuery.udiCode.includes(';')) {
        const codeArray = this.filterQuery.udiCode.split(';')
        const verify = this.verifyScanCount(codeArray)
        if (verify) {
          this.filterQuery.udiCodeList = codeArray
          this.filterQuery.udiCode = ''
          this.filterQuery.orderIdFk = this.orderData.billNo
          // 处理多码的情况
          this.batchVailCode(this.filterQuery)
        }
        return
      }
      if (this.filterQuery.udiCode) {
        if (!this.parseString(this.filterQuery.udiCode)) {
          this.$refs.inputRef.focus()
          this.$refs.inputRef.select()
          this.$message.error('无效追溯码')
          return
        }
      }
      let tQuery = {
        code: this.filterQuery.udiCode.trim(),
      };
      enterCodeWeb(tQuery).then((response) => {
        if (response.code === 20000) {
          this.$refs.inputRef.focus();
          this.$refs.inputRef.select();
          this.isSuccess = true;
          this.printCodeResult(response.data, response.message)
          this.filterQuery.udiCode = response.data.code;
          this.scanCode = ""
          this.originCode = ""
          this.addCode();
        } else {
          if (response.code == 502) {
            this.checkSuccess = false;
            this.isSuccess = false;
            this.printCodeResult(response.data, response.message)
            this.filterQuery.udiCode = response.data.code;
            this.originCode = response.data.code;
          } else if (response.code == 501) {
            this.checkSuccess = false;
            this.$message.error(response.message);
            this.scanCode = ""
          } else if (response.code == 503) {
            this.checkSuccess = false;
            this.isSuccess = false;
            this.printCodeResult(response.data, response.message)
            this.filterQuery.udiCode = response.data.code;
            this.scanCode = ""
            this.$confirm(response.message, "提示", {
              type: "warning",
            })
              .then(() => {
                this.filterQuery.udiCode = response.data.code;
                this.addCode();
              })
              .catch(() => {
                this.filterQuery.udiCode = response.data.code;
              });
          } else {
            this.scanCode = ""
            this.$alert(response.message, "提示", {
              confirmButtonText: "确定",
              type: "warning",
              closeOnClickModal: true,
              callback: (action) => {
                this.$refs.inputRef.focus();
                this.$refs.inputRef.select();
              },
            });
          }
        }
        this.loading = false;
      });
      // this.getInputFocus()
    },

    addCode() {
      //前端单码校验是否已经校验该码
      let isIncludes = this.checkCode(this.filterQuery.udiCode)
      if (!isIncludes) {
        this.filterQuery.orderIdFk = this.orderData.billNo
        this.verifyCode(this.filterQuery)
      } else {
        this.scanCode = ""
        this.getInputFocus()
        this.$message.error("该追溯码已审核")
      }
    },
    checkCode(code) {
      return this.checkCodeList.includes(code)
    },

    enterBillNoKey(billNo) {
      this.loading = true;
      this.filterQuery.code = this.scanCode
      let tQuery = {
        viewType: 'tagCode',
        workPlaceCode: this.workplaceId,
        busType: this.filterQuery.busType,
        code: this.filterQuery.code.trim()
      }
      if (billNo != null) {
        tQuery.code = billNo
      }
      enterCodeBillNo(tQuery).then((response) => {
        if (response.code == 601) {
          this.placeholder = '已选入单据，请扫描追溯码进行审核'
          this.orderData.billNo = response.data.billNo
          this.getBillNo(this.orderData.billNo)
          this.$refs.inputRef.focus()
          this.$refs.inputRef.select()
          this.scanCode = ''
          this.getCodeList()
          this.getBizDetailList()
          this.updateOrder()
        } else {
          this.$refs.inputRef.focus()
          this.$refs.inputRef.select()
          this.scanCode = ''
          this.$message.error(response.message)
        }
        this.loading = false
      })
    },
    getBillNo(billNo) {
      let post = {
        billNo: billNo,
        workPlaceCode: this.workplaceId,
        page: 1,
        limit: 10
      }
      findByBill(post).then(res => {
        if (res.code == 20000) {
          if (res.data.billNo != null) {
            this.orderData = res.data
            this.scanCode = ''
            this.filterQuery.workPlaceCode = this.workplaceId
            this.curRow = this.orderData
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getBizDetailList() {

      if (this.orderData != null) {
        // this.codeQuery.page = 1
        this.busQuery.orderIdFk = this.orderData.billNo
        // this.codeQuery.bizIdFk = this.bizId
      }
      orderDetail(this.busQuery).then(res => {
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        this.busDataList = res.data.list
        this.busDataTotal = res.data.total
      }).catch(() => {
        this.$message.error('数据加载失败')
      })
    },
    verifyCode(query) {
      checkCollectOrderManCode(query).then(res => {
        if (res.code == 20000) {
          if (Array.isArray(res.data)) {
            let codeList = res.data
              .filter(item => item.status === 1)
              .map(item => item.code);
            codeList.forEach(code => {
              this.checkCodeList.push(code);
            });
            this.printCodeResultList(res.data)
            this.codeCount = this.codeCount + query.udiCodeList.length
            this.checkCodeEnd()
          } else {

            if (this.busDataList.length > 0) {
              this.busDataList.forEach(item => {
                // 检查 item 的 id 是否与 bizId 匹配
                if (item.id == res.data.bizIdFk) {
                  // 如果匹配，递增计数器
                  if (item.scanActCount == null) {
                    item.scanActCount = res.data.scanActCount;
                  } else {
                    item.scanActCount += res.data.scanActCount;
                  }
                }
              });
            }

            //如果校验成功
            this.codeCount = this.codeCount + 1
            this.checkCodeList.push(res.data.code)
            this.verifyFinish(1, res.data, res.message)
            // this.$message.success('校验成功')
            this.checkCodeEnd()
          }
        } else {
          if (Array.isArray(res.data)) {
          } else {
            this.verifyFinish(2, res.data, res.message)
            this.$message.error(res.message)
          }
        }
      })
    },
    checkCodeEnd() {
      if (this.codeCount == this.detailList.length) {
        this.$confirm("单据追溯码已经全部审核完毕，是否立即完成单据审核？", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.commitCheckOrder()
        })
      }
    },
    verifyFinish(val, data, message) {
      if (val == 1) {
        this.errVisible = false
        this.successVisible = true
        this.printCodeResult(data, message)
      } else {
        this.errVisible = true
        this.successVisible = false
        this.errResult = data + '追溯码不存在'
      }
      this.scanCode = ''
      this.getInputFocus()
    },
    getInputFocus(event) {
      // event.currentTarget.select();
      this.$nextTick(() => {
        this.$refs.inputRef.focus()
        this.$refs.inputRef.select()
      })
    },
    printCodeResult(data, message) {
      const resultParts = []
      if (data.udi) {
        resultParts.push('层级标识: ' + data.udi)
      }
      if (data.cpmctymc) {
        resultParts.push(data.productType == 2 ? '药品通用名称' : '产品通用名称: ' + data.cpmctymc)
      }
      if (data.batchNo) {
        resultParts.push('批次号: ' + data.batchNo)
      }
      if (data.produceDate) {
        resultParts.push('生产日期: ' + data.produceDate)
      }
      if (data.expireDate) {
        resultParts.push('失效日期: ' + data.expireDate)
      }
      if (data.serialNo) {
        resultParts.push('序列号: ' + data.serialNo)
      }
      if (data.productType == 2) {
        if (data.bzgg) {
          resultParts.push('包装规格: ' + data.bzgg)
        }
      } else {
        if (data.ggxh) {
          resultParts.push('规格型号: ' + data.ggxh)
        }
      }
      if (data.prepnSpec) {
        resultParts.push('制剂规格: ' + data.prepnSpec)
      }
      if (data.prepnUnit) {
        resultParts.push('剂型: ' + data.prepnUnit)
      }
      if (data.packUnit) {
        resultParts.push('计量单位: ' + data.packUnit)
      }
      this.scanTitle = '扫码结果：' + data.code
      this.result = resultParts.join(' , ')
      if (message == 'success') {
        this.scanResultType = 'success'
      }
    },
    async printCodeResultList(vailCodeResultResponses) {
      this.errResult = ''
      this.result = ''
      this.scanCode = ''
      this.successVisible = false
      this.errVisible = false
      this.scanTitle = '扫码结果：'
      for (let i = 0; i < vailCodeResultResponses.length; i++) {
        let data = vailCodeResultResponses[i]
        if (data.status == 1) {
          this.result = this.result + (isBlank(this.result) ? '' : ';') + vailCodeResultResponses[i].code + ':' + vailCodeResultResponses[i].sucMsg
        } else if (data.status == 2) {
          this.errResult = this.errResult + '\n' + vailCodeResultResponses[i].code + ':' + vailCodeResultResponses[i].errMsg
        }
      }
      if (!isBlank(this.result)) {
        this.successVisible = true
      }
      if (!isBlank(this.errResult)) {
        this.errVisible = true
      }
    },
    parseString(str) {
      // 1. 判断是否以 "MA" 开头
      if (str.startsWith('MA')) {
        return true
      }

      // 2. 判断是否以 "01" 开头且长度大于等于 18
      if (str.startsWith('01') && str.length >= 16) {
        return true
      }

      // 3. 判断是否以 "#" 开头且 "#" 的个数大于等于 4
      if (str.startsWith('#') && (str.match(/#/g) || []).length >= 4) {
        return true
      }

      // 4. 判断是否以 "8" 开头且长度为 20 位
      if (str.startsWith('8') && str.length === 20) {
        return true
      }

      // 5. 判断是否以 "11", "17", "21", 或 "10" 开头
      const prefixes = ['11', '17', '21', '10']
      if (prefixes.some(prefix => str.startsWith(prefix))) {
        return true
      }
      // 如果没有任何条件满足，返回 false
      return false
    },

    getCodeList() {
      if (this.orderData != null) {
        // this.codeQuery.page = 1
        this.codeQuery.orderIdFk = this.orderData.billNo
        // this.codeQuery.bizIdFk = this.bizId
      }
      this.codeLoading = true
      if (this.codeQuery.fifoSplit == 3) {
        manualCodeDetail(this.codeQuery).then(res => {
          this.codeLoading = false
          if (res.code != 20000) {
            this.$message.error(res.message)
            return
          }
          this.detailList = res.data.list
          this.codeList = this.detailList.map(item => item.udiCode)
          this.resultTotal = res.data.total || 0
          // this.codeLoading = false
        }).catch(() => {
          // this.codeLoading = false
          this.resultTotal = res.data.total || 0
          this.$message.error('数据加载失败')
        })
      }

    },

    batchVailCode(params) {
      // batchVailCode(params).then((res) => {
      //   if (res.code === 20000) {
      const vailCodeResultResponseList = []
      const vailCodeResultResponse = {}
      const codeList = []
      params.udiCodeList.forEach(code => {
        let isIncludes = this.checkCode(code)
        if (isIncludes) {
          vailCodeResultResponse.status = 2;
          vailCodeResultResponse.code = code;
          vailCodeResultResponse.errMsg = "追溯码已被校验";
          vailCodeResultResponseList.push(vailCodeResultResponse);
        } else {
          codeList.push(code)
        }
      });
      if (vailCodeResultResponseList.length > 0) {
        this.printCodeResultList(vailCodeResultResponseList)
      }

      if (codeList.length > 0) {
        params.udiCodeList = codeList
        this.verifyCode(params)
      }
      this.scanCode = ""
      this.$refs.inputRef.focus()
      this.$refs.inputRef.select()

      // } else {
      //   this.$message.error(res.message)
      // }
      // })
    },
    confirmCheckOrder() {
      //完成校验
      if (this.codeCount != this.detailList.length) {
        this.$confirm('当前单据追溯码未全部审核是否完成此单据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.commitCheckOrder()
        }).catch(() => {
        })
      } else {
        this.$confirm('是否确定完成此单据审核?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.commitCheckOrder()
        }).catch(() => {
        })
      }

    },
    commitCheckOrder() {
      this.finishOrder()
      this.init()
      this.$message.success('单据审核完成')
    },
    finishOrder() {
      finishCheckOrder(this.orderData).then(res => {
        if (res.code == 20000) {
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {

      })
    },
    cancelOrder() {
      this.$confirm('此操作将取消当前正在审核单据，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        abandonOrder(this.orderData).then(res => {
          if (res.code == 20000) {
            this.init()
            this.$message.success("放弃成功")
          } else {
            this.$message.error(res.message)
          }
        })
      }).catch(() => {
      });
    },
    selectPrescribe() {
      this.selectPrescriptionVisible = true;
    },
    confirmSelect(row) {
      this.placeholder = '已选入单据，请扫描追溯码进行审核'
      this.orderData = row;
      this.orderData.workPlaceCode = this.workplaceId;
      this.scanCode = ''
      this.getCodeList()
      this.getBizDetailList()
      this.getInputFocus()
      this.updateOrder()
      this.closeDialog()
      this.selectSysParam()
      // this.startDeal();
    },
    selectAllData() {
      this.placeholder = '已选入单据，请扫描追溯码进行审核'
      this.scanCode = ''
      this.orderData.workPlaceCode = this.workplaceId;
      this.getCodeList()
      this.getBizDetailList()
      this.getInputFocus()
      this.updateOrder()
    },
    closeDialog() {
      this.selectPrescriptionVisible = false;
    },
    updateOrder() {
      this.orderData.tagStatus = 2;
      this.orderData.workPlaceCode = this.workplaceId;
      updateOrder(this.orderData).then(res => {
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    saveDraftOrder() {
      this.$confirm('此操作将挂起当前正在审核单据，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        draftOrder(this.orderData).then(res => {
          this.loading = false
          if (res.code == 20000) {
            this.init()
          }
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
      });
    },
    findCurOrder() {
      let nextQuery = {
        // workPlaceCode: this.formData.workPlaceCode,
        busType: this.$route.query.busType
      }
      getCurOrder(nextQuery).then(res => {
        this.loading = false
        if (res.code == 20000) {
          let temp = res.data;
          if (temp.tagStatus === -1) {
            this.$confirm('检测到当前工位存在挂起单据，是否继续上一次单据处理?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.orderData = temp;
              this.selectAllData()
            }).catch(() => {
            });
          } else if (temp.tagStatus === 2 || temp.tagStatus === 1) {
            this.orderData = temp;
            this.selectAllData()
          }

        } else {
          // this.$message.error(res.message)
          this.$refs.inputRef.focus();
        }
      }).catch(() => {
        this.loading = false
      })
    },
    init() {
      this.filterQuery = {
        code: '',
        billNo: null,
        codeList: [],
        busType: this.$route.query.busType,
        workPlaceCode: '',
        orderIdFk: null,
        udiCode: '',
        udiCodeList: []
      }
      this.scanCode = ''
      this.errVisible = false
      this.errResult = ''
      this.successVisible = true
      this.scanTitle = '扫码结果:'
      this.scanResultType = 'success'
      this.curRow = null
      this.orderData = {
        busType: this.$route.query.busType
      }
      this.codeCount = 0
      this.workplaceId = Number(this.$route.query.workplaceId)
      this.codeList = []
      this.detailList = []
      this.checkCodeList = []
      this.busDataList = []
      this.result = '\n'
      this.scanTip = '扫码审核:'
      this.placeholder = '请输入单据号进行扫码审核'
      this.resultTotal = 0
      this.getInputFocus()
      this.selectSysParam()
    },
    verifyScanCount(codeArray) {
      //判断扫码数量是否超出或少于设置扫码数量
      if (this.collectSet.scanMaxCount != null && this.collectSet.scanMaxCount != 0) {
        if (this.collectSet.scanMaxCount > codeArray.length) {
          this.scanCode = ''
          this.$message.error("扫码数量少于设置扫码数量");
          return false;
        } else if (this.collectSet.scanMaxCount < codeArray.length) {
          this.scanCode = ''
          this.$message.error("扫码数量超出");
          return false;
        }
      }
      return true;
    },
    selectSysParam() {
      getSet().then((response) => {
        if (response.code == 20000) {
          this.collectSet = response.data
        }
      })
    },
    rowStyle({row, rowIndex}) {
      let rowBackground = {}
      if (this.checkCodeList.length == 0) {
        rowBackground.color = '#F56C6C'
        rowBackground.height = '38px'
        return rowBackground
      }
      if (this.checkCodeList.includes(row.udiCode)) {
        rowBackground.color = '#56a717'
      }
      if (!this.checkCodeList.includes(row.udiCode)) {
        rowBackground.color = '#F56C6C'
      }
      rowBackground.height = '38px'
      return rowBackground;
    },
    rowStyleBiz({row, rowIndex}) {
      let rowBackground = {}
      const progress = row.scanActCount / row.count;

      if (row.scanActCount == null || row.scanActCount == 0) {
        rowBackground.color = '#F56C6C'; // 进度小于50%为红色
      } else if (progress < 1.0) {
        rowBackground.color = '#E6A23C'; // 进度在50%到100%之间为橙色
      } else {
        rowBackground.color = '#56a717'; // 进度达到或超过100%为绿色
      }
      rowBackground.height = '38px'
      return rowBackground
    }
  },
  watch: {
    resetKey(newVal, oldVal) {
      this.$refs.inputRef.focus()
    }
  },
  created() {
    if (this.$route.query.workplaceId != null) {
      this.workplaceId = Number(this.$route.query.workplaceId)
      // this.formData.workPlaceCode = Number(this.$route.query.workplaceId);
      // this.getWorkBindBusTypes(this.formData.workPlaceCode);
    }
    if (this.$route.query.busType != null) {
      this.filterQuery.busType = this.$route.query.busType
      // this.formData.workPlaceCode = Number(this.$route.query.workplaceId);
      // this.getWorkBindBusTypes(this.formData.workPlaceCode);
    }
    // this.getResultDetailList()
    // this.init()
    this.checkCodeList = []
    this.codeCount = 0
    this.findCurOrder()
    this.selectSysParam();
  },
  mounted() {
    this.getInputFocus()
  }
}
</script>

<style scoped>


</style>
