<template>
  <div>
    <el-card class="el-card">
      <el-form v-if="queryList && queryList.length > 0 && showSearch" :model="filterQuery" class="query-form"
               size="mini" label-width="100px">
        <el-row style=" display:flex;  flex-wrap: wrap; ">
          <template v-for="(item, index) in queryList">
            <el-form-item v-if="item.columnType == 'input' && executeEval(row,item.expression,true)"
                          class="query-form-item"
                          :label="item.columnDesc+`:`" :key="item.id">
              <el-input
                v-model="filterQuery[item.columnName]"
                :placeholder="item.columnDesc"
                :disabled="executeEval(null,item.disabledFuc,false)"
                @keyup.enter.native="executeFuc($event,'5',item.clickFuc)"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item v-if="item.columnType == 'select' && executeEval(row,item.expression,true)"
                          class="query-form-item"
                          :label="item.columnDesc+`:`">
              <el-select v-model="filterQuery[item.columnName]"
                         :placeholder="item.columnDesc"
                         :disabled="executeEval(null,item.disabledFuc,false)"
                         clearable>
                <el-option
                  v-for="dict in item.lableRuleObj"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="item.columnType == 'selectServer' && executeEval(row,item.expression,true)"
                          class="query-form-item"
                          :label="item.columnDesc+`:`">
              <el-select
                v-model="filterQuery[item.columnName]"
                :placeholder="item.columnDesc"
                @change="executeFuc($event,'5',item.checkRules)"
                :disabled="executeEval(null,item.disabledFuc,false)"
                filterable
                remote
                :remote-method="(query) => executeFuc(query,'5',item.clickFuc)"
                clearable>
                <el-option
                  v-for="item in options[item.clickFuc]"
                  :key="item.code"
                  :label="item.label"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="item.columnType == 'datePicker' && executeEval(row,item.expression,true)"
                          class="query-form-item"
                          :label="item.columnDesc+`:`">
              <el-date-picker
                :picker-options="pickerOptions"
                v-model="actDateRange"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item v-if="item.columnType == 'date' && executeEval(row,item.expression,true)"
                          class="query-form-item"
                          :label="item.columnDesc+`:`">
              <el-date-picker
                v-model="filterQuery[item.columnName]"
                :style="`width:${item.width+'px'}`"
                value-format="yyyy-MM-dd"
                :disabled="executeEval(null,item.disabledFuc,false)"
                type="date"
                :placeholder="item.columnDesc"
              ></el-date-picker>
            </el-form-item>
          </template>
        </el-row>
      </el-form>
      <div class="top-right-btn">
        <el-button-group>
          <el-button icon="el-icon-view" type="primary" @click="hideSearch">显示/隐藏搜索栏</el-button>
          <el-button
            type="primary"
            icon="el-icon-refresh"
            @click="onReset"
          >重置
          </el-button>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit"
          >查询
          </el-button
          >
          <el-button type="primary" icon="el-icon-plus" @click="addOrders">新增单据</el-button>
        </el-button-group>
      </div>
      <el-divider style="margin: 15px"></el-divider>
      <el-table v-loading="loading" :data="list" style="width: 100%" highlight-current-row
                border :default-sort="defaultSort"
                :row-style="{ height: '32px' }"
                @row-click="(row) => executeFuc(row,'0',tableObj.handleChangeFuc)"
                @sort-change="handleSortChange"
      >

        <el-table-column label="操作" width="100" fixed="right" v-if="splitType!='search'">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click.native.stop="editOrder(scope.row)"
            >编辑
            </el-button
            >
            <el-button
              type="text"
              size="small"
              @click.native.stop="deleteDialog(scope.row)"
            >删除
            </el-button
            >
          </template>
        </el-table-column>
        <template v-for="(item, index) in tableHeader">
          <el-table-column
            v-if="item.columnType == 'id' && executeEval(row,item.expression,true)"
            type="index" :label="item.columnDesc"></el-table-column>
          <el-table-column
            v-if="item.columnType == 'selection'"
            type="selection"
            :width="item.width"
            :selectable="(row,number) => executeFuc(row,'3',item.clickFuc)"
          ></el-table-column>

          <el-table-column
            v-if="item.columnType == 'radio' && executeEval(row,item.expression,true)"
            :prop="item.columnName"
            :label="item.columnDesc"
            :sortable="item.sort"
            :width="item.width"
            :show-overflow-tooltip="item.tooltip"
            :key="item.columnName"
          >
            <template slot-scope="scope">
              <el-radio :label="scope.row.id" v-model="radioCheck"><span></span></el-radio>
            </template>
          </el-table-column>
          <el-table-column
            v-if="item.columnType == 'laber' && executeEval(row,item.expression,true)"
            :prop="item.columnName"
            :label="item.columnDesc"
            :sortable="item.sort"
            :width="item.width"
            :show-overflow-tooltip="item.tooltip"
            :key="item.columnName"
          >
            <template slot-scope="scope">
              <span :style="{color: executeFuc(scope.row,'4',item.lableRuleObj[scope.row[item.columnName]])}">{{
                  item.lableRuleObj[scope.row[item.columnName]]
                }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="item.columnType == 'eltag' && executeEval(row,item.expression,true)"
            :prop="item.columnName"
            :label="item.columnDesc"
            :sortable="item.sort"
            :width="item.width"
            :show-overflow-tooltip="item.tooltip"
            :key="item.columnName"
          >
            <template slot-scope="scope">
              <el-tag
                :type="executeFuc(scope.row,'4',item,item.lableRuleObj?item.lableRuleObj[scope.row[item.columnName]]:scope.row[item.columnName])">
                <span>{{
                    item.lableRuleObj ? item.lableRuleObj[scope.row[item.columnName]] : scope.row[item.columnName]
                  }}</span>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            v-if="item.columnType == 'button' && executeEval(row,item.expression,true)"
            :prop="item.columnName"
            :label="item.columnDesc"
            :width="item.width"
            :key="item.columnName"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button v-for="(buttonItem, buttonIndex) in item.buttonRulObj"
                         :type="buttonItem.type"
                         :size="buttonItem.size"
                         :style="buttonItem.style"
                         :key="buttonItem"
                         v-if="executeEval(scope.row,buttonItem.hasPermi,true)"
                         :disabled="executeEval(scope.row,buttonItem.disabledFuc,false)"
                         @click.native.stop="executeFuc(scope.row,'1',buttonItem.clickFuc)"
              >{{ buttonItem.name }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            v-if="item.columnType == 'text' && executeEval(row,item.expression,true)"
            :prop="item.columnName"
            :label="item.columnDesc"
            :sortable="item.sort"
            :width="item.width"
            :show-overflow-tooltip="item.tooltip"
            :key="item.columnName"
          >
            <template slot-scope="scope">
              <span :style="{color: executeFuc(scope.row,'4',item,scope.row[item.columnName])}">{{
                  scope.row[item.columnName]
                }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <el-dialog
        :title="titleMap[title]"
        :visible.sync="addOrderVisible"
        width="85%"
        append-to-body
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        v-if="addOrderVisible"
        @close='closeDialog'
      >
        <addOrder
          :closeDialog="closeDialog"
          :orderQuery="idQuery"
          :splitBusType="splitBusType"
          :viewType="viewType"
          :dialogTitle="title"
        ></addOrder>
      </el-dialog>
      <el-dialog
        title="异常扫码单"
        :visible.sync="errOrderVisible"
        width="85%"
        append-to-body
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        v-if="errOrderVisible"
        @close='closeDialog'
      >
        <err-order
        ></err-order>
      </el-dialog>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="filterQuery.page"
        :limit.sync="filterQuery.limit"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script>
import {
  deleteByOrderId,
  getOrderList, submitCodes
} from "@/api/inout/order";
import addOrder from "@/views/inout/DialogCreateOrder";
import errOrder from "@/views/inout/IoCreateErrorOrder";
import {getInvListByUserOptimize} from "@/api/system/invWarehouse";
import {getLocalJoinByUserOptimize} from "@/api/basic/busType";
import {getCorrespondence} from "@/api/basic/basicUnitMaintain";
import {
  getHead, executeFuc
} from "@/utils/customConfig";
import {convertDate} from "@/utils/date";
import {isBlank} from "@/utils/strUtil";
import {getBizDetailList} from "@/api/inout/orderDetailBiz";
import {getCodeList} from "@/api/inout/code";

export default {
  name: "IoSplitScanCode",
  data() {
    return {

      //界面配置---------------------
      tableObj: [],
      queryList: [],
      tableHeader: [],
      fromList: [],

      tableObj2: [],
      queryList2: [],
      tableHeader2: [],
      fromList2: [],

      tableObj4: [],
      queryList4: [],
      tableHeader4: [],
      fromList4: [],
      convertDateFun: convertDate,
      defaultSort: {prop: 'createTime', order: 'desc'},
      options: {
        getInvList: [],
        getDeptList: [],
        getBusType: [],
      },
      //界面配置---------------------end

      total: 0,
      radioCheck: false,
      currentRow: {},
      showSearch: true,
      titleMap: {
        add: "新增单据",
        edit: "编辑单据",
        splitAddIn: "工位上货-新增",
        splitEditIn: "工位上货-编辑",
        splitAddOut: "工位退货-新增",
        splitEditOut: "工位退货-编辑",
      },
      title: "add",
      filterQuery: {
        id: "",
        billNo: null,
        mainAction: null,
        action: null,
        statusType: "scan_code",
        page: 1,
        limit: 10,
        startTime: null,
        endTime: null,
        keyWords: null,
        invCode: this.$store.getters.locInvCode,
        vueType: null,
      },
      fromOptions: [],
      checkStatus: {
        1: "草稿",
        2: "等待处理",
        3: "等待校验",
        4: "处理异常",
        5: "校验成功",
        6: "校验异常",
        7: "已审核",
        8: "审核拒绝",
        9: "正在处理", 10: "待审核", 11: "待配货",
      },
      curIndex: "",
      idQuery: {},
      storageList: [],
      invList: [],
      list: [],
      addOrderVisible: false,
      errOrderVisible: false,
      loading: false,
      index: null,
      formName: null,
      errorDetail: "",
      formMap: {
        add: "新增",
        edit: "编辑",
      },
      enableDept: false,
      splitBusType: "SC72197936495755",
      fromTypeMap: {
        "1": "UDIMS平台",
        "2": "网页新增",
        "3": "pda即时校验",
        "4": "pda未校验",
        "5": "pc端扫码精灵",
        "6": "流转自动补单",
        "7": "UDI供应商平台",
        "8": "平衡补录单据",
        "10": "手动补单",
        "11": "仓库盘点",
        "12": "采购计划",
        "13": "领用单据",
        "14": "第三方系统单据",
      },
      deleteData: {
        billNo: "",
        status: 10,
      },
      dialogTableVisible: false,
      formLoading: false,
      deleteLoading: false,
      busTypes: [],
      actDateRange: [],
      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]);
            },
          },
        ],
      },
      viewType: 2,
      bizQuery: {
        productName: null,
        orderIdFk: null,
        page: 1,
        limit: 10
      },
      bizTotal: 0,
      bizDetailLoading: false,
      bizDetailList: [],
      codeQuery: {
        orderIdFk: null,
        page: 1,
        limit: 10
      },
      codeTotal: 0,
      codeDetailLoading: false,
      codeDetailList: [],
      resultQuery: {
        orderId: null,
        code: null,
        page: 1,
        limit: 10
      },
      resultTotal: 0,
      resultDetailLoading: false,
      resultDetailList: [],
      stockChangeVisible: false,
      curRow: null,
      //out:预出库扫码;return:预出库退回;search:预出库单查询
      splitType: null,
    };
  },
  components: {
    addOrder, errOrder
  },
  methods: {
    onReset() {
      this.filterQuery = {
        ...this.filterQuery,
        id: "",
        billNo: null,
        mainAction: null,
        action: null,
        statusType: null,
        page: 1,
        limit: 10,
        startTime: null,
        endTime: null,
        invCode: this.$store.getters.locInvCode,
      };
      this.actDateRange = [];
      this.getList();
    },
    onSubmit() {
      if (this.actDateRange !== null) {
        this.filterQuery.startTime = this.actDateRange[0];
        this.filterQuery.endTime = this.actDateRange[1];
      } else {
        this.filterQuery.startTime = null;
        this.filterQuery.endTime = null;
      }
      this.filterQuery.page = 1;
      this.getList();
    },
    hideSearch() {
      this.showSearch = !this.showSearch;
    },
    getBusType(_this) {
      let query = {
        code: this.filterQuery.invCode,
        enabled: true,
      };
      getLocalJoinByUserOptimize(query)
        .then((response) => {
          _this.options.getBusType = response.data || [];
          _this.getList();
        })
        .catch(() => {
        });
    },
    addOrders() {
      this.idQuery = {};
      this.title = "add";
      this.addOrderVisible = true;
    },

    editOrder(row) {
      this.idQuery = row;
      this.title = "edit";
      this.addOrderVisible = true;
    },

    closeDialog() {
      this.addOrderVisible = false;
      this.addHosOrderVisible = false;
      this.getList();
    },

    handleSortChange(column, prop, order) {
      if (column.order === 'descending') {
        this.filterQuery.sort = 'desc'
      } else {
        this.filterQuery.sort = 'asc'
      }
      this.filterQuery.orderBy = column.prop;
      this.getList();
    },
    //获取订单列表
    getList() {
      this.loading = true;
      getOrderList(this.filterQuery)
        .then((response) => {
          this.loading = false;
          if (response.code === 20000) {
            this.list = response.data.list || [];
            this.total = response.data.total || 0;
          } else {
            this.$message.error(response.message);
          }
        })
        .catch((error) => {
          this.$message.error(error.message)
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },
    deleteOrders(data) {
      this.loading = true;
      this.deleteData.billNo = data;
      deleteByOrderId(this.deleteData)
        .then((response) => {

          if (response.code == 20000) {
            this.getList();
            this.$message({
              type: "success",
              message: "删除成功！",
            });
          } else if (response.code == 520) {
            this.$message.error("新增扫码单据列表已不存在该扫码单据！");
            this.getList();
          } else {
            this.$message.error(response.message);
            this.getList();
          }

        })
        .catch(() => {
        });
    },
    deleteDialog(row) {
      this.$confirm("此操作将永久删除该订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteOrders(row.billNo);
        })
        .catch(() => {
        });
    },


    onUpload(data) {
      this.loading = true;
      var idQuery = {
        billNo: "",
      };
      idQuery.billNo = data;
      submitCodes(idQuery)
        .then((response) => {
          this.loading = false;
          if (response.code === 20000) {
            this.$message.success("提交成功");
            this.getList();
          } else {
            this.$message.error(response.message);
          }
          this.loading = false;
        });
    },
    getInvList(_this) {
      getInvListByUserOptimize()
        .then((response) => {
          _this.options.getInvList = response.data || [];
          _this.getList();
        })
        .catch(() => {
        });
    },
    invChange(_this) {
      _this.filterQuery.action = null;
      _this.getBusType(_this);
    },

    findMethod(query) {
      this.fromOptions = [];
      let cQuery = {
        key: query,
        corpType: 2,
        page: 1,
        limit: 10,
      };
      getCorrespondence(cQuery)
        .then((response) => {
          this.loading = false;
          this.fromOptions = response.data.list || [];
        })
        .catch(() => {
          this.loading = false;
          this.fromOptions = [];
        });
    },
    statusFilterType(status) {
      const statusMap = {
        2: "warning",
        1: "warning",
        4: "danger",
        3: "success",
      };
      return statusMap[status];
    },

    errOrderDialog() {
      this.errOrderVisible = true;
    },
    executeFuc(row, type, clickFuc, value) {
      return executeFuc(this, row, type, clickFuc, value);
    },
    executeEval(row, expression, defaultRet) {
      if (expression) {
        return eval(expression);
      }
      return defaultRet;
    },
    handleSelectionChange(_this, val) {
      _this.currentRow = val;
      _this.getOrderDetails();
    },
    getOrderDetails() {
      this.bizQuery.page = 1;
      this.codeQuery.page = 1;
      this.resultQuery.page = 1;
      this.getBizDetailList();
      this.getCodeList();
    },
    onBizReset() {
      this.bizQuery = {
        productName: null,
        orderIdFk: null,
        page: 1,
        limit: 10
      };

      if (!isBlank(this.currentRow.billNo)) {
        this.getBizDetailList();
      }
    },
    onBizSubmit() {
      this.bizQuery.page = 1;
      this.getBizDetailList();
    },
    getBizDetailList() {
      if (isBlank(this.currentRow.billNo)) {
        this.$message.error("请先选择需要查询的单据！")
        return;
      }
      this.bizDetailLoading = true;
      this.bizQuery.page = null;
      this.bizQuery.limit = null;
      this.bizQuery.orderIdFk = this.currentRow.billNo;
      getBizDetailList(this.bizQuery).then((res) => {
        this.bizDetailLoading = false;
        if (res.code === 20000) {
          this.codeDetailList = res.data.list || [];
          this.bizTotal = res.data.total || 0;
        } else {
          this.$message.error(res.message);
          this.codeDetailList = [];
          this.bizTotal = 0;
        }
      }).catch((error) => {
        this.bizDetailLoading = false;
        this.$message.error(error.message);
        this.bizDetailList = [];
        this.bizTotal = 0;
      })
    },
    onCodeReset() {
      this.codeQuery = {
        orderIdFk: null,
        page: 1,
        limit: 10
      };
      this.getCodeList();
    },
    onCodeSubmit() {
      this.codeQuery.page = 1;
      this.getCodeList();
    },
    getCodeList() {
      if (isBlank(this.currentRow.billNo)) {
        this.$message.error("请先选择需要查询的单据！")
        return;
      }

      this.resultQuery.orderId = this.currentRow.billNo;
      this.resultDetailLoading = true;
      getCodeList(this.resultQuery).then((res) => {
        this.resultDetailLoading = false;
        if (res.code === 20000) {
          this.resultDetailList = res.data.list || [];
          this.resultTotal = res.data.total || 0;
        } else {
          this.$message.error(res.message);
          this.resultDetailList = [];
          this.resultTotal = 0;
        }
      }).catch((error) => {
        this.resultDetailLoading = false;
        this.$message.error(error.message);
        this.resultDetailList = [];
        this.resultTotal = 0;
      });
    },

  },
  mounted() {
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
  },
  created() {
    this.getInvList(this);
    this.getBusType(this);

    this.splitType = this.$route.query.splitType;
    if (this.splitType == "search") {
      this.filterQuery.vueType = "splitOrder";
      this.filterQuery.statusType = 'split_finish';
    } else if (this.splitType == "out") {
      this.filterQuery.action = 'SC72197936495755';
      this.filterQuery.statusType = 'scan_code';
    } else if (this.splitType == "return") {
      this.filterQuery.action = 'SC72249388338364';
      this.filterQuery.statusType = 'scan_code';
    }

    getHead("IoSplitScanCode", "1").then((re) => {
      // 处理返回的数据
      this.tableObj = re.data;
      this.tableHeader = re.data.tableList;
      this.queryList = re.data.queryList;
      this.fromList = re.data.fromList;
      this.getList();
    });
  },
};
</script>

<style scoped>
.query-form {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}
.query-form-item {
  margin-right: 5px;
  margin-bottom: 6px;
}

</style>

