<template>
  <div>
    <el-card>
      <el-button-group  style="display: flex; justify-content: flex-end;" v-if="type == 1">
        <el-button
          type="primary"
          @click.native="confirmCheckOrder()"
        >校验完成
        </el-button>
      </el-button-group>
      <el-form :model="orderData" class="demo-form-inline" style="margin-top: 30px" @submit.native.prevent>

        <!--<div style="border: 1px solid #ebeef5;border-radius: 2px;margin-top: 15px;padding: 15px">-->
        <el-row :gutter="0" style="margin-top: 5px" v-if="type == 1">
          <el-col :span="20">
            <el-form-item prop="code" label="扫码校验" label-width="80px">
              <el-input
                id="inputer"
                @keypress.enter.native="enterKey($event)"
                ref="inputRef"
                @focus="getInputFocus($event)"
                style="ime-mode: disabled"
                type="tel"
                :placeholder="this.placeholder"
                v-model="scanCode"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button-group style="display: flex;">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-plus"
                style="margin-left: 15px"
                @click.native.stop="enterKey($event)"
              >添加
              </el-button>
            </el-button-group>
          </el-col>
        </el-row>
        <el-alert
          v-if="successVisible && type == 1"
          :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 && type == 1"
          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.fromCorp }}</el-descriptions-item>
          <el-descriptions-item label="收货方">{{ orderData.fromCorpName }}</el-descriptions-item>
          <el-descriptions-item label="单据时间">{{ orderData.billTime }}</el-descriptions-item>
          <el-descriptions-item label="来源系统">{{ orderData.fromType }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ orderData.createTime }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ orderData.updateTime }}</el-descriptions-item>
          <el-descriptions-item label="单据备注">{{ orderData.remark }}</el-descriptions-item>
        </el-descriptions>

      </el-form>
    </el-card>
    <el-tabs type="border-card" style="margin: 15px">
      <!--单据业务详情-->
      <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="code" 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="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>
        <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="resultTotal>0"
          :total="resultTotal"
          :limit.sync="codeQuery.limit"
          :page.sync="codeQuery.page"
          @pagination="getResultDetailList"
        ></pagination>
        <!-- 在表格下方添加说明 -->

      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { isBlank } from '@/utils/strUtil'
import { getCodeEndList } from '@/api/collect/IoCollectCodeSelect'
import { commitCheckCodeOrder, scanCheckCodeOrder, scanCheckCodeReplace } from '@/api/collect/splitCreateOrder'

export default {
  name: 'DialogCheckCode',
  props: {
    orderData: {
      type: Object,
      default: null,
      required: true
    },
    closeCodeCheckDialog: {
      type: Function,
      required: true
    },
    type: {
      type: Object,
      default: null,
      required: true
    },
  },
  data() {
    return {
      detailList: [],
      resultTotal:0,
      scanTip: '扫码校验:',
      placeholder: '请点击输入框进行扫码校验',
      scanTitle: '扫码结果:',
      scanResultType: 'success',
      result: '\n',
      errVisible: false,
      successVisible: true,
      errResult: '',
      scanCode: '',
      codeQuery: {
        billNo:null,
        code: null,
        selectType:2,
        page: 1,
        limit: 10
      },
      filterQuery: {
        code: '',
        billNo: null,
        codeList: [],
      },
      checkCodeList:[],
      checkCodeEndList:[],
    }
  },
  methods: {
    enterKey() {
      this.errResult = ''
      this.filterQuery.code = this.scanCode.trim()
      if (this.filterQuery.code.includes(';')) {
        const codeArray = this.filterQuery.code.split(';')
        this.filterQuery.codeList = codeArray
        this.filterQuery.code = ''
        this.filterQuery.billNo = this.orderData.billNo
        // 处理多码的情况
        this.batchVailCode(this.filterQuery)
        return
      }
      if (this.filterQuery.code) {
        if (!this.parseString(this.filterQuery.code)) {
          this.$refs.inputRef.focus()
          this.$refs.inputRef.select()
          this.$message.error('无效追溯码')
          return
        }
      }
      //单码校验
      this.filterQuery.billNo = this.orderData.billNo
      this.verifyCode(this.filterQuery)
      // this.getInputFocus()
    },
    verifyCode(query) {
      scanCheckCodeOrder(query).then(res => {
        if (res.code == 20000) {
          if (Array.isArray(res.data)) {
            this.printCodeResultList(res.data)
            this.codeQuery.selectType = 1
            this.getResultDetailList()
            let codeList = res.data
            let filterCodeList = codeList.filter(item => item.status === 5).map(item => item.code);;
            if (filterCodeList.length > 0){
              query.codeList = filterCodeList
              this.replaceCode(query,1)
            }
          } else {
            this.verifyFinish(1, res.data, res.message)
            this.checkCodeEndList.push(query.code)
            this.codeQuery.selectType = 1
            this.getResultDetailList()
            //码不对 全部码
            this.$message.success('校验成功')
          }
        }else if (res.code == 503){
          this.replaceCode(query,2)
        } else if (res.code == 504){
        //追溯码不存在 是否执行更换
        this.$confirm('追溯码校验超出是否继续添加', '提示', {
          confirmButtonText: '添加',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          closeOnPressEscape: false,//按下 ESC 键关闭弹窗
          closeOnClickModal: false,//点击遮罩关闭弹窗
          distinguishCancelAndClose: true,//区分取消与关闭
        }).then(() => {
          scanCheckCodeReplace(query).then(res => {
            if (res.code == 20000){
              this.scanCode = ''
              this.orderData.checkCodeConfirm = res.data.checkCodeConfirm
              this.codeQuery.selectType = 1
              this.getResultDetailList()
              this.getInputFocus()
              this.$message.success("添加成功")
            }else {
              this.$message.error("添加失败")
            }
          })
        })
      }else {
          if (Array.isArray(res.data)) {

          } else {
            this.scanCode = ''
            this.getInputFocus()
            // this.verifyFinish(2, res.data, res.message)
            this.$message.error(res.message)
          }
        }
      })
    },
    replaceCode(query,type){
      let title = ''
      if (type == 1){
        const codeStr = query.codeList.join('\n');
         title = `${codeStr}该追溯码不存在是否继续添加`;
      }else {
         title = '该追溯码不存在是否继续添加'
      }
      //追溯码不存在 是否执行更换
      this.$confirm(title, '提示', {
        confirmButtonText: '添加',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        closeOnPressEscape: false,//按下 ESC 键关闭弹窗
        closeOnClickModal: false,//点击遮罩关闭弹窗
        distinguishCancelAndClose: true,//区分取消与关闭
      }).then(() => {
        scanCheckCodeReplace(query).then(res => {
          if (res.code == 20000){
            this.scanCode = ''
            this.orderData.checkCodeConfirm = res.data.checkCodeConfirm
            this.codeQuery.selectType = 1
            this.getResultDetailList()
            this.getInputFocus()
            this.$message.success("添加成功")
          }else {
            this.$message.error("添加失败")
          }
        })
      }).catch(() => {
        this.scanCode = ''
        this.getInputFocus()
      })
    },
    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.successVisible = false
      this.errVisible = false
      this.scanTitle = '扫码结果：'
      for (let i = 0; i < vailCodeResultResponses.length; i++) {
        let data = vailCodeResultResponses[i]
        if (data.status == 1) {
          this.scanResultType = "success"
          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
        }else if (data.status == 5) {
          this.scanResultType = "warning"
          this.result = this.result + (isBlank(this.result) ? '' : ';') + 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 >= 18) {
        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
    },
    getResultDetailList() {
      this.codeQuery.billNo = this.orderData.billNo
      getCodeEndList(this.codeQuery).then((res) => {
        if (res.code === 20000) {
          this.detailList = res.data.list || []
          this.checkCodeList = this.detailList.map(item => item.code)
          this.resultTotal = res.data.total || 0;
          this.codeQuery.selectType = 2
        } else {
          this.$message.error(res.message)
          this.detailList = []
          this.resultTotal = 0;
        }
      }).catch((error) => {
        this.$message.error(error.message)
        this.detailList = []
        // this.resultTotal = 0;
      })
    },
    batchVailCode(params) {
      // batchVailCode(params).then((res) => {
      //   if (res.code === 20000) {
      this.$refs.inputRef.focus()
      this.$refs.inputRef.select()
      this.verifyCode(params)
      // } else {
      //   this.$message.error(res.message)
      // }
      // })
    },
    confirmCheckOrder(){
      if (this.orderData.checkCodeConfirm == 1){
        //追溯码不存在 是否执行更换
        this.$confirm('当前单据存在可替换追溯码是否替换完成校验', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          closeOnPressEscape: false,//按下 ESC 键关闭弹窗
          closeOnClickModal: false,//点击遮罩关闭弹窗
          distinguishCancelAndClose: true,//区分取消与关闭
        }).then(() => {
          this.commit()
        }).catch(() => {

        })
      }else {
        this.commit()
      }

        // // 检查是否所有行都是绿色
        // let allGreen = this.detailList.every(row => {
        //   return this.checkCodeEndList.includes(row.code);
        // });
        //
        // if (allGreen) {
        //   // 如果所有行都是绿色，执行提交操作
        //   // this.doSubmit();
        //   this.$message.success('所有行都是绿色');
        // } else {
        //   // 如果不是所有行都是绿色，提示用户
        //   this.$message.error('请确保所有行都是绿色后再提交');
        // }
    },
    commit(){
      commitCheckCodeOrder(this.filterQuery).then(res => {
        if (res.code == 20000){
          this.closeCodeCheckDialog()
          this.$message.success("校验完成")
        }else {
          if (this.orderData.checkCodeConfirm == 1){
            this.closeCodeCheckDialog()
          }
          this.$message.error(res.message)
        }
      }).catch(() => {

      })
    },
    init() {
      this.codeQuery = {
        billNo: null,
        code: null,
        selectType:2,
        page: 1,
        limit: 10
      }
      this.errVisible = false
      this.successVisible = true
    },
    rowStyle({row, rowIndex}) {
      let rowBackground = {}
      if (row.scanCodeCheckStatus == 1) {
        rowBackground.color = '#56a717'
      }
      if (row.scanCodeCheckStatus == 3) {
        rowBackground.color = '#E6A23C';
      }
      rowBackground.height = "38px"
      return rowBackground;
    },
  },
  created() {
    this.filterQuery.billNo = this.orderData.billNo
    this.getResultDetailList()
    this.init()
  },
  mounted() {
    this.getInputFocus()
  }
}
</script>

<style scoped>


</style>
