<!-- 历史头寸 -->
<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"
      :is-need-customcolumn="true"
      :current-page="searchParams.pageStart"
      :page-size="searchParams.pageLimit"
      :total="total"
      @sizeChange="handleSizeChange"
      @currentChange="handleCurrentChange"
      @handleSelectionChange="handleSelectionChange"
    />
  </div>
</template>

<script>
import FormSearch from '@/components/formSearch/index.vue';
import PublicTable from '@/components/table/index.vue';
import { setCurrency } from '@/utils/index.js';
const searchArr = [
  {
    type: 'selectTreeTable',
    prop: 'folder',
    span: 4,
    attrs: {
      label: '账户',
      placeholder: '请选择',
      info: { title: '账户检索' },
      clearable: false,
    },
    options: [],
  },
  {
    type: 'pickerDateSingle',
    prop: 'revalueDate',
    span: 4,
    attrs: {
      label: '日期',
    },
  },
  {
    type: 'select',
    prop: 'purpose',
    span: 4,
    attrs: {
      label: '数据用途',
    },
    options: [
      { label: '时点快照', value: 'SNAPSHOT-POS' },
      { label: '日结估值', value: 'END-DAY-POS' },
      { label: '切日', value: 'SYS-DATE-POS' },
    ],
  },
  {
    type: 'select',
    prop: 'timePoint',
    span: 4,
    attrs: {
      label: '价格时点',
      disabled: true,
    },
    options: [],
  }];
export default {
  components: {
    FormSearch,
    PublicTable,
  },
  props: {
    query: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      formArr: searchArr,
      loading: false,
      // table数据源
      tableData: [],
      tableInfo: {
        defaultExpandAll: false,
        // ['FxSwapPairTermPosition', 'FxSwapPairPosition'].indexOf(this.queryParam.scriptId) === -1,
        // tableHeight: document.documentElement.clientHeight - 336,
      },
      // 表格项绑定的属性
      columns: [],
      // 操作栏自定义按钮
      operations: [

      ],
      tableTopButton: [

      ],
      // 搜索查询的参数
      searchParams: {
        pageStart: 1,
        pageLimit: 20,
        purpose: 'END-DAY-POS',
        revalueDate: '',
        folder: '',
      },
      total: 0,
    };
  },
  computed: {
    queryParam() {
      return Object.keys(this.query).length > 0 ? this.query : this.$route.query;
    },
  },
  watch: {
    'searchParams.purpose': {
      handler(newVal) {
        console.log(this.formArr.filter(v => v.prop === 'timePoint'), newVal, 'lll');
        // this.formArr.filter(v => v.prop === 'timePoint').attrs.disabled = newVal !== 'SNAPSHOT-POS';
        this.formArr[3].attrs.disabled = newVal !== 'SNAPSHOT-POS';// 时点快照 可选择价格时点
        if (newVal !== 'SNAPSHOT-POS') {
          this.searchParams.timePoint = '';
        }
      },
      deep: true,
    },
    // '$route.query': {
    //   handler(newVal) {
    //   // 重新获取数据
    //     this.init();
    //   },
    //   deep: true,
    // },
  },
  async mounted() {
    console.log(this.queryParam, 'this.queryParam');
    await this.getOptions();
    this.init();
  },
  methods: {
    async init() {
      this.setSearchFormArr();
      this.searchParams = Object.assign({}, { ...this.searchParams, ...JSON.parse(this.queryParam.searchParams) });
      await this.getRevalueDate();
      await this.getTableConfig();
      this.getTableList();
    },
    setSearchFormArr() { // 设置查询条件
      if (this.queryParam.formArr && JSON.parse(this.queryParam.formArr).length > 0) {
        this.formArr = [...searchArr, ...JSON.parse(this.queryParam.formArr)];
      } else {
        this.formArr = [...searchArr];
      }
      console.log(this.formArr, 'ffff');
    },
    searchSubmit(val) {
      console.log('search结果', val);
      this.searchParams = { ...this.searchParams, ...val };
      this.getTableList();
    },
    resetForm() {
      this.searchParams = {
        pageStart: 1,
        pageLimit: 20,
        ...JSON.parse(this.queryParam.searchParams),
      };
    },
    outOperation(val, index, prop, num) {
      console.log(val, index, prop, num, '查询');
      this.searchParams[prop] = val;
      if (prop === 'purpose') {
        this.getTimePoint();
      }
    },
    // 页面展示条数改变事件-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;
    },
    async getOptions() { // 账户
      await this.$apis.getPosOptions({ 'codifierGrpCodes': 'folderTreeAuthWithGrp' }).then(res => {
        this.formArr[0].options = res.data.result.folderTreeAuthWithGrp;
      });
    },
    getTimePoint() {
      this.$apis.getPosOptions({ 'codifierGrpCodes': 'timePoint', 'queryParam': { 'siteCode': 'BANKZB', 'appId': 'RCS', 'posType': 'FxSpotPairPosition', 'purpose': this.searchParams.purpose, 'revalueDate': this.searchParams.revalueDate.replaceAll('-', '') }}).then(res => {
        this.formArr[3].options = res.data.result.timePoint;
      });
    },
    async  getTableConfig() {
      await this.$apis.getOneQueryComponent({ 'queryParam.__scriptId': this.queryParam.scriptId }).then(res => {
        const fieldList = res.data.result?.fieldList ? res.data.result?.fieldList : JSON.parse(res.data.result?.field);
        this.columns = fieldList?.filter(v => v.display).map(v => {
          return {
            // ...v,
            name: v.code,
            prop: v.code,
            headerAlign: 'center',
            align: v?.attributeMap?.align,
            label: v.localName,
            width: 'auto',
            minWidth: (v.width?.includes('%') ? document.querySelector('.table-box').offsetWidth * v.width : v.width) || '150px',
            fixed: v.frozen === 'Y',
            render: (h, params) => {
              if (v.name === 'Operation') {
                return h('Icon', {
                  attrs: {
                    class: 'el-icon-document',
                  },
                  style: {
                    cursor: 'pointer',
                    color: '#017BFF',
                    fontSize: '16px',
                  },
                  on: {
                    click: () => {
                      Eui.service.router.push({
                        path: '/7026/pos/forexSpotSingleCurrencyPosition/detail',
                        query: {
                          extraParams: JSON.stringify(params.row),
                          scriptId: this.queryParam.detailScriptId,
                          posType: this.queryParam.posType,
                          searchParams: JSON.stringify(this.searchParams),
                          formArr: JSON.stringify(searchArr.slice(1)),
                        },
                      });
                    },
                  },
                });
              } else {
                return h('span', {
                  domProps: {
                    innerHTML: params.row[v.code],
                  },
                });
              }
            },
          };
        });
      });
    },
    async getRevalueDate() {
      await this.$apis.getPosSystemDate({ 'errorShow': false }).then(res => {
        const date = new Date(res.data.result.timeMillis);
        date.setTime(date.getTime() - 86400000); // 往前一天
        const formattedDate = date.toISOString().split('T')[0];
        this.searchParams.revalueDate = formattedDate;
      });
    },
    getTableList() {
      const param = [
        { field: 'posType', value: this.queryParam.posType },
        { field: 'flagHistory', value: 'Y' },
      ];
      if (['FxSpotPairPosition', 'FxSpotCurrencyPosition', 'FxSwapPairPosition'].indexOf(this.queryParam.scriptId) > -1) {
        param.push({ field: 'dataSet', value: 'RealTime' });
      }
      Object.keys(this.searchParams).filter(v => ['pageStart', 'pageLimit'].indexOf(v) === -1).forEach(key => {
        if (this.searchParams[key]) {
          param.push({ filed: key, value: this.searchParams[key] });
        }
      });
      const params = {
        ...this.searchParams,
        revalueDate: this.searchParams.revalueDate.replaceAll('-', ''),
        '__action': 'Query',
        '__scriptId': this.queryParam.scriptId,
        '__sqlId': 'defaultSqlId',
        param: JSON.stringify(param),
      };
      const transformedParams = {};
      for (const key in params) {
        transformedParams[`queryParam.${key}`] = params[key];
      }
      this.loading = true;
      this.tableData = [];
      this.$apis.getForeignCurrencyList(transformedParams).then(res => {
        this.tableData = res.data.result.datals;
        setCurrency(res.data.result.datals, this.columns);
        this.total = res.data.result.total;
        this.loading = false;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
