<template>
  <div>
    <basic-container class="page-crad">
      <avue-crud ref="crud" :option="option" :data="dataList" :page.sync="page" :search.sync="search"
        :cell-style="cellStyle" @search-change="searchChange" @current-change="currentChange" @size-change="sizeChange"
        @refresh-change="refreshChange" @on-load="onLoad" :table-loading="loading" @saveColumn="saveColumn"
        @resetColumn="resetColumn" @search-criteria-switch="searchCriteriaSwitch">
        <template slot="menuLeft">
          <!-- <el-button type="info" icon="el-icon-printer" size="small" :loading="exportLoading" @click.stop="statement">
            报表打印
          </el-button> -->
          <el-button type="info" size="small" @click="outExport" icon="el-icon-download">导出</el-button>
        </template>
        <template slot="brandSearch">
          <el-select v-model="search.brand" filterable clearable>
            <el-option v-for="(item, index) in brandOption" :key="index" :label="item.dictValue"
              :value="item.dictValue" />
          </el-select>
        </template>
      </avue-crud>
    </basic-container>
    <report-dialog :switchDialog="switchDialog" :searchValue="statementData" :reportName="'经销商-可用库存表'"
      @onClose="onClose()" />
  </div>
</template>

<script>
import { getToken } from "@/util/auth";
import { getList } from "@/api/statisticAnalysis/purchaseReconciliation";
import { micrometerFormat } from "@/util/validate";
import _ from "lodash";
import reportDialog from "@/components/report-dialog/main";

export default {
  name: "index",
  components: {
    reportDialog
  },
  data() {
    return {
      exportLoading: false,
      switchDialog: false,
      statementData: {},
      form: {},
      search: {},
      dataList: [],
      loading: false,
      detailData: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]
      },
      option: {},
      defaultOption: {
        searchShow: true,
        align: "center",
        searchSpan: 8,
        searchMenuSpan: 8,
        border: true,
        index: true,
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        showSummary: true,
        searchIcon: true,
        searchIndex: 2,
        menu: false,
        column: [
          {
            label: "采购单号",
            prop: "orderNo",
            search: false,
            overHidden: true,
          },
          {
            label: "来源销售单号",
            prop: "orgOrderNo",
            search: false,
            overHidden: true,
          },
          {
            label: "品牌",
            prop: "brand",
            search: true,
            overHidden: true,
          },
          {
            label: "制单日期",
            prop: "careteTime",
            search: true,
            type: 'date',
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            unlinkPanels: true,
            searchRange: true,
            overHidden: true,
          },
          {
            label: "数量",
            prop: "quantity",
            search: false,
            overHidden: true,
          },
          {
            label: "采购金额",
            prop: "orderAmount",
            search: false,
            overHidden: true,
          },
          {
            label: "已付金额",
            prop: "settlmentAmount",
            search: false,
            overHidden: true,
          },
        ],
      },
      // 仓库配置
      configurationWarehouse: {
        multipleChoices: false,
        multiple: false,
        collapseTags: false,
        placeholder: "请点击右边按钮选择",
        dicData: [],
      },
      brandOption: [],
    };
  },
  filters: {
    decimalFormat(num) {
      return num ? Number(num).toFixed(2) : "0.00";
    }
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(128), this.defaultOption);
    this.getWorkDicts('brand').then(res => {
      this.brandOption = res.data.data;
    })
  },
  methods: {
    cellStyle() {
      return "padding:0;height:40px;";
    },
    searchCriteriaSwitch(type) {
      if (type) {
        this.option.height = this.option.height - 46;
      } else {
        this.option.height = this.option.height + 46;
      }
      this.$refs.crud.getTableHeight();
    },
    //点击搜索按钮触发
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    outExport() {
      let params = { ...this.search }
      if (!params.brand) this.$set(params, 'brand', '');
      if (params.careteTime && params.careteTime.length > 0) {
        params = {
          ...params,
          beginCreateTime: params.careteTime[0] + ' 00:00:00',
          endCreateTime: params.careteTime[1] + ' 23:59:59',
        }
      } else {
        params = {
          ...params,
          beginCreateTime: '',
          endCreateTime: '',
        }
      }
      console.log(params)
      this.$confirm('是否导出数据明细？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(
          `/api/blade-purchase-sales/exportOrder/selPurchaseExport?${this.website.tokenHeader
          }=${getToken()}&brand=${params.brand}&beginCreateTime=${params.beginCreateTime}&endCreateTime=${params.endCreateTime}`
        );
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消' //
        });
      })
    },
    refreshChange() {
      delete this.search.corpName;
      delete this.search.storageName
      this.onLoad(this.page, this.search);
    },
    currentChange(val) {
      this.page.currentPage = val;
    },
    sizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
    },
    onLoad(page, params) {
      console.log(this.search, params)
      if (this.search.careteTime && this.search.careteTime.length > 0) {
        params = {
          ...params,
          beginCreateTime: this.search.careteTime[0],
          endCreateTime: this.search.careteTime[1]
        };
      }
      let queryParams = Object.assign({}, params);
      delete queryParams.careteTime;
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        queryParams
      )
        .then(res => {
          this.dataList = res.data.data.records ? res.data.data.records : [];
          this.page.total = res.data.data.total;
          if (this.page.total) {
            this.option.height = window.innerHeight - 210;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    editOpen(row) {
      if (row.billType == "BJ") {
        this.$router.push({
          path: "/exportTrade/customerInquiry/index",
          query: {
            id: row.id
          }
        });
      } else {
        this.$router.push({
          path: "/exportTrade/salesContract/index",
          query: {
            id: row.id
          }
        });
      }
    },
    statement() {
      this.statementData = { ...this.search };
      if (this.statementData.careteTime && this.statementData.careteTime.length > 0) {
        this.statementData.createStartTime = this.statementData.careteTime[0] + " " + "00:00:00"
        this.statementData.createEndTime = this.statementData.careteTime[1] + " " + "23:59:59"
        delete this.statementData.careteTime
      }
      this.switchDialog = !this.switchDialog;
    },
    onClose(val) {
      this.switchDialog = val;
    },
    //列保存触发
    async saveColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(128),
        this.option
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    async resetColumn() {
      this.option = this.defaultOption;
      const inSave = await this.delColumnData(this.getColumnName(128), this.defaultOption);
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout()
        })
        this.$message.success("重置成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
  }
};
</script>

<style scoped>
.page-crad ::v-deep .basic-container__card {
  height: 94.2vh;
}

::v-deep .el-table__expanded-cell[class*="cell"] {
  padding: 0px;
}

.itemTable ::v-deep .el-table {
  width: 100%;
}
</style>
