<template>
  <Container>
    <div
      v-if="$accessCheck($Access.inventoryStatisticsSearchInventoryStatistics)"
      slot="right"
      class="box-search-form"
    >
      <el-form inline size="small">
        <el-form-item>
          <el-input
            v-model="keywords"
            placeholder="商品名称/商品编码"
            clearable
            @keyup.enter.native="pageChange(1)"
            @clear="pageChange(1)"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="pageChange(1)"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="warehouseId"
            filterable
            placeholder="请选择仓库"
            @change="pageChange(1)"
          >
            <el-option
              v-for="item in warehouse_list"
              :key="item.id"
              :label="item.warehouseName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="timeValue"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
            :clearable="false"
            @change="jurisdiction"
          ></el-date-picker>
        </el-form-item>
      </el-form>
    </div>
    <div slot="left" class="all-handel-btn">
      <el-button
        type="primary"
        class="float_left"
        size="small"
        @click="openUrl"
      >
        打印
      </el-button>
      <el-button type="primary" size="small" @click="inventoryStatistics(1)">
        导出
      </el-button>
      <el-popover
        popper-class="custom-table-checkbox"
        trigger="click"
        style="float: left; margin-left: 10px"
      >
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="(item, index) in columns"
            :key="index"
            :label="item.label"
            @change="change"
          ></el-checkbox>
        </el-checkbox-group>
        <el-button
          slot="reference"
          icon="el-icon-setting"
          size="small"
        ></el-button>
      </el-popover>
    </div>
    <div class="tip">{{ myDate }}库存日报</div>
    <vxe-table
      show-footer
      :data="tableData"
      border="inner"
      :footer-method="objectSpanMethod"
    >
      <vxe-table-column
        field="materielName"
        title="商品名称"
      ></vxe-table-column>
      <vxe-table-column field="unitName" title="商品规格">
        <template #default="{ row }">
          <span>{{ row.unitName }}</span>
          <span v-if="row.skuName">_{{ row.skuName }}</span>
        </template>
      </vxe-table-column>
      <vxe-table-column field="topEndNum" title="昨日结存总数量">
        <template #default="{ row }">
          {{ $_common.formatNub(row.topEndNum) }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="selfInNum" title="今日入库总数量">
        <template #default="{ row }">
          {{ $_common.formatNub(row.selfInNum) }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="selfOutNum" title="今日出库总数量">
        <template #default="{ row }">
          {{ $_common.formatNub(row.selfOutNum) }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="selfPurchaseInNum" title="采购入库">
        <template #default="{ row }">
          {{ $_common.formatNub(row.selfPurchaseInNum) }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="selfPurchaseReturnOutNum" title="采购退货出库">
        <template #default="{ row }">
          {{ $_common.formatNub(row.selfPurchaseReturnOutNum) }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="selfSaleOutNum" title="销售出库">
        <template #default="{ row }">
          {{ $_common.formatNub(row.selfSaleOutNum) }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="selfSaleReturnInNum" title="销售退货入库">
        <template #default="{ row }">
          {{ $_common.formatNub(row.selfSaleReturnInNum) }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="selfAllocateInNum" title="调拨入库">
        <template #default="{ row }">
          {{ $_common.formatNub(row.selfAllocateInNum) }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="selfAllocateOutNum" title="调拨出库">
        <template #default="{ row }">
          {{ $_common.formatNub(row.selfAllocateOutNum) }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="selfEndNum" title="今日结存总数量">
        <template #default="{ row }">
          {{ $_common.formatNub(row.selfEndNum) }}
        </template>
      </vxe-table-column>
    </vxe-table>
    <FooterPage
      :page-size="pageSize"
      :total-page.sync="total"
      :current-page.sync="page"
      @pageChange="pageChange"
      @sizeChange="sizeChange"
    ></FooterPage>
  </Container>
</template>

<script>
  import {
    getAllWarehouse,
    inventoryStatistics,
    exportsInventoryStatistics,
  } from "@/api/Stock";
  import { exportsalesManRank } from "@/api/Commission";
  export default {
    name: "Index",
    data() {
      return {
        tableData: [],
        total: 0,
        page: 1,
        pageSize: 10,
        warehouse_list: [],
        warehouseId: "",
        keywords: "",
        spanArr: [],
        endTime: "",
        startTime: "",
        checkList: [
          "商品规格",
          "昨日结存总数量",
          "今日结存总数量",
          "今日入库总数量",
          "今日出库总数量",
          "采购入库",
          "采购退货出库",
          "销售出库",
          "销售退货入库",
          "调拨入库",
          "调拨出库",
        ],
        columns: [
          {
            label: "商品规格",
          },
          {
            label: "昨日结存总数量",
          },
          {
            label: "今日结存总数量",
          },
          {
            label: "今日入库总数量",
          },
          {
            label: "今日出库总数量",
          },
          {
            label: "采购入库",
          },
          {
            label: "采购退货出库",
          },
          {
            label: "销售出库",
          },
          {
            label: "销售退货入库",
          },
          {
            label: "调拨入库",
          },
          {
            label: "调拨出库",
          },
        ],
        unitNameFlag: true,
        topEndNumFlag: true,
        selfEndNumFlag: true,
        selfInNumFlag: true,
        selfOutNumFlag: true,
        selfPurchaseInNumFlag: true,
        selfPurchaseReturnOutNumFlag: true,
        selfSaleOutNumFlag: true,
        selfSaleReturnInNumFlag: true,
        selfAllocateInNumFlag: true,
        selfAllocateOutNumFlag: true,
        timeValue: "",
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
        },
        timeData: new Date(),
      };
    },
    computed: {
      myDate() {
        if (this.timeValue) {
          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.timeData = new Date(this.timeValue);
        }
        let date = this.timeData;
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        return year + "年" + month + "月" + day + "日";
      },
    },
    async created() {
      let start = new Date(new Date().toLocaleDateString());
      let end = new Date();
      this.endTime = parseInt(end.getTime() / 1000);
      this.startTime = parseInt(start.getTime() / 1000);
      await this.getAllWarehouse();
      await this.inventoryStatistics();
    },
    activated() {
      if (this.$_isInit()) return;
      this.inventoryStatistics();
    },
    methods: {
      objectSpanMethod({ columns, data }) {
        const properties = ["materielName", "unitName"];
        return this.$_common.getSummariesVxe(columns, data, properties);
      },
      pageChange(val) {
        this.page = val;
        this.inventoryStatistics();
      },
      sizeChange(val) {
        this.pageSize = val;
        this.pageChange(1);
      },
      openUrl(row) {
        let checkList = JSON.stringify(this.checkList);
        let routeData = this.$router.resolve({
          path: `/ReconciliationPrint`,
          query: {
            id: 1,
            warehouseId: this.warehouseId,
            page: this.page,
            pageSize: this.pageSize,
            checkList: checkList,
            startTime: this.startTime,
            endTime: this.endTime,
          },
        });
        window.open(routeData.href, "_blank");
      },
      async inventoryStatistics(exports) {
        let params = {
          page: this.page,
          pageSize: this.pageSize,
          warehouseId: this.warehouseId,
          search: this.keywords,
          start: this.startTime,
          end: this.endTime,
        };
        if (exports) {
          params.export = 1;
          params.reconciliation = 1;
          const target = await exportsInventoryStatistics({
            ...params,
          });
        } else {
          const { data, pageTotal } = await inventoryStatistics(params);
          this.tableData = [];
          data.forEach((item) => {
            item.Details.forEach((itemD) => {
              this.tableData.push({
                materielCode: item.materielCode,
                materielId: item.materielId,
                materielName: item.materielName,
                warehouseId: item.warehouseId,
                ...itemD,
              });
            });
          });
          this.total = pageTotal;
          const getSpanArr = this.$_common.getSpanArr(
            this.tableData,
            "materielId"
          );
          this.spanArr = getSpanArr.spanArr;
        }
        // console.log(this.warehouseId);
      },
      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 (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            // sums[index] += "";
            sums[index] = this.$_common.formatNub(sums[index], 2) + "";
          } else {
            sums[index] = "--";
          }
        });

        return sums;
      },
      //  选择仓库
      async getAllWarehouse() {
        const { data } = await getAllWarehouse({
          page: 1,
          pageSize: 999,
        });

        this.warehouse_list = data;
        this.warehouseId = data[0].id;
      },
      change() {
        this.unitNameFlag = this.checkList.some((item) => item === "商品规格");
        this.topEndNumFlag = this.checkList.some(
          (item) => item === "昨日结存总数量"
        );
        this.selfEndNumFlag = this.checkList.some(
          (item) => item === "今日结存总数量"
        );
        this.selfInNumFlag = this.checkList.some(
          (item) => item === "今日入库总数量"
        );
        this.selfOutNumFlag = this.checkList.some(
          (item) => item === "今日出库总数量"
        );
        this.selfPurchaseInNumFlag = this.checkList.some(
          (item) => item === "采购入库"
        );
        this.selfPurchaseReturnOutNumFlag = this.checkList.some(
          (item) => item === "采购退货出库"
        );
        this.selfSaleOutNumFlag = this.checkList.some(
          (item) => item === "销售出库"
        );
        this.selfSaleReturnInNumFlag = this.checkList.some(
          (item) => item === "销售退货入库"
        );
        this.selfAllocateInNumFlag = this.checkList.some(
          (item) => item === "调拨入库"
        );
        this.selfAllocateOutNumFlag = this.checkList.some(
          (item) => item === "调拨出库"
        );
      },
      async jurisdiction(val) {
        let start2 = new Date(val);
        let value1 = parseInt(start2.getTime() / 1000);
        if (val) {
          this.startTime = value1;
          this.endTime = value1 + 86399;
        } else {
          this.startTime = "";
          this.endTime = "";
        }
        this.pageChange(1);
      },
    },
  };
</script>

<style scoped lang="scss">
  .tip {
    font-weight: bold;
    text-align: center;
    line-height: 50px;
  }
  .custom-table-checkbox {
    .el-checkbox {
      display: block !important;
      margin: 0 0 $base-padding/4 0;
    }
  }
</style>
