<template>
  <div>
    <el-card style="margin-top: -20px">
      <el-form :model="formData" ref="dataForm" label-width="100px">
        <el-button-group style="display: flex;margin: 0px 0 10px 80%; height: 35px">
          <el-button
            type="primary"
            @click.native="checkFinish()"
          >完成核对
          </el-button
          >
          <el-button
            type="primary"
            @click.native="renewAccept()"
          >重新核对
          </el-button
          >
        </el-button-group>
        <el-row>
          <el-col :span="11">
            <el-form-item prop="fromCorp" label="单据编号:">
              <el-input v-model="formData.billNo" auto-complete="off"
                        disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="fromCorp" label="单据时间:">
              <el-input v-model="formData.createTime" auto-complete="off"
                        disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item prop="fromCorp" label="单据类型:">
              <el-input v-model="formData.billTypeName" auto-complete="off"
                        disabled
                        clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="fromCorp" label="收货仓库:">
              <el-input v-model="formData.invName" auto-complete="off"
                        disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="11">
            <el-form-item prop="fromCorp" label="送货单位:">
              <el-input v-model="formData.fromCorpName" auto-complete="off"
                        disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item prop="code" label="扫码校验:">
              <el-input
                id="inputer"
                placeholder="请输入UDI码"
                @focus="getInputFocus($event)"
                @keypress.enter.native="enterKey($event)"
                ref='inputRef'
                style="ime-mode:disabled"
                type="tel"
                v-model="udiCode"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button
              type="primary"
              size="small"
              @click.native.stop="addCode()"
              style="height: 31px; margin-left: 20px"
            >添加
            </el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card>
      <el-table v-loading="detailLoading"
                :data="detailList"
                border
                :row-style="rowStyle"
                :cell-style="{padding:6+'px'}"
                style="width: 100%">
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column label="物资名称" width="160" prop="coName"></el-table-column>
        <el-table-column label="规格型号" width="160" prop="spec"></el-table-column>
        <el-table-column label="批次号" width="100" prop="batchNo"></el-table-column>
        <el-table-column label="单据数量" width="100" prop="count"></el-table-column>
        <el-table-column label="审核数量" width="100" prop="acceptCount"></el-table-column>
        <el-table-column label="生产日期" width="120" prop="productDate"></el-table-column>
        <el-table-column label="失效日期" width="120" prop="expireDate"></el-table-column>
        <el-table-column label="价格" width="120" prop="price"></el-table-column>
        <el-table-column width="100" label="计量单位" prop="measname">
        </el-table-column>
        <el-table-column label="注册/备案号" width="150" prop="certCode"></el-table-column>

        <!--        <el-table-column label="销售清单号（第二票）" width="180" prop="secSalesListNo">-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="销售发票号（第一票）" width="180" prop="firstSalesInvNo">-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="销售发票号（第二票）" width="180" prop="secSalesInvNo">-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="发票日期" width="150" prop="invoiceDate">-->
        <!--        </el-table-column>-->
      </el-table>
    </el-card>
  </div>

</template>

<script>
import A from "../../plugins/KeyScaner"
import {updateStatus, enterCodeWeb, thirdUpdateStatus} from "@/api/inout/order";
import {getAcceptOrder, acceptClear, acceptAddCode, getAcceptStatus} from "@/api/inout/acceptOrder";


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

  },
  data() {
    return {
      formData: {},
      loading: false,
      detailLoading: false,
      udiCode: null,
      sictomText: "",
      originCode: "",
      checkSuccess: false,
      detailList: [],
      query: {
        code: "",
        corpOrderId: "",
        page: 1,
        limit: 10,
      },
    }
  },

  components: {},

  methods: {

    rowStyle({row, rowIndex}) {
      let rowBackground = {};
      if (row.reCount != row.acceptCount) {
        rowBackground.color = '#f60303';
      }
      return rowBackground;
    },


    handleCurrentChange(val) {
      this.query.page = val;
      this.getCodeList();
    },


    enterKey(event) {
      this.checkSuccess = true;
      let tQuery = {
        originCode: this.originCode,
        code: this.udiCode.trim(),
      }
      if (tQuery.code.includes(tQuery.originCode.substr(0,tQuery.originCode.length-1))) {
        tQuery.originCode = "";
      }
      enterCodeWeb(tQuery).then((response) => {
        if (response.code === 20000) {
          this.$refs.inputRef.focus();
          this.$refs.inputRef.select();
          this.udiCode = response.data;
          this.originCode = "";
          this.addCode(event);
        } else {
          if (response.code == 502) {
            this.checkSuccess = false;
            this.udiCode = response.data;
            this.originCode = this.udiCode;
          } else if (response.code == 501) {
            this.checkSuccess = false;
            this.originCode = "";
            this.$message.error(response.message);
          } else if (response.code == 503) {
            this.checkSuccess = false;
            this.udiCode = response.data;
            this.$confirm(response.message, "提示", {
              type: "warning",
            })
              .then(() => {
                this.udiCode = response.data;
                this.addCode();
              })
              .catch(() => {
                this.udiCode = this.originCode;
              });

          } else if (response.code == 508) {
            this.originCode = "";
            this.udiCode = "01" + response.data.nameCode;
            this.originCode = this.udiCode;
          } else {
            this.originCode = "";
            this.$alert(response.message, '提示', {
              confirmButtonText: '确定',
              type: 'warning',
              closeOnClickModal: true,
              callback: action => {
                this.$refs.inputRef.focus();
                this.$refs.inputRef.select();
              }
            });
          }
        }
        this.loading = false;
      });
    },

    addCode(event) {
      if (this.$isBlank(this.udiCode)) {
        this.$message.error("UDI码不能为空！");
      }
      let postQuery = {
        billNo: this.orderQuery.billNo,
        orderDetailEntities: this.detailList,
        code: this.udiCode,
      }


      acceptAddCode(postQuery)
        .then((response) => {
          if (response.code == 20000) {
            this.detailLoading = false;
            this.detailList = response.data.orderDetailEntities || [];
            if (response.data.finishAccept) {
              this.$confirm("核对结果正确,是否立即完成核对？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  this.postAccept();
                })
                .catch(() => {
                });
            } else {
              this.$message.success("匹配成功！");
              if (event == null) {
              } else event.target.select();
              this.$refs.inputRef.select();
            }

          } else {
            this.$message.error(response.message);
            if (event == null) {
            } else event.target.select();
            this.$refs.inputRef.select();
          }


        })
        .catch(() => {
          this.detailLoading = false;
        });


    },

    getInputFocus(event) {
      event.currentTarget.select();
    },


    checkFinish() {
      let query = {
        //orderId: this.orderQuery.billNo,
        billNo: this.orderQuery.billNo,
      };
      getAcceptStatus(query)
        .then((response) => {
          if (response.code == 20000) {
            let tip = "核对结果正确,是否立即完成核对？";
            this.finishAccept(tip);
          } else {
            let tip = "核对未完成,是否强制完成核对此单据？";
            this.finishAccept(tip);
          }
        })
        .catch(() => {
        });


    },


    finishAccept(tip) {
      this.$confirm(tip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.postAccept();

      }).catch(() => {
        // this.$message.info('回退失败');
      });

    },
    postAccept() {
      let query = {
        orderId: this.orderQuery.billNo,
      };
      thirdUpdateStatus(query)
        .then((response) => {
          if (response.code == 20000) {
            this.$message.success("核对成功！");
            this.closeDialog();
            this.$emit('childByValue', 1)
          } else {
            this.$message.error(response.message);
          }
        })
        .catch(() => {
        });
    },

    renewAccept() {
      let query = {
        billNo: this.orderQuery.billNo,
      }
      acceptClear(query)
        .then((response) => {
          this.detailLoading = false;
          this.detailList = response.data.orderDetailEntities || [];
        })
        .catch(() => {
          this.detailLoading = false;
          this.detailList = [];
        });
    },


    getOrderDetail() {
      this.detailLoading = true;
      let query = {
        billNo: this.orderQuery.billNo,
      }
      getAcceptOrder(query)
        .then((response) => {
          this.detailLoading = false;
          this.detailList = response.data.orderDetailEntities || [];
          if (response.data.exitAccept) {
            this.$confirm("检测到上一次验收操作未完成, 是否继续上一次验收?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
              })
              .catch(() => {
                this.renewAccept();
              });
          }

        })
        .catch(() => {
          this.detailLoading = false;
          this.detailList = [];
        });
    }

  },


  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.udiCode = "";
        that.sictomText = "";
        that.originCode = "";
        return;
      }
      if (that.sitcomScan) {
        let tempTxt = text;
        let str = tempTxt.replace(/[\r]/g, "");
        that.sictomText = that.sictomText + str;
        that.udiCode = that.sictomText;
      } else {
        that.udiCode = text;
      }
    };
    inputer.focus();


  },
  created() {

    this.formData = this.orderQuery;
    this.getOrderDetail()
  },


}
</script>

<style scoped>


#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;

}
</style>
