<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="98px"
    >
      <QueryFormWrapper>
        <el-col :span="8">
          <el-form-item label="销售出库单号" prop="saleOutNo">
            <el-input
              v-model="queryParams.saleOutNo"
              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">
            <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="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-printer"
          size="mini"
          :loading="exportLoading"
          @click="handlePrint"
          >单据打印</el-button
        >
      </el-col>
    </el-row>
    <!-- 列表 -->
    <!-- <AutoResizer :given-height="377">
      <template #default="{height}">

      </template>
    </AutoResizer> -->
    <el-table
      ref="multipleTable"
      v-loading="loading"
      :data="list"
      border
      :summary-method="getSummaries"
      show-summary
      @selection-change="tableSelected"
      @select="select"
      @select-all="selectAll"
    >
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column
        label="erp单号"
        align="center"
        prop="erpWriteNo"
        width="140"
        fixed="left"
      />
      <el-table-column
        label="销售出库单号"
        align="center"
        prop="saleOutNo"
        width="190"
        fixed="left"
      />
      <el-table-column
        label="销售单号"
        align="center"
        prop="saleOrderNo"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        label="检验单号"
        align="center"
        prop="testNo"
        width="130"
      />
      <el-table-column
        label="物料编码"
        align="center"
        prop="materialNo"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        label="物料名称"
        align="center"
        prop="materialName"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column label="箱号" align="center" prop="boxNo" width="170" />
      <!-- <el-table-column label="计划数量" align="center" prop="planQty" /> -->
      <el-table-column label="装箱数量" align="center" prop="boxQty" />
      <el-table-column label="出库状态" align="center" prop="outStatus">
        <template slot-scope="scope">
          <dict-tag
            :type="DICT_TYPE.WMS_ISSUE_STATUS"
            :value="scope.row.outStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="检验结果" align="center" prop="testResult">
        <template slot-scope="scope">
          <dict-tag
            :type="DICT_TYPE.WMS_TEST_RESULT"
            :value="scope.row.testResult"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="单位"
        align="center"
        prop="unitCode"
        width="100"
      />
      <el-table-column label="创建人" align="center" prop="creator" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="160"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="160"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <!-- <el-button
            v-hasPermi="['wms:sale-out-order-detail:create']"
            type="text"
            icon="el-icon-thumb"
            size="mini"
            :disabled="(scope.row.outStatus === 0)"
            @click="handleEnsure(scope.row)"
          >确认出库</el-button> -->
          <el-button
            type="text"
            icon="el-icon-printer"
            size="mini"
            @click="handlePrintLabel(scope.row)"
            >标签打印</el-button
          >
          <el-button
            v-hasPermi="['wms:sale-out-order-detail:delete']"
            type="text"
            icon="el-icon-delete"
            size="mini"
            class="text-danger"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 出库明细 -->
    <detail ref="detialList" />
    <!-- 单据打印 -->
    <IssuePrinit ref="issuePrinit" />
    <!-- 标签打印 -->
    <PackingLabelPrinitTemplate
      ref="packingLabelPrinitTemplate"
      :print-data="printData"
    />
  </div>
</template>

<script>
import { updateOutOrder, deleteOrderDetail } from "@/api/wms/output/salesIssue";
import { getSaleOutDetailPage } from "@/api/wms/inquirePurchase/complexDocuments";
import { queryLabelDetail } from "@/api/wms/output/salesIssue";
import detail from "./details.vue";
const AccessTokenKey = "ACCESS_TOKEN";
import IssuePrinit from "./IssuePrinit.vue";
import { mapState } from "vuex";
import PackingLabelPrinitTemplate from "./PackingLabelPrinitTemplate.vue";
import { getLodop } from "@/plugins/lodopFuncs";
import { handlePrint } from "@/utils/lodop";

export default {
  name: "SalesIssueDetails",
  components: {
    detail,
    IssuePrinit,
    PackingLabelPrinitTemplate,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // wms销售出库明细列表
      list: [],
      // 弹出层标题
      title: "",
      ids: "",
      tokens: "",
      baseUrl: "",
      currentRows: [],
      reportId: "",

      // 标签打印
      printData: [],
      printStyle: `
        <style>
        table {
            width:100%;
            margin: 0 auto;
            border: 1px solid #000000;
            border-collapse: collapse;
            table-layout: fixed;
            page-break-after:always;
            color: #000000;
            font-family:Arial,"Microsoft Yahe","微软雅黑";
          }
          th, td {
            border: 1px solid #000000;
            color: #000000;
          }
          td {
            font-size: 10px;
            transfrom:scale(0.75)
          }
        </style>
      `,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        masterId: null,
        saleOutNo: null,
        productName: null,
        boxNo: null,
        boxQty: null,
        unitCode: null,
        stockCode: null,
        areaCode: null,
        locationCode: null,
        createTime: [],
        id: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        masterId: [
          { required: true, message: "主表ID不能为空", trigger: "blur" },
        ],
        saleOutNo: [
          { required: true, message: "销售订单号不能为空", trigger: "blur" },
        ],
        boxNo: [{ required: true, message: "箱号不能为空", trigger: "blur" }],
      },
    };
  },
  computed: {
    ...mapState({
      routeLists: (state) => state.permission.addRoutes,
    }),
  },
  created() {
    this.getList();
    this.tokens = localStorage.getItem(AccessTokenKey);
    this.reportId = this.$route.meta.reportId;
    this.baseUrl = process.env.VUE_APP_REPORT_API;
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      this.queryParams.saleOrderNo = this.$route.query.saleOrderNo;
      getSaleOutDetailPage(this.queryParams)
        .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,
        masterId: undefined,
        saleOutNo: undefined,
        productName: undefined,
        boxNo: undefined,
        boxQty: undefined,
        unitCode: undefined,
        stockCode: undefined,
        areaCode: undefined,
        locationCode: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 确认出库
    handleEnsure(row) {
      const { testResult, outStatus } = row;
      if (
        (testResult === 1 && outStatus === 0) ||
        (testResult === 1 && outStatus === 1) ||
        (testResult === 0 && outStatus === 0)
      ) {
        this.$modal.msgWarning("检验结果/出库状态不满足，不能进行出库操作");
        return;
      }
      updateOutOrder(row).then((res) => {
        this.$modal.msgSuccess("出库成功");
        this.getList();
      });
    },
    handlePrint() {
      if (this.ids === "") {
        this.$modal.msgWarning("请选择你要打印的数据行");
        return;
      }
      const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&id=${this.ids}`;
      this.$refs.issuePrinit.dialogVisible = true;
      this.$refs.issuePrinit.title = "出货单";
      this.$refs.issuePrinit.src = src;
    },
    // 表格选中
    tableSelected(val) {
      this.currentRows = val;
      const list = this.currentRows.map((item) => item.saleOutNo);
      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;
      }
    },
    // 删除
    handleDelete(row) {
      const { id, materialName } = row;
      this.$modal
        .confirm('是否确认删除出库明细名称为"' + materialName + '"的数据项?')
        .then(function () {
          return deleteOrderDetail(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功，请在erp系统同步删除!");
        })
        .catch(() => {});
    },
    // 标签打印
    async handlePrintLabel(row) {
      const { boxNo } = row;
      try {
        this.$modal.msgSuccess("正在打印标签...");
        const boxDetailsResult = await queryLabelDetail(boxNo);
        const { data } = boxDetailsResult;
        this.printData.push(data.data);
        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(
                "5mm",
                "4mm",
                "54mm",
                "45mm",
                item.innerHTML + this.printStyle
              );
            });
            handlePrint(LODOP);
            this.printData = [];
            clearTimeout(timer);
            timer = null;
          }, 600);
        });
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    // 小数点问题处理
    getHandleTotalNumber(val) {
      return Math.round(parseFloat(val) * 10000) / 10000;
    },
    // 总计
    getSummaries(param) {
      const { columns } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }
        const values =
          this.list.map((item) => Number(item[column.property])) || [];
        if (column.property === "boxQty") {
          sums[index] = values.reduce((acc, cur) => {
            const value = Number(cur);
            if (!isNaN(value)) {
              return this.getHandleTotalNumber(acc + cur);
            } else {
              return this.getHandleTotalNumber(acc);
            }
          }, 0);
          sums[index];
        }
      });
      return sums;
    },
  },
};
</script>
