<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"
        @expand-change="expandChange" @refresh-change="refreshChange"
        @resetColumn="resetColumnTwo('crud', 'option', 'optionList', 405)"
        @saveColumn="saveColumnTwo('crud', 'option', 'optionList', 405)" :page.sync="page">
        <template slot-scope="{type,size,row,index}" slot="menu">
          <el-button :size="size" :disabled="row.status==1" :type="type" @click="$refs.crud.rowDel(row, index)">删除</el-button>
        </template>
        <template slot-scope="{type,size,row,$index}" slot="menuLeft">
          <el-button icon="el-icon-plus" type="primary" :size="size" @click="detailsOpen = true">新建</el-button>
        </template>
        <template slot-scope="{ row, index }" slot="confirmingPersonName">
          <span style="color: #409EFF;cursor: pointer" @click.stop="editOpen(row, 2)">{{ row.confirmingPersonName }}
          </span>
        </template>
        <template slot-scope="{ row, index }" slot="sysNo">
          <span style="color: #409EFF;cursor: pointer" @click.stop="editOpen(row, 2)">{{ row.sysNo }}
          </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/tirePartsMall/financingManagement/balanceRecharge";
import detailsPage from "./detailsPage"
import { getDetails } from "@/api/tirePartsMall/salesService/saleOrder";
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: 6,
        border: true,
        height: "auto",
        searchMenuPosition: "right",
        align: "center",
        size: "small",
        menuWidth: 50,
        searchSpan: 6,
        searchMenuSpan: 24,
        searchIcon: true,
        // expand: true,
        // expandWidth: 60,
        searchIndex: 3,
        highlightCurrentRow: true,
        dialogWidth: "70%",
        summaryText: "合计",
        showSummary: true,
        sumColumnList: [
          {
            name: 'amount',
            type: 'sum',
            decimals: 2,
          }],
        column: [
          {
            label: '确认人',
            prop: "confirmingPersonName",
            search: true,
            overHidden: true,
            type: 'select',
            filterable: true,
            remote: true,
            props: {
              label: 'cname',
              value: 'cname',
              res: 'data.records'
            },
            dicUrl: '/api/blade-sales-part/corpsDesc/list?current=1&size=20&corpType=GYS&cname={{key}}',
          },
          {
            label: '单号',
            prop: "sysNo",
            overHidden: true,
          },
          {
            label: '金额',
            prop: "amount",
            overHidden: true,
          },
          {
            label: '状态',
            prop: "status",
            type: 'select',
            dicData: [{
              label: '已确认',
              value: 1
            }, {
              label: '录入',
              value: 0
            }],
            overHidden: true,
          },
          {
            label: "确认时间",
            prop: "confirmingPersonDate",
            searchProp: "confirmingPersonDateList",
            type: "date",
            search: true,
            overHidden: true,
            searchRange: true,
            unlinkPanels: true,
            searchDefaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss"
          },
          {
            label: "制单人",
            prop: "createUserName",
            searchProp: "createUser",
            search: true,
            overHidden: true,
            filterable: true,
            remote: true,
            type: "select",
            dicUrl: "/api/blade-user/page?size=20&current=1&account={{key}}",
            props: {
              label: "account",
              value: "id",
              res: 'data.records'
            }
          },
          {
            label: "制单日期",
            prop: "createTime",
            searchProp: "createTimeList",
            type: "date",
            search: true,
            overHidden: true,
            searchRange: true,
            unlinkPanels: true,
            searchDefaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd HH:mm:ss"
          },
          {
            label: "更新人",
            prop: "updateUserName",
            searchProp: "updateUser",
            overHidden: true,
            filterable: true,
            remote: true,
            type: "select",
            dicUrl: "/api/blade-user/page?size=20&current=1&account={{key}}",
            props: {
              label: "account",
              value: "id",
              res: 'data.records'
            }
          },
          {
            label: "更新日期",
            prop: "updateTime",
            searchProp: "updateTimeList",
            type: "date",
            overHidden: true,
            searchRange: true,
            searchDefaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd HH:mm:ss"
          }
        ]
      }
    }
  },
  activated() {
    setTimeout(() => {
      if (this.$route.query.srcId) {
        this.$store.commit("IN_BALANCE_DETAIL");
        this.detailsOpen = true;
      }
    }, 100);
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(405), 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";
    // }
  },
  methods: {
    // 导出
    outExport() {
      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/returns/listExport',      //跳转目标下载地址
        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 = {}
      }
      if (this.$route.query.srcId) {
        this.$router.$avueRouter.closeTag(this.$route.fullPath);
        this.$router.push({
          path: "/tirePartsMall/financingManagement/balanceRecharge/index"
        });
      }
      this.onLoad(this.page, this.search)
      this.$store.commit("OUT_BALANCE_DETAIL");

    },
    editOpen(row, status) {
      this.form = row
      this.detailData = {
        id: row.id,
        status: status
      };
      this.$store.commit("IN_BALANCE_DETAIL");
      this.detailsOpen = true;
    },
    //刷新
    refreshChange() {
      this.onLoad(this.page, this.search)
    },
    expandChange(row) {
      if (!row.itemData) {
        getDetails({ id: row.id })
          .then(res => {
            this.dataList[row.$index].itemData = res.data.data.orderItemsList;
          })
          .finally(() => {
            this.dataList[row.$index].itemLoading = false;
          });
      }
    },
    rowDel(form, index) {
      this.$confirm('此操作将永久删除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove({ ids: form.id }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.dataList.splice(index, 1);
          this.onLoad(this.page)
        })
      }).catch(() => {
      });
    },
    searchChange(params, done) {
      this.page.currentPage = 1
      done();
      this.onLoad(this.page, params)
    },
    onLoad(page, params = {}) {
      params = {
        ...params,
        current: page.currentPage,
        size: page.pageSize,
        ...Object.assign(params, this.search)
      }
      this.loading = true
      this.dataList.forEach(item => {
        this.$refs.crud.toggleRowExpansion(item, false);
      });
      getList(params).then(res => {
        if (res.data.data.records) {
          res.data.data.records.forEach(e => {
            e.itemLoading = true;
          });
        }
        this.dataList = res.data.data.records
        this.page.total = res.data.data.total
        this.$nextTick(() => {
          this.$refs.crud.doLayout()
          this.$refs.crud.dicInit()
        })
      }).finally(() => {
        this.loading = false
      })
    },
    //自定义列保存
    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>
.itemTable ::v-deep .el-table {
  margin-left: 50px;
  width: 100%;
}

.bottomBox {
  padding: 3px 6px;
  border-radius: 12px;
  color: #fff;
  font-size: 10px;
}

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