
import { setCurrency, commonMore } from '@/utils/index';
export default {
  data() {
    return {
      isRealTime: false,
      activeTab: '0',
      timer: null,
      queryParam: {},
      configObj: {
        buttonList: [],
      },
      dropCustomButtons: [
        { slot: 'dropExportPage' },
        { slot: 'dropExportAll' },
      ],
    };
  },
  mounted() {

  },
  beforeDestroy() {
    // 组件销毁之前清除定时器
    this.clearTimer();
  },
  methods: {
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    /**
     * 获取表格列
     * @param {String} scriptId
     */
    async getTableConfig(scriptId, detailScriptId, posType) {
      await this.$apis.getOneQueryComponent({ 'queryParam.__scriptId': scriptId }).then(res => {
        this.configObj = res.data.result;
        // 间隔时间
        this.configObj.interVal = this.configObj?.attributeList ? this.configObj?.attributeList.filter(v => v.code === 'interval')[0]?.value * 1000 : JSON.parse(this.configObj.attribute).filter(v => v.code === 'interval')[0]?.value * 1000;
        //   this.tableTopButton = [...this.tableTopButton,...res.data.result.buttonList.map(v => {
        //     return {
        //       ...v,
        //       text: v.localName,
        //       type: 'default',
        //     };
        //   })];
        const btn = res.data.result?.buttonList ? res.data.result?.buttonList : JSON.parse(res.data.result.button);
        if (btn?.filter(v => v.localName.includes('现金流查询')).length > 0) {
          this.tableTopButton = [...this.tableTopButton, {
            text: this.$t('menu.cashFlowQuery'),
            type: 'default',
            class: 'el-text-color',
            callback: (value) => {
              this.toCashFlow(value, this.searchParams.folder);
            },
            posType: res.data.result.name,
          }];
        }
        const fieldList = res.data.result?.fieldList ? res.data.result?.fieldList : JSON.parse(res.data.result?.field);
        this.columns = fieldList?.filter(v => v.display === 'Y').map((v, i) => {
          return {
            // ...v,
            name: v.code,
            prop: v.code,
            headerAlign: 'center',
            align: v?.attributeMap?.align,
            label: v.localName,
            minWidth: (v.width?.includes('%') ? document.querySelector('.table-box').offsetWidth * v.width : v.width) || '150px',
            render: (h, params) => {
              if (v.name === 'Operation') {
                const detailTab = {
                  class: 'el-icon-document',
                  path: '/7026/pos/forexSpotSingleCurrencyPosition/detail',
                  query: {
                    extraParams: JSON.stringify(params.row),
                    scriptId: detailScriptId,
                    posType,
                    searchParams: JSON.stringify(this.searchParams),
                  },
                };
                // 外汇期权头寸操作按钮展示图标不同
                const icons = scriptId === 'FxOptionPosition' ? [
                  { // to-do  2d情景分析
                    class: 'el-icon-upload2',
                    path: '',
                  },
                  { // tp-do  3d情景分析
                    class: 'el-icon-folder',
                    path: '',
                  },
                  detailTab,
                ] : [detailTab];
                return h('div',
                  icons.map((icon, index) =>
                    h('Icon', {
                      attrs: {
                        class: icon.class,
                      },
                      style: {
                        cursor: 'pointer',
                        color: '#017BFF',
                        fontSize: '16px',
                      },
                      on: {
                        click: () => {
                          Eui.service.router.push({
                            path: icon.path,
                            query: icon.query,
                          });
                        },
                      },
                    }),
                  ),
                );
              } else {
                return h('span', {
                  domProps: {
                    innerHTML: params.row[v.code],
                  },
                });
              }
            },
            fixed: v.frozen === 'Y',
            // width: v.width || 'auto',
          };
        });
      });
    },
    // 根据登录信息设置 默认账户
    async setUserFolder(scriptId) {
      const res = await this.$apis.getUserInfo();
      await this.$apis.findPreferenceDtoByUserIdAndType({ 'user': res.data.result.loginId, 'preferenceType': scriptId }).then(res => {
        this.searchParams.folder = res.data.result.preferenceData;
      });
    },
    async getOptions(code) { // 账户
      await this.$apis.getPosOptions({ 'codifierGrpCodes': code || 'folderTreeAuthWithGrp' }).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(scriptId, isNotLoad, posType) {
      console.log(scriptId, isNotLoad, posType, 'lklk');
      const param = [
        { field: 'posType', value: posType || scriptId },
        { field: 'flagHistory', value: '' },
      ];
      if (['FxSpotPairPosition', 'FxSpotCurrencyPosition', 'FxSwapPairPosition'].indexOf(scriptId) > -1) {
        param.push({ field: 'dataSet', value: 'RealTime' });
      }
      const keys = ['folder'];
      keys.forEach(key => {
        if (this.searchParams[key]) {
          param.push({ filed: key, value: this.searchParams[key] });
        }
      });
      const params = {
        ...this.searchParams,
        '__action': 'Query',
        '__scriptId': scriptId,
        '__sqlId': 'defaultSqlId',
        param: JSON.stringify(param),
      };
      // if (params.currency instanceof Array) {
      //   params.currency = params.currency.join(',');
      // }
      const transformedParams = {};
      for (const key in params) {
        transformedParams[`queryParam.${key}`] = params[key];
      }
      if (!isNotLoad) {
        this.loading = true;
      }
      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;
      });
    },
    toHistory(v, scriptId, posType) {
      console.log(v, scriptId, 'vvv');
      this.setQuery(scriptId, posType);
      if (v.localName === '历史头寸') { // 历史头寸
        Eui.service.router.push({
          path: '/7027/pos/historyPos',
          query: this.queryParam,
        });
      } else if (v.localName === '外汇现金流查询') { // 外汇现金流查询

      }
    },
    toCashFlow(value, folderId) { // 现金流查询
      console.log(value, 'vvvv');
      const productList = { 'forexSpotSingleCurrencyPosition': 'FXSPOT', 'forexSpotCurrencyPairPosition': 'FXSPOT', 'forexSwapPosition': 'FXSWAP,FXFWD,NDF', 'forexSwapTenorPosition': 'FXSWAP,FXFWD,NDF', 'forexOptionsPosition': 'FXOPTION_VANILA,FXOPTION_BARRIER,FXOPTION_DIGITAL,FXOPTION_TOUCH,FXOPTION_ASIAN,FXOPTION_RANGE_ACCRUAL' };
      Eui.service.router.push({
        path: '/7064/pos/posQuery/searchFxPosition',
        query: {
          folderId,
          posType: value.posType,
          product: productList[this.$route.path.split('/')[this.$route.path.split('/').length - 1]],
        },
      });
    },
    setQuery(scriptId, posType, detailScriptId) {
      const filteredParams = Object.assign({}, this.searchParams);
      delete filteredParams.pageStart;
      delete filteredParams.pageLimit;
      this.queryParam = {
        scriptId,
        posType: posType || scriptId,
        searchParams: JSON.stringify(filteredParams),
      };
      if (detailScriptId) {
        this.queryParam.detailScriptId = detailScriptId;
      }
      if (this.formArr.length > 1) {
        this.queryParam.formArr = JSON.stringify(this.formArr.slice(1));
      }
    },
    handleClick(tab, scriptId, detailScriptId, posType) {
      console.log(tab.index, scriptId, 'eee');
      this.activeTab = tab.index;
      if (tab.index === '1') { // 历史头寸
        this.setQuery(scriptId, posType, detailScriptId);
      }
    },
    startTimer(e, scriptId) {
      if (e) {
        this.timer = setInterval(() => {
          this.getTableList(scriptId, true);
        }, this.configObj.interVal);
      } else {
        this.clearTimer();
      }
    },
    async exportPage(scriptId, posType, folder, type) { // 导出当前页  导出全部
      const arr = this.columns.map(v => {
        return {
          field: v.prop,
          width: v.width || v.minWidth,
          label: commonMore.encodeUnicode(v.label),
          title: `<span class="LANG" langid="${scriptId}.${v.prop}">${commonMore.encodeUnicode(v.label)}</span>`,
        };
      });
      const params = {
        'queryParam.__scriptId': scriptId,
        'queryParam.pageCtrl': false,
        'queryParam.__action': 'Export',
        'queryParam.__exportType': 'XLSX',
        'queryParam.folder': folder,
        'queryParam.__sqlId': 'defaultSqlId',
        'queryParam.pageLimit': 50,
        'queryParam.__exportSubType': type, // 0 当前页  1全部
        'queryParam.__exportNum': type === 1 ? '-1' : '',
        'queryParam.pageStart': 1,
        'cols': JSON.stringify(arr),
        'queryParam.__exportHead': JSON.stringify(this.columns.map(v => {
          return {
            name: v.label,
            key: v.prop,
            width: v.width || v.minWidth,
            align: v.align,
          };
        })),
        'queryParam.param': JSON.stringify([{ 'field': 'posType', 'value': posType }, { 'field': 'flagHistory', 'value': '' }, { 'field': 'folder', 'value': folder }]),
        'queryParam.__gridType': 'treegrid',
        'queryParam.__idField': 'id',
        'queryParam.__closedItem': JSON.stringify(this.$refs.table.notExpandRows),
      };
      const formObj = new FormData();

      // 这里将整个 params 作为 reqJson 对象添加到 formObj 中
      formObj.append('reqJson', params);
      // const { data, fileName } = await this.$apis.exportForData(formObj);
      const { data, fileName } = await this.$apis.getForeignCurrencyList(params);
      // const url = window.origin.replace(/^https?:/, '') + (process.env.NODE_ENV !== 'production' ? '/dev' : '') + '/pos/equery.action';
      // console.log(url, 'uuu');
      // fetch(url, {
      //   method: 'POST',
      //   body: formObj,
      // })
      //   .then(response => response.json())
      //   .then(data => {
      //     console.log('成功:', data);
      //   })
      //   .catch((error) => {
      //     console.error('错误:', error);
      //   });

      console.log(data, fileName, '数据');
      const link = document.createElement('a');
      link.href = URL.createObjectURL(data);
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
    },
    exportAll() { // 导出全部

    },
  },
};
