<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="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="productCode" class="query-form-item" label="产品编码:">
              <el-input
                v-model="relFormData.productCode"
                auto-complete="off"
                style="width: 90%"
                clearable
                :disabled="true"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="subTypeNo" class="query-form-item" label="类型编码:">
              <el-input
                v-model="relFormData.subTypeNo"
                auto-complete="off"
                style="width: 90%"
                clearable
                :disabled="true"
              ></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%"
                clearable
                :disabled="true"
              ></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%"
                clearable
                :disabled="true"
              ></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"
                :disabled="true"
                style="width: 90%"
              >
              </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"
                :disabled="true"
                style="width: 90%"
              >
              </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="请输入备注"
              ></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="addCode()"
                style="margin-left: 15px"
              >添加
              </el-button>
            </el-button-group>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item prop="checked" label="">
              <el-checkbox v-model="checked">录入父级编码</el-checkbox>
            </el-form-item>
          </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>
          <el-text tag="b" size="large">待关联数量：<span>0</span></el-text>
          <el-text tag="b">总关联数量：<span>0</span></el-text>
          <el-text tag="b" size="large">父级编码：<span>{{ a || '暂未录入'}}</span></el-text>
        </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="150" 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="150" prop="parentCode" show-overflow-tooltip></el-table-column>
            </el-table>
          </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {addRelCode,scanCodeRelCode} from "@/api/collect/relCode";
// import relCodeDetail from "@/views/collect/relCode/relCodeDetail";
import A from "@/plugins/KeyScaner";

export default {
  name: "relCodeEdit",
  props: {
    closeDialog: {
      type: Function,
      required: true,
    },
    orderQuery: {
      type: Object,
      required: true,
      default: {}
    },
    resetKey: {
      type: Function,
      required: true
    },

  },
  watch: {
    resetKey(newVal, oldVal) {
      this.$refs.inputRef.focus();
    }
  },
  data() {
    return {
      userInfo: {
        inv: this.$store.getters.locInvName,
        deptName: this.$store.getters.locDeptName,
        userName: this.$store.getters.name,
        userId: this.$store.getters.userId,
        companyName: this.$store.getters.companyName,
      },
      //扫码相关
      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,
      },
      detailList: [],
      checkPreInArray: [],
      errView: 0,
      isCodeAlive: true,
      isCheckResultAlive: true,
      isBizDetailAlive: true,
      isCodeDetailAlive: true,
      isSickerAlive: true,
      actionEnable: false,
      formRules: {
        productCode: [
          {required: true, message: "请输入产品编号", trigger: "blur"},
        ],
        subTypeNo: [
          {required: true, message: "请输入类型编号", trigger: "blur"},
        ],
        cascadeRatio: [
          {required: true, message: "请输入包装比例", trigger: "change"},
        ],
        packageSpec: [
          {required: true, message: "请输入包装规格", trigger: "change"},
        ],
        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,
      checked:true
    };
  },
  components: {
    // relCodeDetail
  },
  methods: {
    splitChange() {
      this.$refs.inputRef.focus();
    },
    //添加条码
    addCode() {
      let tQuery = {
        parentCode: this.scanCode,
      };
      scanCodeRelCode(tQuery).then((response) => {
        if (response.code === 20000) {
          this.$refs.inputRef.focus();
          this.$refs.inputRef.select();
          this.isSuccess = true;
          // this.codeFormData.code = response.data.code;
          console.log("====response=======",response.data)
          this.detailList.push(response.data);
          this.printCodeResult(response.data);
          this.scanCode = ""
        }else{
          this.$message.error(response.message);
        }
        this.loading = false;
      })
      .catch(() => {
        this.loading = false;
      });
    },


    refreshCodesPanel() {
      this.warnVisible = false;
      this.errVisible = false;

      this.isCodeAlive = false;
      this.isBizDetailAlive = false;
      this.isCodeDetailAlive = false;
      this.isSickerAlive = false;

      this.$nextTick(() => {
        //重新加载组件
        this.isCodeAlive = true;
        this.isBizDetailAlive = true;
        this.isCodeDetailAlive = true;
        this.isSickerAlive = true;

      });

      //选择性刷新
      if (this.isCheckResultAlive) {
        this.isCheckResultAlive = false;
        this.$nextTick(() => {
          //重新加载组件
          this.isCheckResultAlive = true;
        });
      }
    },

    refreshOrder(orderQuery) {
      this.relFormData = orderQuery;
      this.scanCode = "";
      this.result = "";
      this.refreshCodesPanel()
    },

    submit(val) {
      // if(this.detailList == null || this.detailList.length == 0){
      //   this.$message.error("请先录入关联码！");
      //   return;
      // }
      this.loading = true;
      let tQuery = Object.assign(this.relFormData);
      tQuery.detailList = this.detailList;
      addRelCode(tQuery).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.addCode()
    },
    printCodeResult(data, isSuccess) {
      const resultParts = ["扫码解析结果：" + data.curCode];

      if (data.packLayer) {
        resultParts.push("层级标识: " + data.packLayer);
      }
      if (data.parentCode) {
        resultParts.push("父级编码: " + data.parentCode);
      }
      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,
        detailList: [],
      }
      this.scanCode = "";
      this.result = "";
      this.detailList = [];
      // this.refreshCodesPanel()
    },

  },
  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() {

  },
};
</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;
}


</style>

