<template>
  <div class="RCSbox common-page">
    <FormSearch
      :form-arr="formArr"
      :form-data="searchParams"
      @outOperation="outOperation"
      @searchSubmit="searchSubmit"
      @reset="resetForm"
    />
    <PublicTable
      ref="table"
      class="table"
      row-key="id"
      :loading="loading"
      :has-index="false"
      :need-select="false"
      :table-data="tableData"
      :table-info="tableInfo"
      :table-column="columns"
      :events="events"
      operation-width="150px"
      :has-operation="false"
      :btn-button="operations"
      :table-top-button="tableTopButton"
      :operation-fixed="true"
      :is-need-pagination="false"
      :drop-custom-buttons="dropCustomButtons"
      :current-page="searchParams.pageStart"
      :page-size="searchParams.pageLimit"
      :total="total"
      @sizeChange="handleSizeChange"
      @currentChange="handleCurrentChange"
      @handleSelectionChange="handleSelectionChange"
    >
      <template #dropDefine>
        <span @click="columnSet">期限列设置</span>
      </template>
    </PublicTable>

    <el-dialog
      title="期限列设置"
      :visible.sync="columnSetVisible"
      width="640px"
    >
      <div class="column-dialog">
        <PublicTable
          class="table"
          row-key="termCode"
          :loading="termTable.loading"
          :has-index="false"
          :need-select="true"
          :table-info="termTable.tableInfo"
          :table-data="termTable.data"
          :table-column="termTable.columns"
          :has-operation="false"
          :is-need-pagination="false"
          @handleSelectionChange="handleTermSelectionChange"
        />
        <span
          slot="footer"
          class="dialog-footer"
          style="text-align:right"
        >
          <el-button
            type="primary"
            :size="$buttonSize"
            @click="handleSave"
          >保 存</el-button>
          <el-button
            type="primary"
            :size="$buttonSize"
            @click="handleDefault"
          >默 认</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import FormSearch from '@/components/formSearch/index.vue';
import PublicTable from '@/components/table/index.vue';
export default {
  components: {
    FormSearch,
    PublicTable,
  },
  data() {
    return {
      columnSetVisible: false,
      formArr: [
        {
          type: 'selectTreeTable',
          prop: 'folderId',
          span: 4,
          attrs: {
            label: '账户',
            placeholder: '请选择',
            info: { title: '账户检索' },
            clearable: false,
          },
          options: [],
        },
        {
          type: 'select',
          prop: 'product',
          span: 4,
          attrs: {
            label: '产品',
            multiple: true,
          },
          // clearable: true,
          options: [],
        },
      ],
      loading: false,
      // table数据源
      tableData: [],
      tableInfo: {
        tableHeight: 350,
        defaultExpandAll: true,
        tableTitle: this.$t('menu.forexCashFlowQuery'),
      },
      // 表格项绑定的属性
      columns: [],
      // 操作栏自定义按钮
      operations: [],
      tableTopButton: [],
      dropCustomButtons: [{ slot: 'dropDefine' }],
      // 搜索查询的参数
      searchParams: {
        pageStart: 1,
        pageLimit: 20,
        folderId: '',
        product: null,
        setType: '3',
      },
      total: 0,
      termTable: {
        tableInfo: {
          // tableHeight: 550,
          selection: [],
        },
        loading: false,
        data: [],
        columns: [
          {
            prop: 'termCode',
            minWidth: '80px',
            align: 'center',
            label: this.$t('field.term'),
          },
          {
            prop: 'termRule',
            minWidth: '180px',
            align: 'center',
            label: this.$t('field.termRule'),
          },
        ],
      },
    };
  },
  watch: {
    '$route.query': {
      handler(newVal) {
        this.init();
      },
      deep: true,
    },
  },
  async mounted() {
    await this.getOptions('folderTreeAuthWithGrp,Product');
    this.init();
  },
  methods: {
    async init() {
      this.searchParams.folderId = this.$route.query.folderId;
      this.searchParams.product = this.$route.query.product.split(',');
      await this.getTermCode();
      this.getTableList();
    },
    searchSubmit(val) {
      console.log('search结果', val);
      this.searchParams = { ...this.searchParams, ...val };
      this.getTableList();
    },
    resetForm() {
      this.searchParams = {
        pageStart: 1,
        pageLimit: 20,
        folderId: this.$route.query.folderId,
        product: this.$route.query.product.split(','),
      };
    },
    outOperation(val, index, prop, num) {
      console.log(val, index, prop, num, '查询');
      this.searchParams[prop] = val;
    },
    // 页面展示条数改变事件-pageLimit
    handleSizeChange(pageLimit) {
      this.searchParams.pageLimit = pageLimit;
      this.getTableList();
    },
    // 页面切换事件-pageStart
    handleCurrentChange(pageStart) {
      this.searchParams.pageStart = pageStart;
      this.getTableList();
    },
    // 多选事件
    handleSelectionChange(val) {
      console.log('多选事件 ', val);
      this.selection = val;
    },
    handleTermSelectionChange(val) {
      this.termTable.tableInfo.selection = val;
      console.log(this.termTable.tableInfo.selection, 'selection');
    },
    async getOptions(code) { // 账户
      await this.$apis.getPosOptions({ 'codifierGrpCodes': code }).then(res => {
        this.formArr[0].options = res.data.result.folderTreeAuthWithGrp;
        if (code) {
          this.formArr[1].options = res.data.result[code.split(',')[1].includes('_') ? code.split(',')[1].split('_')[1] : code.split(',')[1]];
        }
      });
    },
    getTableList() {
      this.loading = true;
      const params = {
        ...this.searchParams,
        posType: this.$route.query.posType,
      };
      const transformedParams = {};
      for (const key in params) {
        transformedParams[`queryParam.${key}`] = params[key];
      }
      this.$apis.getTtCashFlowList(transformedParams).then(res => {
        this.tableData = res.data.result.datals;
        console.log(this.tableData, 'this.tableData');
        this.total = res.data.result.total;
        this.columns = [
          {
            prop: 'currency',
            minWidth: '100px',
            align: 'center',
            label: this.$t('field.currency'),
          }, {
            prop: 'total',
            minWidth: '200px',
            align: 'right',
            label: this.$t('field.riskTotal'),
            render: (h, params) => this.setColumnText(h, params, 'total'),
          }, ...res.data.result.termList.map(v => {
            return {
              prop: v,
              label: v,
              minWidth: '180px',
              align: 'right',
              render: (h, params) => this.setColumnText(h, params, v),
            };
          })];
        this.loading = false;
      });
    },
    setColumnText(h, params, v) {
      return h('div', [
        h('span', {
          domProps: {
            innerHTML: params.row[v] || '',
          },
          class: (params.row[v] != null && params.row[v].toString().startsWith('-')) ? 'color-negativeNumber' : '',
        }),
      ]);
    },
    columnSet() {
      this.columnSetVisible = true;
      this.termTable.loading = true;
      this.$apis.queryTerm({ systemCashTermCode: 'R_POS_CASHTERM_CODE' }).then(res => {
        this.termTable.data = res.data.result.allTermList.map((v, i) => {
          if (i < 4) {
            v._disabled = true;
          }
          return v;
        });
        this.termTable.tableInfo.selection = res.data.result.allTermList.filter(term =>
          res.data.result.saveTermList.includes(term.termCode),
        );
        console.log(this.termTable.tableInfo.selection, 'this.termTable.tableInfo.selection');
        this.termTable.loading = false;
      });
    },
    async getTermCode() { // 获取期限列配置
      await this.$apis.findPreferenceDtoByUserId({ 'preferenceType': 'PosAndCashflow' }).then(res => {
        this.searchParams.queryTermList = res.data.result.preferenceData.split(',');
      });
    },
    handleDefault() {
      this.termTable.tableInfo.selection = this.termTable.data.slice(0, 4);
      console.log(this.termTable.tableInfo.selection, 'this.termTable.tableInfo.selection');
    },
    handleSave() {
      this.$apis.updatePreferenceDto({
        'domain.preferenceData': this.termTable.tableInfo.selection.map(v => v.termCode).join(','),
        'domain.preferenceType': 'PosAndCashflow',
      }).then(res => {
        this.$message.success('操作成功');
        this.columnSetVisible = false;
        this.searchParams.queryTermList = res.data.result.preferenceData.split(',');
        this.getTableList();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.column-dialog{
  display:flex;
  flex-direction: column;
  .table-box{
    padding:0 0 16px;
    height:544px
  }
}
</style>
