<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="68px"
    >
      <QueryFormWrapper>
        <el-col :span="8">
          <el-form-item label="送货批次" prop="deliverBatch">
            <el-input
              v-model="queryParams.deliverBatch"
              placeholder="请输入送货批次"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="送货单号"
            prop="deliveryOrderNo"
            label-width="88px"
          >
            <el-input
              v-model="queryParams.deliveryOrderNo"
              placeholder="请输入送货单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物料编码" prop="materialNo">
            <el-input
              v-model="queryParams.materialNo"
              placeholder="请输入物料编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <div slot="right">
          <el-form-item label-width="0" class="text-right" style="word">
            <EasyAdvancedQuery
              class="mr10"
              label-width="98px"
              @advQuery="advQuery"
            >
              <template #default="{ model }">
                <el-row :gutter="10" type="flex">
                  <el-col :span="12">
                    <el-form-item label="采购订单" prop="purchaseOrderNo">
                      <el-input
                        v-model="model.purchaseOrderNo"
                        placeholder="请输入采购订单"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="物料名称" prop="materialName">
                      <el-input
                        v-model="model.materialName"
                        placeholder="请输入物料名称"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="单据状态" prop="status">
                      <DictSelect
                        v-model="model.status"
                        placeholder="请选择单据状态"
                        dict-type=""
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="单据日期" prop="createTime">
                      <el-date-picker
                        v-model="model.createTime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :default-time="['00:00:00', '23:59:59']"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
            </EasyAdvancedQuery>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </div>
      </QueryFormWrapper>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="small"
          icon="el-icon-printer"
          @click="handlePrintSupplier"
          >送货单打印</el-button
        >
      </el-col>
      <right-toolbar
        :columns="columnsList"
        :show-search.sync="showSearch"
        @saveSetting="getColumnsList"
        @queryTable="getList"
      />
    </el-row>

    <!-- 列表 -->
    <AutoResizer :given-height="177">
      <template #default="{ height }">
        <el-table
          v-if="columnsList.length > 0"
          ref="multipleTable"
          v-loading="loading"
          :data="list"
          :height="height"
          border
          :span-method="arraySpanMethod"
          @selection-change="tableSelected"
          @select="select"
          @select-all="selectAll"
        >
          <el-table-column
            type="selection"
            width="55"
            fixed="left"
            align="center"
          />
          <el-table-column
            v-if="columnsList[0].visible"
            :key="Math.random()"
            label="送货单号"
            align="center"
            prop="deliveryOrderNo"
            width="160"
            fixed="left"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-button type="text" @click="handleDiveryDetail(scope.row)">{{
                scope.row.deliveryOrderNo
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[1].visible"
            :key="Math.random()"
            label="送货批次"
            align="center"
            prop="deliverBatch"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[2].visible"
            :key="Math.random()"
            label="物料编号"
            align="center"
            prop="materialNo"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[3].visible"
            :key="Math.random()"
            label="物料名称"
            align="center"
            prop="materialName"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[4].visible"
            :key="Math.random()"
            label="采购订单"
            align="center"
            prop="purchaseOrderNo"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[5].visible"
            :key="Math.random()"
            label="送货数量"
            align="center"
            prop="deliveryQty"
          />
          <el-table-column
            v-if="columnsList[6].visible"
            :key="Math.random()"
            label="长度"
            align="center"
            prop="length"
            width="100"
          />
          <el-table-column
            v-if="columnsList[7].visible"
            :key="Math.random()"
            label="宽度"
            align="center"
            prop="width"
            width="100"
          />
          <el-table-column
            v-if="columnsList[8].visible"
            :key="Math.random()"
            label="厚度"
            align="center"
            prop="thickness"
            width="100"
          />
          <el-table-column
            v-if="columnsList[9].visible"
            :key="Math.random()"
            label="预计到货日期"
            align="center"
            prop="expectArriveDate"
            width="180"
          />
          <el-table-column
            v-if="columnsList[10].visible"
            :key="Math.random()"
            label="包数"
            align="center"
            prop="bagQty"
            width="120"
          />
          <el-table-column
            v-if="columnsList[11].visible"
            :key="Math.random()"
            label="每包数量"
            align="center"
            prop="pieceQty"
            width="120"
          />
          <el-table-column
            v-if="columnsList[12].visible"
            :key="Math.random()"
            label="尾数"
            align="center"
            prop="mantissaQty"
          />
          <el-table-column
            v-if="columnsList[13].visible"
            :key="Math.random()"
            label="生产日期"
            align="center"
            prop="produceDate"
            width="180"
          />
          <el-table-column
            v-if="columnsList[14].visible"
            :key="Math.random()"
            label="单据日期"
            align="center"
            prop="createTime"
            width="180"
          />
          <el-table-column
            v-if="columnsList[15].visible"
            :key="Math.random()"
            label="规格"
            align="center"
            prop="size"
            width="120"
          />
          <el-table-column label="操作" align="center" width="80" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                class="text-danger"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
    </AutoResizer>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 单据打印 -->
    <IssuePrinit ref="issuePrinit" />
  </div>
</template>

<script>
import {
  getDeliveryNoticePage,
  deleteDeliveryNotice,
} from "@/api/wms/orders/deliveryNotice";
import IssuePrinit from "../output/productionIssue/issueDetails/IssuePrinit.vue";
const AccessTokenKey = "ACCESS_TOKEN";
import { getFormColumnsList } from "@/api/system/saveColumns/index";
import { mapGetters } from "vuex";
import { isArray } from "min-dash";

export default {
  name: "DeliveryNotice",
  components: {
    IssuePrinit,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      synchronizationLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // ERP采购订单主列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      ids: "",
      currentRows: [],
      tokens: "",
      baseUrl: "",
      reportId: "",
      // 高级查询参数
      advParams: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        erpOrderId: null,
        erpOrderNo: null,
        erpOrderTime: [],
        billAmount: null,
        billType: null,
        taxAmount: null,
        totalAmount: null,
        supplierCode: null,
        documentType: null,
        status: null,
        sourceOrderNo: null,
        sourceOrderType: null,
        exchangeRate: null,
        erpMdtime: [],
        createTime: [],
        erpMark: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 显示隐藏列参数
      columns: [
        { key: 0, label: "送货单号", visible: true },
        { key: 1, label: "送货批次", visible: true },
        { key: 2, label: "物料编码", visible: true },
        { key: 3, label: "物料名称", visible: true },
        { key: 4, label: "采购订单", visible: true },
        { key: 5, label: "送货数量", visible: true },
        { key: 6, label: "长度", visible: true },
        { key: 7, label: "宽度", visible: true },
        { key: 8, label: "厚度", visible: true },
        { key: 9, label: "预计到货日期", visible: true },
        { key: 10, label: "包数", visible: true },
        { key: 11, label: "每包数量", visible: true },
        { key: 12, label: "尾数", visible: true },
        { key: 13, label: "生产日期", visible: true },
        { key: 14, label: "单据日期", visible: true },
        { key: 15, label: "规格", visible: true },
      ],
      // 显示隐藏持久化参数
      columnsList: [],
    };
  },
  // 获取当前登录用户id
  computed: {
    ...mapGetters(["userId"]),
  },
  created() {
    this.getColumnsList();
    this.getList();
    this.tokens = localStorage.getItem(AccessTokenKey);
    this.baseUrl = process.env.VUE_APP_REPORT_API;
    this.reportId = this.$route.meta.reportId[0];
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      const params = { ...this.queryParams, ...this.advParams };
      getDeliveryNoticePage(params)
        .then((response) => {
          this.list = response.data.list;
          this.total = response.data.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        erpOrderId: undefined,
        erpOrderNo: undefined,
        erpOrderTime: undefined,
        billAmount: undefined,
        billType: undefined,
        taxAmount: undefined,
        totalAmount: undefined,
        supplierCode: undefined,
        documentType: undefined,
        status: undefined,
        sourceOrderNo: undefined,
        sourceOrderType: undefined,
        exchangeRate: undefined,
        erpMdtime: undefined,
        erpMark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.advParams = {};
      this.handleQuery();
    },

    /** 查看明细 */
    handleView(row) {
      const { id } = row;
      this.$refs.purchaseDetail.queryParams.inStockId = id;
      this.$refs.purchaseDetail.open = true;
    },
    // 表格选中
    tableSelected(val) {
      this.currentRows = val;
      const list = this.currentRows.map((item) => item.deliveryOrderNo);
      this.ids = list.join(",");
    },
    select(selection, row) {
      if (selection.length > 1) {
        const del_row = selection.shift();
        this.$refs.multipleTable.toggleRowSelection(del_row, false);
      }
    },
    selectAll(selection) {
      if (selection.length > 1) {
        selection.length = 1;
      }
    },
    // 合并
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      const newData = this.list.map((item, index) => {
        const filterData = this.list.filter((ele) => {
          return item.deliveryOrderNo === ele.deliveryOrderNo;
        });
        const dataIndex = this.list.findIndex((eleIndex) => {
          return item.deliveryOrderNo === eleIndex.deliveryOrderNo;
        });
        if (index === dataIndex) {
          item.rowspan = filterData.length;
        } else {
          item.rowspan = 0;
        }
        return newData;
      });
      if (columnIndex === 0 || columnIndex === 1) {
        return {
          rowspan: row.rowspan,
          colspan: 1,
        };
      } else {
        return false;
      }
    },
    // 送货单打印
    handlePrintSupplier() {
      if (this.currentRows.length === 0) {
        this.$modal.msgWarning("请选择您要打印的单据!");
        return;
      }
      const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&deliveryOrderNo=${this.ids}`;
      this.$refs.issuePrinit.dialogVisible = true;
      this.$refs.issuePrinit.title = "送货通知单";
      this.$refs.issuePrinit.src = src;
    },
    // 送货通知单明细
    handleDiveryDetail(row) {
      const { deliveryOrderNo } = row;
      this.$router.push({
        path: "/orders/delivery-notice-details",
        query: { deliveryOrderNo },
      });
    },
    // 高级查询
    advQuery(advQueryParams) {
      this.advParams = advQueryParams;
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const { id, materialNo } = row;
      const message = `是否确认删除物料编码为【${materialNo}】的送货通知单?`;
      this.$modal
        .confirm(message)
        .then(function () {
          return deleteDeliveryNotice(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 获取显示隐藏列
    getColumnsList() {
      const { componentName } = this.$route.meta || null;
      const params = {
        userId: this.userId,
        vueForm: componentName,
      };
      getFormColumnsList(params)
        .then((res) => {
          if (isArray(res.data)) {
            this.columnsList = res.data.length === 0 ? this.columns : res.data;
            // 对比默认数据和接口数据，将缺失的列添加到接口数据中
            this.columnsList = this.columns.reduce((acc, defaultColumn) => {
              const found = res.data.find(
                (apiColumn) => apiColumn.key === defaultColumn.key
              );
              if (!found) {
                acc.push({
                  ...defaultColumn,
                  vueForm: componentName,
                  userId: this.userId,
                  id: null,
                });
              }
              return acc;
            }, res.data);
          } else {
            this.columnsList = this.columns;
          }
        })
        .catch((err) => {
          if (err) {
            this.columnsList = this.columns;
          }
        });
    },
  },
};
</script>
