<template>
  <div>
    <el-card class="el-card">
      <el-form
        :model="filterQuery"
        size="mini"
        v-if="searchVisible"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item class="query-form-item" label-width="100px" label="UDI码:">
              <el-input
                id="inputer"
                v-model="filterQuery.code"
                placeholder="UDI码"
                ref='inputRef'
                @keypress.enter.native="enterKey($event)"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="query-form-item" label="供应商:" label-width="100px">
              <el-select
                v-model="filterQuery.supId"
                filterable
                remote
                clearable="true"
                reserve-keyword
                placeholder="请输入供应商名称"
                :remote-method="findMethod"
                size="mini"
                style="width: 100%"
                :loading="loading"
              >
                <el-option
                  v-for="item in fromOptions"
                  :key="item.name"
                  :label="item.name"
                  :value="item.erpId"
                >
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item style="display: flex;margin-left: 20px">
              <el-button type="primary" icon="search" @click="getList"
              >查询
              </el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table
        v-loading="loading"
        :data="list"
        border
        style="width: 100%"
        @row-click="getOrderDetail"
        highlight-current-row
      >
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="扫码单据类型" prop="action">
          <template slot-scope="scope">
            <span>{{ getActionName(scope.row.action) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="订单号"
          prop="billNo"
          show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="来源" prop="fromType">

          <template slot-scope="scope">
            <span>{{ fromTypeMap[scope.row.fromType] }}</span>
          </template>


        </el-table-column>
        <el-table-column label="往来单位" prop="fromName" width="250">

        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="actDate"
          width="150"
          show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click.native.stop="intentDetail(scope.row)"
            >详情
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>


      <pagination
        v-show="total>0"
        :total="total"
        :limit.sync="filterQuery.limit"
        :page.sync="filterQuery.page"
        @pagination="handleCurrentChange"
      ></pagination>
    </el-card>

    <el-card class="el-card" v-if="true" id="printJS-form">
      <el-table
        v-loading="loading"
        border
        :row-class-name="tableRowClassName"
        :data="detailList"
        style="width: 100%"
      >
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column
          label="产品通用名"
          prop="coName"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="包装规格"
          prop="spec"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="批次号"
          prop="batchNo"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="生产日期"
          prop="productDate"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="失效日期"
          prop="expireDate"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="单据数量"
          prop="count"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="实际数量"
          prop="reCount"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="生产企业"
          prop="manufacturer"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="注册/备案凭证号"
          prop="certCode"
          :show-overflow-tooltip="true"
        ></el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      title="单号详情"
      :visible.sync="codeDetailVisible"
      width="80%"
      append-to-body
      v-if="codeDetailVisible"
    >
      <codeDetail
        :idQuery="idQuery"
        v-on:closeDetailDialog="closeDetailDialog"
      ></codeDetail>
    </el-dialog>

  </div>
</template>

<script>
import {
  findAllByOrderId,
  deleteByOrderId,
  updateExportStatus,
  uploadOrder,
  orderDetail,
} from "../../../api/inout/order";
import draggable from "vuedraggable";
import {saveAs} from "file-saver";
import codeDetail from "../../inout/IOFinishCode";
import store from "../../../store";
import {getBussinessType} from "../../../api/basic/bussinessType";
import {filterOrderTrace} from "@/api/inventory/invCodeTrace";
import {getBasicUnitMaintains} from "@/api/basic/basicUnitMaintain";
import A from "../../../plugins/KeyScaner"

const formJson = {
  site_id: "",
  site_name: "",
  describe: "",
  ads: [],
};
export default {
  name: "invUdiTraceOrder",
  props: {
    isSelect: {
      type: Boolean,
      default: false,
    },
    diloadTrue: {
      type: Boolean,
      default: false,
    },
    udiCode: {
      type: Object,
      required: true,
    },
  },

  data() {
    return {
      filterQuery: {
        code: "",
        batchNo: null,
        productIdFk: null,
        customerId: null,
        page: 1,
        limit: 20,
        supId: null,
      },
      searchVisible: true,
      sitcomScan: false,
      checkStatus: {
        1: "校验异常",
        0: "未校验",
        2: "正常",
      },
      fromOptions: [],
      erpCheckStatus: {
        // error: "校验异常",
        // null: "未校验",
        // success: "正常",
        1: "校验异常",
        0: "未校验",
        2: "校验成功",
      },
      fromTypeMap: {
        "1": "UDIMS平台",
        "2": "网页新增",
        "3": "pda即时校验",
        "4": "pda未校验",
        "5": "pc端扫码精灵",
        "6": "缺量补录单据",
        "7": "UDI供应商平台",
        "8": "平衡补录单据",
        "10": "手动补单",
        "12": "采购计划",
        "13": "领用单据",
        "14": "第三方系统单据",
      },
      //往来单位
      unitquery: {key: "", page: 1, limit: 20},
      unitlist: [],
      list: [],
      detailList: [],
      unitUpdateQuery: {
        id: "",
        fromCorpId: "",
        fromCorp: "",
      },
      actDateRange: [],
      detailQuery: {
        orderId: "",
      },
      deleteData: {
        id: "",
      },
      idQuery: {
        id: "",
        billNo:""
      },
      curIndex: "",
      adListNoDataText: "无数据",
      queryAdIdAsyncLoading: false,
      codeDetailVisible: false,
      successOrderExportPDFSettingVisible: false,
      total: 0,
      loading: false,
      index: null,
      formName: null,
      orderId: "",
      formMap: {
        add: "新增",
        edit: "编辑",
      },
      exportQuery: {
        orderId: "",
        exportStatus: "",
      },

      uploadQuery: {
        orderId: "",
      },
      busTypes: [],
      dialogTableVisible: false,
      formLoading: false,
      formVisible: false,
      formData: formJson,
      deleteLoading: false,
      addDialogVisible: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  components: {
    draggable,
    codeDetail,
  },
  methods: {
    onReset() {
      this.$router.push({
        path: "",
      });
      this.filterQuery = {
        code: null,
        batchNo: null,
        productIdFk: null,
        customerId: null,
        page: 1,
        limit: 20,
        supId: null,
      };
      this.actDateRange = [];
      this.getList();
    },

    enterKey(event) {
      this.$refs.inputRef.select();
      this.onSubmit();
    },
    onSubmit() {
      this.getList();
    },
    handleSizeChange(val) {
      this.filterQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.filterQuery.page = val.page;
      this.getList();
    },

    findMethod(query) {
      console.log(query);
      this.fromOptions = [];
      let cQuery = {
        key: query,
      };
      getBasicUnitMaintains(cQuery)
        .then((response) => {
          this.loading = false;
          this.fromOptions = response.data.list || [];
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //获取订单列表
    getList() {
      this.loading = true;
      this.filterQuery.customerId = store.getters.customerId;
      if (!this.$isBlank(this.filterQuery.code)) {
        console.log(this.filterQuery.code)
        let code = this.filterQuery.code;
        this.filterQuery.code = code.replace("\r", "")
      }
      filterOrderTrace(this.filterQuery)
        .then((response) => {
          if (response.code == 20000) {
            this.loading = false;
            this.list = response.data.list || [];
            this.detailList = [];
            this.total = response.data.total || 0;
          } else {
            this.loading = false;
            this.$message.error(response.message);
          }


        })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },
    //业务明细表
    getOrderDetail(row) {
      this.loading = true;
      this.detailQuery = {
        orderIdFk: row.billNo,
      };
      this.refresgOrderDetail();
    },
    refresgOrderDetail() {
      orderDetail(this.detailQuery)
        .then((response) => {
          console.log(response)
          this.loading = false;
          this.detailList = response.data || [];
        })
        .catch(() => {
          this.loading = false;
          this.detailList = [];
        });
    },

    handleUnitClick(row) {
      this.curIndex = row.id;
      // this.dialogTableVisible = true;
    },
    intentDetail(row) {
      this.codeDetailVisible = true;
      this.idQuery.id = row.id;
      this.idQuery.billNo=row.billNo;
    },
    closeDialog() {
      this.successOrderExportPDFSettingVisible = false;
      this.getList();
    },

    deleteOrders(data) {
      this.loading = true;
      this.deleteData.id = data;
      deleteByOrderId(this.deleteData)
        .then((response) => {
          this.getList();
          this.refresgOrderDetail();
          this.$message({
            type: "success",
            message: "删除成功！",
          });
        })
        .catch(() => {
        });
    },
    tableRowClassName({row, rowIndex}) {
      if (row.reCount === row.count) {
        return "success-row";
      } else {
        return "warning-row";
      }
    },

    exportDialog(value) {
      var mOrder = value;
      if (mOrder.exportStatus === "已上传") {
        this.$confirm("该订单已修改, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.uploadOrderDialog(mOrder);
          })
          .catch(() => {
          });
      } else if (mOrder.contrastStatus === 0) {
        this.$confirm("该订单校验异常, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.uploadOrderDialog(mOrder);
          })
          .catch(() => {
          });
      } else if (mOrder.contrastStatus === null) {
        this.$confirm("该订单未校验, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.uploadOrderDialog(mOrder);
          })
          .catch(() => {
          });
      } else {
        this.$confirm("是否确定修改ERP订单?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.uploadOrderDialog(mOrder);
          })
          .catch(() => {
          });
      }
    },

    exportXml(poistion) {
      this.loading = true;
      var mOrder = this.list[poistion];
      var corpOrderId = mOrder.id;
      var codeArry;
      this.query = {
        corpOrderId: corpOrderId,
        page: 1,
        limit: 20,
      };
      findAllByOrderId(this.query) //查找该单号下的所有条码
        .then((response) => {
          this.loading = false;
          codeArry = response.data.list || [];
          var document =
            '<?xml version="1.0" encoding="utf-8"?>\n' +
            '<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="终端接口XML Schema-2.0.xsd" SN="" Version="3.0" License="123456">\n' +
            "<Events>\n" +
            '<Event Name="' +
            mOrder.action +
            '" MainAction="' +
            mOrder.mainAction +
            '">' +
            "<ActionMaping>\n" +
            '<Action Name="' +
            mOrder.mainAction +
            '">\n' +
            "<ActionData>Code</ActionData>\n" +
            "<ActionData>CorpOrderID</ActionData>\n" +
            "<ActionData>Actor</ActionData>\n" +
            "<ActionData>ActDate</ActionData>\n" +
            "<ActionData>ToCorpID</ActionData>\n" +
            "</Action>\n" +
            " </ActionMaping>\n" +
            "<DataMaping>\n" +
            '<MetaData Name="Code" Type="string" />\n' +
            '<MetaData Name="CorpOrderID" Type="string" />\n' +
            '<MetaData Name="Actor" Type="string" />\n' +
            '<MetaData Name="ActDate" Type="Date" />\n' +
            '<MetaData Name="ToCorpID" Type="string" />\n' +
            "</DataMaping>\n" +
            "<DataField>\n";
          for (var value of codeArry) {
            if (value.fromCorpId === null) {
              value.fromCorpId = "";
            }
            var tempdata =
              ' <Data Code="' +
              value.code +
              '" CorpOrderID="' +
              value.corpOrderId +
              '" Actor="' +
              value.actor +
              '" ActDate="' +
              value.actDate +
              '" ToCorpID="' +
              value.fromCorpId +
              '" />\n';

            document = document + tempdata;
          }
          document =
            document +
            "</DataField>\n" +
            "</Event>\n" +
            "</Events>\n" +
            "</Document>\n";

          var blob = new Blob([document], {
            type: "text/plain;charset=utf-8",
          });
          saveAs(blob, mOrder.action + mOrder.corpOrderId + ".xml");

          this.exportQuery.orderId = corpOrderId;
          this.exportQuery.exportStatus = "已上传";
          updateExportStatus(this.exportQuery).then((response) => {
            this.getList();
          });
        })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },

    uploadOrderDialog(value) {
      console.log(value.id + "---" + value.orderid);
      this.uploadQuery = {
        orderId: value.id,
      };
      uploadOrder(this.uploadQuery)
        .then((response) => {
          if (response.code === 20000) {
            this.$message.success(response.data);
            this.getList();
          } else {
            this.$message.error(response.message);
          }
        })
        .catch(() => {
        });
    },

    deleteDialog(rowId) {
      this.$confirm("此操作将永久删除该订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteOrders(rowId);
        })
        .catch(() => {
        });
    },
    closeDetailDialog(val) {
      this.codeDetailVisible = false;
    },
    closeManuDialog(val) {
      this.addDialogVisible = false;
      if (val) {
        this.$message.success("选入成功");
        this.refresgOrderDetail();
        this.getList();
      } else {
        this.$message.error("选入失败");
      }
    },
    cancelDialog() {
      this.addDialogVisible = false;
    },
    importOrder(row) {
      this.orderId = row.id;
      this.addDialogVisible = true;
    },
    getBusType() {
      let query = {
        enabled: true,
      };
      getBussinessType(query)
        .then((response) => {
          this.busTypes = response.data.list || [];
          this.filterQuery.billAction = this.busTypes[0].action;
          // this.getList();
        })
        .catch(() => {
        });
    },
    getActionName(action) {
      for (let i = 0; i < this.busTypes.length; i++) {
        if (this.busTypes[i].action === action) {
          return this.busTypes[i].name;
        }
      }
    },
  },
  filters: {
    statusFilterType(status) {
      const statusMap = {
        false: "success",
        true: "danger",
      };
      return statusMap[status];
    },
  },
  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) {
      //onInput事件在检测到回车键按下或在连续输入后超过500ms没有继续输入时触发
      if (text.includes("delete")) {
        that.filterQuery.code = "";
        return;
      }
      if (that.sitcomScan) {
        that.filterQuery.code = that.filterQuery.code;
      } else {
        that.filterQuery.code = text;
      }
    };
    inputer.focus();//别忘了给要监听的节点放置焦点，如果是div一类默认不具备焦点的节点需要给它加上“tabindex”属性。不建议传入document、Body等全局节点，可能会影响其它输入控件的流畅性。

  },

  created() {
    if (this.$isNotBlank(this.udiCode)) {

      if (!this.diloadTrue) {
        this.searchVisible = false;
      }
      console.log(this.diloadTrue + "----" + this.searchVisible);

      this.filterQuery.code = this.udiCode;
      this.getList();
    }
    this.getBusType();
  },
};
</script>


<style>
.el-table .warning-row {
  background: #ffb5b5;
}

.el-table .success-row {
  background: #ffffff;
}
</style>
