<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['wms:material-transaction:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="$route.name === 'OtherIssue'"
          type="primary"
          plain
          icon="el-icon-thumb"
          size="mini"
          :loading="exportLoading"
          @click="handleIssue"
          >出库</el-button
        >
      </el-col>
      <right-toolbar
        v-if="$route.name === 'OtherIssue'"
        :columns="columnsList"
        :show-search.sync="showSearch"
        @saveSetting="getColumnsList"
        @queryTable="getList"
      />
    </el-row>
    <!-- 列表 -->
    <AutoResizer :given-height="250">
      <template #default="{ height }">
        <el-table
          v-if="columnsList.length > 0"
          v-loading="loading"
          :data="list"
          show-summary
          :summary-method="getSummaries"
          :height="height"
          border
        >
          <el-table-column
            v-if="columnsList[0].visible"
            :key="Math.random()"
            label="物料编码"
            align="center"
            prop="materialNo"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[1].visible"
            :key="Math.random()"
            label="物料条码"
            align="center"
            prop="materialLots"
            width="180"
          />
          <el-table-column
            v-if="columnsList[2].visible"
            :key="Math.random()"
            label="物料名称"
            align="center"
            prop="materialName"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[3].visible"
            :key="Math.random()"
            label="领用部门"
            align="center"
            prop="departmentName"
            width="120"
          />
          <el-table-column
            v-if="columnsList[4].visible"
            :key="Math.random()"
            label="领用人"
            align="center"
            prop="recipient"
            width="100"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[5].visible"
            :key="Math.random()"
            label="出库类型"
            align="center"
            prop="outType"
            width="120"
          >
            <template slot-scope="scope">
              <dict-tag
                :type="DICT_TYPE.WMS_OTHER_ISSUE_TYPE_ERP"
                :value="scope.row.outType"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[6].visible"
            :key="Math.random()"
            label="数量"
            align="center"
            prop="qty"
            sortable
            width="100"
          />
          <el-table-column
            v-if="columnsList[7].visible"
            :key="Math.random()"
            label="备注"
            align="center"
            min-width="120"
            show-overflow-tooltip
            prop="remark"
          />
          <el-table-column
            v-if="columnsList[8].visible"
            :key="Math.random()"
            label="创建时间"
            align="center"
            prop="createTime"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[9].visible"
            :key="Math.random()"
            label="单据编号"
            align="center"
            prop="id"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="otherIssueOperate"
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            width="160"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-printer"
                size="mini"
                @click="handlePrintRepair(scope.row)"
                >标签补打</el-button
              >
              <el-button
                v-hasPermi="['wms:other-out-sock:delete']"
                type="text"
                icon="el-icon-delete"
                size="mini"
                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"
    />
    <!-- 打印标签 -->
    <PrintTemplate ref="packingLabelPrinitTemplate" :print-data="printData" />
    <!-- 出库 -->
    <OtherIssue ref="otherIssue" @complete="getList" />
  </div>
</template>

<script>
import axios from "axios";
import {
  getMaterialTransactionPage,
  deleteMaterialTransaction,
  exportMaterialTransactionExcel,
} from "@/api/wms/output/otherIssue";
import { getLabelPrintData } from "@/api/wms/incoming/register";
import PrintTemplate from "@/views/wms/incoming/register/components/PrintTemplate.vue";
import { getLodop } from "@/plugins/lodopFuncs";
import { handlePrint } from "@/utils/lodop";
import { getFormColumnsList } from "@/api/system/saveColumns/index";
import { mapGetters } from "vuex";
import { isArray } from "min-dash";
import OtherIssue from "@/views/wms/output/otherIssue/components/OtherIssue.vue";

export default {
  name: "OtherIssueDocument",
  components: {
    PrintTemplate,
    OtherIssue,
  },
  inject: ["paramsQuery"],
  data() {
    return {
      printData: [],
      printStyle: `
        <style>
          table {
            width:100%;
            margin: 0 auto;
            border: 1px solid #000000;
            border-collapse: collapse;
            page-break-after:always;
            font-size: 12px;
            table-layout: fixed;
          }

          th, td {
            border: 1px solid #000000;
          }
          td {
            width:100%;
            word-break:keep-all;/* 不换行 */
            white-space:nowrap;/* 不换行 */
            overflow:hidden;/* 内容超出宽度时隐藏超出部分的内容 */
            text-overflow:ellipsis;
          }
        </style>
      `,
      // 生产日期
      produceDate: "",
      // 遮罩层
      loading: true,
      sureLoading: false,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // WMS 入库业务-来料登记主列表
      list: [],
      //  是否显示其他出库操作
      otherIssueOperate: true,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        type: null,
        materialNo: null,
        wmsLabelMasterId: null,
        qty: null,
        createTime: [],
      },
      // 高级
      advParams: {},
      // 显示隐藏列参数
      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 },
      ],
      // 显示隐藏持久化参数
      columnsList: [],
    };
  },
  // 获取当前登录用户id
  computed: {
    ...mapGetters(["userId"]),
  },
  created() {
    // 获取显隐列列表
    this.getColumnsList();
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      const params = {
        ...this.queryParams,
        ...this.paramsQuery,
        ...this.advParams,
      };
      getMaterialTransactionPage(params)
        .then((response) => {
          this.list = response.data.list;
          this.total = response.data.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.toggle = !this.toggle;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        areaTest: undefined,
        materialLots: undefined,
        purchaseOrderNo: undefined,
        materialNo: undefined,
        receiptQty: undefined,
        testStatus: undefined,
        produceDate: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    reLoading(timeout) {
      const loading = this.$loading({
        lock: true,
        text: "标签打印中，请勿重复操作",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      setTimeout(() => {
        loading.close();
      }, timeout * 1000);
    },
    repeatSendPrint(bodyData) {
      axios({
        method: "post",
        // url: 'https://content-yeti-immortal.ngrok-free.app/bartenderPrint',
        // url: 'http://qgz855xj.dongtaiyuming.net/bartenderPrint',
        // url: 'http://218.2.10.30:9001/bartenderPrint',
        // 麦禾田内网
        url: "http://192.168.2.253:9001/bartenderPrint",
        data: bodyData,
      }).then((e) => {
        if (e.data.code !== 200) {
          this.$message.error(e.data.msg);
        }
      });
    },
    // 标签补打
    async handlePrintRepair({ materialLots }) {
      // 麦禾田需要更改为bartender打印，固定打印机仓库
      const { data } = await getLabelPrintData({ qrCode: materialLots });
      if (data[0].qty === "0" || data[0].qty === "0.000000") {
        this.$modal.msgWarning("打印数量不能为0");
        return;
      }
      const reportDataList = data ?? [];
      const totalSize = reportDataList.length;
      // loading
      this.reLoading(reportDataList.length);
      if (totalSize === 0) return;

      this.repeatSendPrint({
        filePath:
          "http://192.168.2.253:9000/253bucket/2024-06-25-16-38-07-1719304687722_列管资产标签.btw",
        fileName: "列管资产标签",
        printer: "Fabulous F-BP43i (cangku)",
        dataSource: reportDataList[0],
      });

      // 原lodop打印
      return;
      try {
        const { materialLots } = row;
        const printParams = {
          qrCode: materialLots,
        };
        const printDetailData = await getLabelPrintData(printParams);
        const { data: productsDetails } = printDetailData;
        if (
          productsDetails[0].qty === "0" ||
          productsDetails[0].qty === "0.000000"
        ) {
          this.$modal.msgWarning("打印数量不能为0");
          return;
        }
        this.printData.push(...productsDetails);

        this.$nextTick(() => {
          let timer = setTimeout(() => {
            const el = this.$refs.packingLabelPrinitTemplate.$el;
            const elItems = el.querySelectorAll(".print-item");
            const LODOP = getLodop();
            if (LODOP === undefined) {
              this.$alert(
                "请先安装C-LODOP插件,下载地址为" +
                  "http://www.c-lodop.com/download.html"
              );
              return;
            }
            LODOP.SET_PRINT_PAGESIZE(1, "60mm", "50mm");
            // LODOP.SET_PRINT_MODE('PRINT_PAGE_PERCENT', 'Full-Page')
            elItems.forEach((item) => {
              LODOP.NewPage();
              // LODOP.ADD_PRINT_HTM('0', '0', '100%', '100%', item.innerHTML + this.printStyle)
              LODOP.ADD_PRINT_HTM(
                "5mm",
                "4mm",
                "54mm",
                "45mm",
                item.innerHTML + this.printStyle
              );
            });
            handlePrint(LODOP);
            this.printData = [];
            clearTimeout(timer);
            timer = null;
          }, 600);
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 删除其他出库
    handleDelete(row) {
      const { id, materialNo } = row;
      this.$modal
        .confirm('是否确认删除物料编码为"' + materialNo + '"的数据项?')
        .then(function () {
          return deleteMaterialTransaction(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;
          }
        })
        .finally(() => {
          this.$emit("columns", this.columnsList);
        });
    },
    // 小数点问题处理
    getHandleNumber(val) {
      return Math.round(parseFloat(val) * 100000000) / 100000000;
    },
    // 总计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }

        const values = data.map((item) => Number(item[column.property]));
        if (column.property === "qty") {
          sums[index] = values.reduce((acc, cur) => {
            const value = Number(cur);
            if (!isNaN(value)) {
              return this.getHandleNumber(acc + cur);
            } else {
              return acc;
            }
          }, 0);
          sums[index];
        }
      });
      return sums;
    },
    // 出库发料
    handleIssue() {
      this.$refs.otherIssue.open = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      const params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal
        .confirm("是否确认导出所有其他出库数据项?")
        .then(() => {
          this.exportLoading = true;
          return exportMaterialTransactionExcel(params);
        })
        .then((response) => {
          this.$download.excel(
            response,
            `其他出库-${new Date().toLocaleString()}.xls`
          );
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
