<template>
  <div>
    <basic-container class="page-crad" v-show="show">
      <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" @search-reset="searchReset">
        <template slot="header">
          <el-table :data="commodityData" border size="small" @header-click="cellClick" style="width: 100%"
            v-loading="itemloading">
            <el-table-column v-for="(item, index) in commodityLabel" :key="index" :prop="item.prop" show-overflow-tooltip
              :label="item.label" />
          </el-table>
        </template>
        <template slot="menuLeft">
          <el-button type="info" icon="el-icon-printer" size="small" :loading="exportLoading" @click.stop="statement"
            v-if="false">报表打印</el-button>
          <el-button type="info" size="small" @click="outExport" icon="el-icon-download">导出</el-button>
        </template>
        <template slot="corpNameSearch">
          <crop-select v-model="search.corpId" corpType="KG"></crop-select>
        </template>
        <template slot="sizeSearch">
          <el-select v-model="search.size" placeholder="请选择">
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </template>
        <template slot="customerName" slot-scope="scope">
          <span style="color: #409EFF;cursor: pointer" @click.stop="beforeOpenPage(scope.row, scope.index)">{{
            scope.row.customerName
          }}</span>
        </template>
        <template slot="whetherSettlementSearch">
          <el-checkbox v-model="search.whetherSettlement" :true-label="0" :false-label="1"></el-checkbox>
        </template>
      </avue-crud>
    </basic-container>
    <report-dialog :switchDialog="switchDialog" :searchValue="statementData" :reportName="'经销商-可用库存表'"
      @onClose="onClose()" />
    <detail v-if="!show" :detail-data="detailData" :trade-type="tradeType" @goBack="goBack"></detail>
  </div>
</template>

<script>
import { getToken } from "@/util/auth";
import { getList } from "@/api/statisticAnalysis/collectLedger";
import { getStatisticsList, statisticsSum } from "@/api/tireMall/tirePartsMall/statisticAnalysis/index";
import { micrometerFormat } from "@/util/validate";
import _ from "lodash";
import reportDialog from "@/components/report-dialog/main";
import { gainUser } from "@/api/basicData/customerInquiry";
import detail from "./detail";
import { dateFormat } from "@/util/date";
export default {
  name: "index",
  components: {
    reportDialog,
    detail
  },
  data() {
    return {
      itemloading: false,
      commodityLabel: [
        {
          id: 1,
          label: "金额",
          prop: "totalMoney",
        }, {
          id: 2,
          label: "实收金额",
          prop: "paymentAmountTl",
        }, {
          id: 3,
          label: "运费",
          prop: "freight",
        }, {
          id: 4,
          label: "未收金额",
          prop: "outstandingAmount",
        }
      ],
      commodityData: [], // 合计数据
      exportLoading: false,
      switchDialog: false,
      statementData: {},
      form: {},
      search: {
        whetherSettlement: 0,
        businesDateList:[dateFormat(new Date,'yyyy-MM'),dateFormat(new Date,'yyyy-MM')]
      },
      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: 6,
        searchMenuSpan: 24,
        border: true,
        index: true,
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        showSummary: true,
        summaryText: '合计',
        sumColumnList: [
          {
            name: 'totalMoney',
            type: 'sum'
          },
          {
            name: 'paymentAmountTl',
            type: 'sum'
          },
          {
            name: 'freight',
            type: 'sum'
          },
          {
            name: 'outstandingAmount',
            type: 'sum'
          },
        ],
        // searchIcon: true,
        // searchIndex: 3,
        menu: false,
        column: [
          {
            label: '客户',
            prop: "customerName",
            type: "select",
            search: true,
            overHidden: true,
            filterable: true,
            props: {
              label: 'cname',
              value: 'id'
            },
            dicUrl: '/api/blade-sales-part/corpsDesc/listAll?cname={{key}}&corpType=KH&enableOrNot=1',
          },
          {
            label: '业务员',
            prop: "salerId",
            search: true,
            type: "select",
            props: {
              label: "name",
              value: "id"
            },
            dicUrl: "/api/blade-user/salerList",
            filterable: true,
            hide: true,
          },
          {
            label: '业务员',
            prop: "salerName",
            overHidden: true,
          },
          {
            label: "业务日期",
            prop: "businesDate",
            type: 'date',
            format: "yyyy-MM",
            valueFormat: "yyyy-MM",
            unlinkPanels: true,
            searchRange: true,
            overHidden: true,
          },
          {
            label: "业务日期",
            prop: "businesDateList",
            search: true,
            type: 'monthrange',
            format: "yyyy-MM",
            valueFormat: "yyyy-MM",
            unlinkPanels: true,
            searchRange: true,
            overHidden: true,
            hide: true
          },
          {
            label: "结清不显示",
            prop: "whetherSettlement",
            search: true,
            hide: true
          },
          // {
          //   label: "是否显示金额为0",
          //   prop: "size",
          //   search: true,
          //   overHidden: true,
          //   hide: true,
          //   showColumn: false
          // },
          {
            label: "金额",
            prop: "totalMoney",
            search: false,
            overHidden: true,
          },
          {
            label: "运费",
            prop: "freight",
            search: false,
            overHidden: true,
          },
          {
            label: "实收金额",
            prop: "paymentAmountTl",
            search: false,
            overHidden: true,
          },
          {
            label: "未收金额",
            prop: "outstandingAmount",
            search: false,
            overHidden: true,
          },
        ],
      },
      // 仓库配置
      configurationWarehouse: {
        multipleChoices: false,
        multiple: false,
        collapseTags: false,
        placeholder: "请点击右边按钮选择",
        dicData: [],
      },
      brandOption: [],
      userList: [],
      tradeType: '',
      sysitemType: null,
      show: true,
    };
  },
  async created() {
    this.option = this.defaultOption;
    this.option = await this.getColumnData(this.getColumnName(284), this.defaultOption);

    this.getWorkDicts('brand').then(res => {
      this.brandOption = res.data.data;
    })
    gainUser().then(res => {
      this.userList = res.data.data;
    });
    this.search=this.deepClone(this.search)
  },
  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();
    },
    searchReset() {
    },
    //点击搜索按钮触发
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    refreshChange() {
      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) {
      this.search = this.deepClone(this.search)
      this.search.customerId = this.search.customerName
      this.sysitemType = localStorage.getItem('sysitemType');
      if (this.sysitemType == 999) {
        this.tradeType = ''
      } else if (this.sysitemType == 1) {
        this.tradeType = 'XX'
      } else if (this.sysitemType == 2) {
        this.tradeType = 'GN'
      } else if (this.sysitemType == 3) {
        this.tradeType = 'JK'
      } else if (this.sysitemType == 4) {
        this.tradeType = 'CK'
      } else if (this.sysitemType == 5) {
        this.tradeType = 'SW'
      } else if (this.sysitemType == 6) {
        this.tradeType = 'JXS'
      } else if (this.sysitemType == 7) {
        this.tradeType = 'LY'
      }
      this.loading = true;
      this.dataList.forEach(item => {
        this.$refs.crud.toggleRowExpansion(item, false);
      });
      let queryParams = this.deepClone(Object.assign({ type: 0 }, params, this.search));
      if (queryParams.accDate && queryParams.accDate.length > 0) {
        queryParams = {
          ...queryParams,
          accDateStart: queryParams.accDate[0] + ' 00:00:00',
          accDateEnd: queryParams.accDate[1] + ' 23:59:59',
        }
        delete queryParams.accDate;
      }
      getStatisticsList(
        page.currentPage,
        page.pageSize,
        queryParams
      )
        .then(res => {
          if (res.data.data.records) {
            res.data.data.records.forEach(e => {
              e.itemLoading = true;
            });
          }
          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 - 330;
          }
          this.itemloading = true,
            statisticsSum({ type: 0, ...queryParams }).then(res => {
              this.commodityData = [res.data.data]
            }).finally(() => {
              this.itemloading = false;
            });
        })
        .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.accDate && this.statementData.accDate.length > 0) {
        this.statementData.accDateStart = this.statementData.accDate[0] + " " + "00:00:00"
        this.statementData.accDateEnd = this.statementData.accDate[1] + " " + "23:59:59"
        delete this.statementData.accDate
      }
      this.switchDialog = !this.switchDialog;
    },
    onClose(val) {
      this.switchDialog = val;
    },

    // 跳转到详情
    beforeOpenPage(row, index) {
      this.detailData = {
        customerId: row.customerId,
        businesDate: row.businesDate,
        salerId: row.salerId,
      };
      this.show = false;
    },
    goBack() {
      this.detailData = this.$options.data().detailData
      if (JSON.stringify(this.$route.query) != "{}") {
        this.$router.$avueRouter.closeTag();
        this.$router.push({
          path: "/statisticAnalysis/collectLedger/index"
        });
      }
      this.dataList.forEach(item => {
        this.$refs.crud.toggleRowExpansion(item, false)
      })
      this.show = true;
      this.onLoad(this.page, this.search);
    },
    outExport() {
      if (!this.search.corpId) this.$set(this.search, 'corpId', '');
      if (this.search.accDate && this.search.accDate.length > 0) {
        this.search = {
          ...this.search,
          accDateStart: this.search.accDate[0] + ' 00:00:00',
          accDateEnd: this.search.accDate[1] + ' 23:59:59',
        }
      } else {
        this.search = {
          ...this.search,
          accDateStart: '',
          accDateEnd: '',
        }
      }
      this.$confirm('是否导出应收总账信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(
          `/api/blade-sales-part/order/statistics-export?${this.website.tokenHeader
          }=${getToken()}&type=0&businesDateList[0]=${this.search.businesDateList[0] == null || this.search.businesDateList[0] === undefined ? '' : this.search.businesDateList[0]
          }&businesDateList[1]=${this.search.businesDateList[1] == null || this.search.businesDateList[1] === undefined ? '' : this.search.businesDateList[1]
          }&customerId=${this.search.customerName == null || this.search.customerName === undefined ? '' : this.search.customerName}`
        );
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消' //
        });
      })
    },
    //列保存触发
    async saveColumn() {
      const inSave = this.saveColumnData(this.getColumnName(284), 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;
      //   this.option = await this.getColumnData(this.getColumnName(284), this.defaultOption);
      const inSave = await this.delColumnData(this.getColumnName(284), 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%;
}

/deep/ .el-col-md-8 {
  width: 24.33333%;
}
</style>
