<template>
    <div>
      <el-form
        :model="relFormData"
        :rules="formRules"
        ref="dataForm"
        @submit.native.prevent
        label-width="110px"
      >
        <el-card>
          <el-row style="margin-bottom: 8px">
            <el-button-group
              style="display: flex; margin-top: 5px; float: right"
            >
              <el-button size="mini" type="primary" @click.native="giveUp()" :loading="submitLoading"
                         style="margin-right: 8px;border-radius: 5%;"
              >放弃
              </el-button>
<!--              <el-button size="mini" type="primary" @click.native="submit()" :loading="submitLoading"-->
<!--                         style="margin-right: 8px;border-radius: 5%;"-->
<!--              >保存-->
<!--              </el-button>-->
              <el-button size="mini" type="primary" @click.native="submit()" :loading="submitLoading"
                         style="margin-right: 8px;border-radius: 5%;"
              >提交
              </el-button>
            </el-button-group>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item prop="cpmctymc" class="query-form-item" label="产品名称:">
                <el-input
                  v-model="relFormData.cpmctymc"
                  auto-complete="off"
                  style="width: 90%"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="packageSpec" class="query-form-item" label="规格型号:">
                <el-input
                  v-model="relFormData.packageSpec"
                  auto-complete="off"
                  style="width: 90%"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="productCode" class="query-form-item" label="产品编码:">
                <el-input
                  v-model="relFormData.productCode"
                  auto-complete="off"
                  style="width: 90%"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="cascadeRatio" class="query-form-item" label="包装比例:">
                <el-input
                  v-model="relFormData.cascadeRatio"
                  auto-complete="off"
                  style="width: 90%"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="packLayer" class="query-form-item" label="当前层级:">
                <el-input
                  v-model="relFormData.packLayer"
                  auto-complete="off"
                  style="width: 90%"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="packUnit" class="query-form-item" label="层级单位:">
                <el-input
                  v-model="relFormData.packUnit"
                  auto-complete="off"
                  style="width: 90%"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="batchNo" class="query-form-item" label="批次号:">
                <el-input
                  v-model="relFormData.batchNo"
                  auto-complete="off"
                  style="width: 90%"
                  :disabled="true"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="madeDate" class="query-form-item" label="生产日期:">
                <el-date-picker
                  v-model="relFormData.madeDate"
                  type="datetime"
                  placeholder="日期"
                  clearable
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 90%"
                  :disabled="true"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="validateDate" class="query-form-item" label="失效日期:">
                <el-date-picker
                  v-model="relFormData.validateDate"
                  type="datetime"
                  placeholder="日期"
                  clearable
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 90%"
                  :disabled="true"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="comment" class="query-form-item" label="备注:">
                <el-input
                  v-model="relFormData.comment"
                  auto-complete="off"
                  clearable
                  style="width: 90%"
                  placeholder="请输入备注"
                  :disabled="true"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider></el-divider>
          <el-row>
            <el-col :span="18">
              <el-form-item prop="code" label="扫码录入:">
                <el-input
                  id="inputer"
                  @focus="getInputFocus($event)"
                  @keypress.enter.native="enterKey($event)"
                  ref="inputRef"
                  style="ime-mode: disabled"
                  type="tel"
                  placeholder="请点击输入框进行扫码设置或者扫码录入"
                  v-model="scanCode"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button-group>
                <el-button
                  type="primary"
                  size="mini"
                  @click.native.stop="enterKey()"
                  style="margin-left: 15px"
                >添加
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>

          <el-alert
            title="扫码结果:"
            :type="scanResultType"
            :closable="false"
            :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="warning"
            :closable="true"
            :dangerouslyUseHTMLString="true"
            :description="errResult">
          </el-alert>
        </el-card>
      </el-form>
      <el-tabs type="border-card" style="margin: 15px">
        <el-tab-pane label="关联详情">
          <div>
            <span><strong>父级编码：{{ parentCode || '暂未录入'}}</strong> <strong>  (<span style="color: #FF0000;">{{ syxjsl || 0}}</span>/<span >{{ bhxjsl || 0}}</span>)</strong></span>
          </div>
          <div>
              <el-table v-loading="loading"
              :data="detailList"
              style="width: 100%;" max-height="350" height="350"
              border
              :row-style="rowStyle"
              ref="multipleTable">
                <el-table-column type="index" label="序号" width="50"></el-table-column>
                <el-table-column label="追溯码" width="250" prop="curCode" show-overflow-tooltip></el-table-column>
                <el-table-column label="层级" width="150" prop="packLayer" show-overflow-tooltip></el-table-column>
                <el-table-column label="父级编码" width="250" prop="parentCode" show-overflow-tooltip></el-table-column>
              </el-table>
            </div>
        </el-tab-pane>
      </el-tabs>

    </div>
  </template>

  <script>
  import {enterCodeWeb} from "@/api/inout/order";
  import {addRelCode,scanCodeRelCode} from "@/api/collect/relCode";
  import A from "@/plugins/KeyScaner";
  export default {
    name: "operateRelCode",
    props: {
      closeDialog: {
        type: Function,
        required: true,
      },
      orderQuery: {
        type: Object,
        required: true,
        default: null
      },
      resetKey: {
        type: Function,
        required: true
      },
      opeParentCode:{
        type: String,
        required: true,
        default: null
      },
      opeRelFormData:{
        type: Object,
        required: true,
        default: null
      }
    },
    watch: {
      resetKey(newVal, oldVal) {
        this.$refs.inputRef.focus();
      }
    },
    data() {
      return {
        //扫码相关
        codeFormData: {
          code: "",
          batchNo: null,
          produceDate: null,
          expireDate: null,
          serialNo: null,
          relId: null,
        },
        relFormData: {
          productCode: null,
          subTypeNo: null,
          cascadeRatio: null,
          packageSpec: null,
          comment: null,
          batchNo: null,
          madeDate: null,
          validateDate: null,
          workShop: null,
          lineName: null,
          lineManager: null,
          packUnit: null,
          bhxjsl: null,
          detailList:[]
        },
        detailList: [],
        checkPreInArray: [],
        errView: 0,
        actionEnable: false,
        formRules: {
          batchNo: [
            {required: true, message: " ", trigger: "blur"},
          ],
          madeDate: [
            {required: true, message: " ", trigger: "blur"},
          ],
          validateDate: [
            {required: true, message: " ", trigger: "blur"},
          ],
        },
        isScan: true,
        scanText: "扫码录入：",
        corpOrderIdDisabled: false,
        isSupVesion: false,
        loading: false,
        index: null,
        formVisible: false,
        deleteLoading: false,
        orderNo: null,
        fromStorageOptions: [],
        curRow: null,
        dialogTableVisible: false,
        selectRlVisible: false,
        selectSpaceVisible: false,
        sitcomScan: false,
        sictomText: "",
        originCode: "",
        checkSuccess: false,
        codeDetail: null,
        fromDeptOptions: [],
        submitLoading: false,
        scanCode: "",
        isSuccess: false,
        result: "",
        scanResultType: "success",
        splitType: null,
        warnResult: "",
        errResult: "",
        warnVisible: false,
        errVisible: false,
        parentCode:null,
        bhxjsl:0,
        syxjsl:0,
        popDialogVisible:false,
        title:null,
        popParentCode:null,
        popRelFormData:null,
        popLevel:1,
      };
    },
    methods: {
      splitChange() {
        this.$refs.inputRef.focus();
      },
      handleDataSent(data){
        // this.relFormData = data;
        // console.log("00000",data)
      },
      popCloseDialog() {
        this.popDialogVisible = false;
      },
      //添加条码
      addCode() {
        //控制三期
        if (this.relFormData.batchNo == null) {
          this.$message.warning("请输入批次号！");
          return;
        }
        if (this.relFormData.madeDate == null) {
          this.$message.warning("请选择生产日期！");
          return;
        }
        if (this.relFormData.validateDate == null) {
          this.$message.warning("请选择失效日期！");
          return;
        }

        let tQuery = Object.assign(this.codeFormData);
        tQuery.curCode = this.codeFormData.code;
        tQuery.parentCode = this.parentCode;
        scanCodeRelCode(tQuery).then((response) => {
          if (response.code === 20000) {
            this.$refs.inputRef.focus();
            this.$refs.inputRef.select();
            this.isSuccess = true;
            let data = response.data;
            if(data !== null){
              if(this.detailList.some(item => item.curCode === data.curCode)) {
                //码重复提示
                this.$message.warning("录入码重复！");
                return;
              } else {
                if( this.bhxjsl !=0 && this.syxjsl != 0 && this.bhxjsl === this.syxjsl){
                  //满了自动保存
                  this.$message.warning("包含下级码已录满！");
                  return;
                }

                if (this.relFormData.productCode){
                  this.detailList.push(data);
                }

                //存在一个父级关联需-1
                this.syxjsl = this.detailList.length;

                if( this.bhxjsl === this.syxjsl){
                    this.$confirm("该层级已录入完成, 是否关闭?", "提示", {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                    })
                      .then(() => {
                        this.relFormData.detailList = this.detailList
                        //触发保存 切换到上一级别
                        this.submit()
                        this.closeDialog()
                      })
                      .catch(() => {
                      });
                  }
              }
              //判断是否是下级
              if(data.packLayer > 1){
                this.relFormData.cpmctymc = data.cpmctymc;
                this.relFormData.productCode = data.productCode;
                  this.relFormData.subTypeNo = data.subTypeNo;
                  this.relFormData.cascadeRatio = data.cascadeRatio;
                  this.relFormData.bhxjsl = data.bhxjsl;
                  this.relFormData.packageSpec = data.packageSpec;
                  // this.relFormData.comment = data.comment;
                  this.relFormData.packLayer = data.packLayer;
                  this.relFormData.packUnit = data.packUnit;
                  // this.relFormData.batchNo= data;
                  // this.relFormData.madeDate= data;
                  // this.relFormData.validateDate = data;
                  this.relFormData.workShop = data.workShop;
                  this.relFormData.lineName = data.lineName;
                  this.relFormData.lineManager = data.lineManager;
                  // this.relFormData.detailList:[]

                // this.relFormData = data;
                this.parentCode = data.curCode;
                this.bhxjsl = data.bhxjsl;
                //弹框
                this.popDialogVisible = true;
                this.popRelFormData =  this.relFormData;
                this.title = "手工关联:" + data.curCode;
                this.popParentCode = data.curCode;
              }
            }

          }else{
            this.$message.error(response.message);
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
      },

      refreshCodesPanel() {
        this.warnVisible = false;
        this.errVisible = false;
      },
      giveUp() {
        this.relFormData = {
          productCode: null,
          subTypeNo: null,
          cascadeRatio: null,
          packageSpec: null,
          comment: null,
          batchNo: null,
          madeDate: null,
          validateDate: null,
          workShop: null,
          lineName: null,
          lineManager: null,
          packUnit: null,
          bhxjsl: null,
          detailList: []
        }
        this.detailList = []
        this.parentCode = null
        this.bhxjsl = 0
        this.syxjsl = 0
        this.packLayer = null
      },
      submit() {
        //增加数量是否完全判断
        if( this.bhxjsl != this.syxjsl){
          this.$confirm("该层级已录入数量与应录入数量不符, 是否继续提交?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              addRelCode(this.relFormData).then((response) => {
                this.loading = false;
                if (response.code === 20000) {
                  this.$message.success("保存成功！");
                  this.clearRel();
                } else {
                  this.$message.error(response.message);
                }
              })
                .catch(() => {
                  this.loading = false;
                  this.clearRel();
                });
            })
            .catch(() => {
            });
        }else {
          addRelCode(this.relFormData).then((response) => {
            this.loading = false;
            if (response.code === 20000) {
              this.$message.success("保存成功！");
              this.clearRel();
            } else {
              this.$message.error(response.message);
            }
          }).catch(() => {
              this.loading = false;
              this.clearRel();
            });
        }

      },
      // 刷新表单
      resetForm() {
        if (this.$refs["dataForm"]) {
          // 清空验证信息表单
          this.$refs["dataForm"].clearValidate();
          // 刷新表单
          this.$refs["dataForm"].resetFields();
        }
      },
      enterKey(event) {
        this.warnResult = "";
        this.errResult = "";
        this.result = "";
        this.warnVisible = false;
        this.errVisible = false;

        this.checkSuccess = true;
        this.codeFormData.code = this.scanCode.trim();
        let tQuery = {
          originCode: this.originCode,
          code: this.codeFormData.code.trim(),
        };
        enterCodeWeb(tQuery).then((response) => {
          if (response.code === 20000) {
            this.$refs.inputRef.focus();
            this.$refs.inputRef.select();
            this.isSuccess = true;
            this.printCodeResult(response.data)
            this.codeFormData.code = response.data.code;
            this.scanCode = ""
            this.addCode();
          } else {
            if (response.code == 502) {
              this.checkSuccess = false;
              this.isSuccess = false;
              this.scanCode = ""
              this.printCodeResult(response.data)
              this.codeFormData.code = response.data.code;
              this.originCode = this.codeFormData.code;
            } else if (response.code == 501) {
              this.checkSuccess = false;
              this.scanCode = ""
              this.$message.error(response.message);
            } else if (response.code == 503) {
              this.checkSuccess = false;
              this.isSuccess = false;
              this.scanCode = ""
              this.printCodeResult(response.data)
              this.codeFormData.code = response.data.code;
              this.$confirm(response.message, "提示", {
                type: "warning",
              })
                .then(() => {
                  this.codeFormData.code = response.data.code;
                  this.addCode();
                })
                .catch(() => {
                  this.codeFormData.code = response.data.code;
                });
            } else if (response.code == 508) {
              this.scanCode = ""
              this.originCode = "";
              this.codeFormData.code = "01" + response.data.nameCode;
              this.originCode = this.codeFormData.code;
            } else {
              this.$alert(response.message, "提示", {
                confirmButtonText: "确定",
                type: "warning",
                closeOnClickModal: true,
                callback: (action) => {
                  this.$refs.inputRef.focus();
                  this.$refs.inputRef.select();
                },
              });
            }
          }
          this.loading = false;
        });

      },
      printCodeResult(data, isSuccess) {
        const resultParts = ["扫码解析结果：" + data.code];

        if (data.udi) {
          resultParts.push("层级标识: " + data.udi);
        }
        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);
        }
        this.result = resultParts.join(" , ");
      },
      getInputFocus(event) {
        event.currentTarget.select();
      },

      clearRel() {
        this.relFormData = {
          productCode: null,
          subTypeNo: null,
          cascadeRatio: null,
          packageSpec: null,
          comment: null,
          batchNo: null,
          madeDate: null,
          validateDate: null,
          workShop: null,
          lineName: null,
          lineManager: null,
          packUnit: null,
          cpmctymc:null,
        }
        this.scanCode = "";
        this.result = "";
        this.detailList = [];
        this.bhxjsl = 0;
        this.syxjsl = 0;
        this.parentCode = null;
        this.refreshCodesPanel()
      },
      init(){
        if(this.opeParentCode != null){
          this.parentCode = this.opeParentCode;
        }
        if(this.opeRelFormData != null){
          this.relFormData = this.opeRelFormData;
          // this.detailList.push(this.relFormData);
          this.bhxjsl = this.relFormData.bhxjsl;
        }
      }
    },
    filters: {},
    mounted() {
      document.body.ondrop = function (event) {
        event.preventDefault();
        event.stopPropagation();
      };
      var that = this;
      var inputer = document.getElementById("inputer");
      window.sc = new A.KeyScaner(inputer); //传入要监听的DOM节点
      sc.onInput = function (text) {
        if (text.includes("delete")) {
          that.codeFormData.code = "";
          that.sictomText = "";
          that.originCode = "";
          return;
        }
        if (that.sitcomScan) {
          let tempTxt = text;
          let str = tempTxt.replace(/[\r]/g, "");
          that.sictomText = that.sictomText + str;
          that.codeFormData.code = that.sictomText;
        } else {
          that.codeFormData.code = text;
        }
      };
      inputer.focus();
      this.$refs.inputRef.focus();
    },
    beforeDestroy() {

    },
    created() {
      this.init();
    },
  };
  </script>


  <style scoped>
  .scroll-alert {
    width: 100%; /* 或者你需要的宽度 */
    overflow: hidden;
    white-space: nowrap;
    box-sizing: border-box;
    /*border: 1px solid #f56c6c; !* 类似于 Element UI 警告框的边框 *!*/
    background-color: rgba(255, 235, 59, 0.1); /* 类似于 Element UI 警告框的背景色 */
    padding: 10px;
    position: relative;
  }

  .scroll-text {
    display: inline-block;
    padding-left: 100%; /* 初始位置在容器右侧 */
    animation: scroll 10s linear infinite; /* 滚动动画 */
  }

  @keyframes scroll {
    from {
      transform: translateX(0);
    }
    to {
      transform: translateX(-100%);
    }
  }

  .query-form-item {
    margin-right: 5px;
    margin-bottom: 6px;
  }

  #inputer {
    width: 100%;
    min-height: 30px;
    background-color: white;
    border: #d0d0d0;
    border-style: solid;
    border-width: 0.1px;
    color: #4a4a4a;
  }

  #inputer:focus {
    width: 100%;
    min-height: 30px;
    background-color: white;
    border: #0080ff;
    border-style: solid;
    border-width: 0.1px;
    color: #4a4a4a;
  }

  .ime-disabled {
    ime-mode: disabled;
  }

  .result-display {
    border: 2px solid #ccc; /* 默认外框颜色 */
    border-radius: 10px;
    margin-top: 5px;
    margin-left: 15px;
    margin-right: 25px;
    padding-left: 25px;
    /* 不设置背景颜色 */
  }

  .result-success {
    border-color: #4CAF50; /* 成功时外框颜色 */
  }

  .result-failure {
    border-color: #0080ff; /* 失败时外框颜色 */
  }

  .result-text {
    height: 18px;
    /* 你可以在这里设置默认的文本颜色或其他样式 */
  }

  .result-text-success {
    color: #4CAF50; /* 成功时文本颜色 */
    font-size: 14px;
  }

  .result-text-failure {
    color: #0080ff; /* 失败时文本颜色 */
    font-size: 14px;
  }

  .mar-left {
    margin-left: 20px;
  }
  </style>

