<template>
  <div>
    <basic-container v-show="!detailsOpen">
      <avue-crud :option="option" :search.sync="search" v-model="form" :table-loading="loading" :data="dataList"
        ref="crud" :key="key" @on-load="onLoad" @search-change="searchChange" @row-del="rowDel"
        @refresh-change="refreshChange" @resetColumn="resetColumnTwo('crud', 'option', 'optionList', 268)"
        @saveColumn="saveColumnTwo('crud', 'option', 'optionList', 268)" :page.sync="page">
        <template slot-scope="{type,size,row,$index}" slot="menuLeft">
          <el-button type="warning" icon="el-icon-download" size="small" @click="outExport">导出</el-button>
        </template>
        <template slot-scope="{ row, index }" slot="closingAmount">
          <span style="color: #409EFF;cursor: pointer" @click.stop="editOpen(row)">{{ row.closingAmount }}
          </span>
        </template>
      </avue-crud>
    </basic-container>
    <detailsPage v-if="detailsOpen" @goBack="goBack" :onLoad="form" :detailData="detailData" @backToList="backToList">
    </detailsPage>
  </div>
</template>

<script>
import { getList, remove } from "@/api/accountsReceivableStatistics";
import detailsPage from "./detailsPage"
import {getToken} from "@/util/auth";

export default {
  name: "index",
  components: {
    detailsPage
  },
  data() {
    return {
      detailsOpen: false,
      loading: false,
      search: {},
      form: {},
      dataList: [],
      detailData: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]
      },
      key: 0,
      option: {},
      optionList: {
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        index: true,
        span: 8,
        border: true,
        menu: false,
        height: "auto",
        searchMenuPosition: "right",
        align: "center",
        size: "small",
        menuWidth: 140,
        searchSpan: 8,
        searchIcon: true,
        searchIndex: 2,
        highlightCurrentRow: true,
        dialogWidth: "70%",
        summaryText: "合计",
        showSummary: true,
        sumColumnList: [
          {
            name: 'opening',
            type: 'sum',
          },
          {
            name: 'addAmount',
            type: 'sum',
          },
          {
            name: 'chargeAmount',
            type: 'sum',
          },
          {
            name: 'unpaidAmount',
            type: 'sum',
          },
        ],
        column: [{
          label: '客户名称',
          prop: "customerName",
          type: "select",
          search: true,
          overHidden: true,
          props: {
            label: 'cname',
            value: 'id'
          },
          dicUrl: '/api/blade-sales-part/corpsDesc/listAll?cname={{key}}&corpType=KH&enableOrNot=0',

        }, {
          label: '区域',
          prop: "region",
          overHidden: true,
        }, {
          label: '业务员',
          prop: "salerName",
          search: true,
          type: 'select',
          overHidden: true,
          props: {
            label: "name",
            value: "id"
          },
          dicUrl: "/api/blade-user/client/getUserByRole",
          filterable: true,
        }, {
          label: '公司',
          prop: "salesCompanyId",
          hide: true,
          showColumn: false,
          type: 'select',
          search: true,
          overHidden: true,
          props: {
            label: 'fullName',
            value: 'id'
          },
          dicUrl: '/api/blade-system/dept/top-list',
        }, {
          label: '期初应收',
          prop: "opening",
          overHidden: true,
        }, {
          label: '新增',
          prop: 'addAmount',
          overHidden: true,
        }, {
          label: '实收',
          prop: 'chargeAmount',
          overHidden: true,
        }, {
          label: '未收',
          prop: 'unpaidAmount',
          overHidden: true,
        }, {
          label: '业务日期',
          prop: "createTime",
          searchProp: "createTimeList",
          type: "date",
          overHidden: true,
          search: true,
          hide: true,
          showColumn: false,
          search: true,
          width: 100,
          searchRange: true,
          searchDefaultTime: ["00:00:00", "23:59:59"],
          format: "yyyy-MM-dd HH:mm:ss",
          valueFormat: "yyyy-MM-dd HH:mm:ss"
        }, {
          label: '期末',
          prop: "closingAmount",
          overHidden: true,
        }]
      }
    }
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(268), this.optionList);
    this.key++
    let i = 0;
    this.option.column.forEach(item => {
      if (item.search) i++
    })
    if (i % 3 !== 0) {
      const num = 3 - Number(i % 3)
      this.option.searchMenuSpan = num * 8;
      this.option.searchMenuPosition = "right";
    }
    this.refreshChange()
  },
  methods: {
      // 导出
      outExport() {
          console.log(this.search,412)
          let config = { params: { ...this.search } }
          if (config.params) {
              for (const propName of Object.keys(config.params)) {
                  const value = config.params[propName];
                  if (value !== null && typeof (value) !== "undefined") {
                      if (value instanceof Array) {
                          for (const key of Object.keys(value)) {
                              let params = propName + '[' + key + ']';
                              config.params[params] = value[key]
                          }
                          delete config.params[propName]
                      }
                  }
              }
          }
          const routeData = this.$router.resolve({
              path: '/api/blade-sales-part/order/collectionExport',      //跳转目标下载地址
              query: {
                  ...config.params    //括号内是要传递给新窗口的参数
              }
          })
          window.open(routeData.href.slice(1, routeData.href.length) + '&' + `${this.website.tokenHeader}=${getToken()}`);
      },
    check(row) {
      this.form = row
      this.detailsOpen = true
    },
    backToList(type) {
      this.form = {}
      this.detailsOpen = false
      if (type === 0) {
        this.detailData = {}
      }
      this.onLoad(this.page, this.search)
    },
    //刷新
    refreshChange() {
      this.onLoad(this.page, this.search)
    },
    rowDel(form, index) {
      this.$confirm('此操作将永久删除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove(form.id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.dataList.splice(index, 1);
          this.onLoad(this.page)
        })
      }).catch(() => {
      });
    },
    searchChange(params, done) {
      done();
      this.onLoad(this.page, params)
    },
    onLoad(page, params = {}) {
      this.search.customerId = this.search.customerName
      params = {
        ...params,
        current: page.currentPage,
        size: page.pageSize,
        ...Object.assign(params, this.search)
      }
      this.loading = true
      getList(params).then(res => {
        this.dataList = res.data.data.records
        this.page.total = res.data.data.total
        this.loading = false
      }).finally(() => {
        this.loading = false
      })
    },
    editOpen(row, status) {
      console.log('1111');
      this.form = row
      console.log(this.form);
      this.detailData = {
        id: row.customerId,
        status: status
      };
      this.detailsOpen = true;
    },
    //自定义列保存
    async saveColumnTwo(ref, option, optionBack, code) {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    //自定义列重置
    async resetColumnTwo(ref, option, optionBack, code) {
      this[option] = this[optionBack];
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    }
  }
}
</script>

<style scoped></style>
