<template>
  <div class="RCSbox">
    <div class="cright">
      <FormSearch
        :form-arr="formArr"
        :form-data="formData"
        @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"
        operation-width="150px"
        :btn-button="operations"
        :table-top-button="tableTopButton"
        :operation-fixed="true"
        :is-need-pagination="true"
        :current-page="pageParams.pageNum"
        :page-size="pageParams.pageSize"
        :total="pageParams.total"
        :is-need-customcolumn="true"
        :is-need-import="false"
        :is-need-export="true"
        @sizeChange="handleSizeChange"
        @currentChange="handleCurrentChange"
        @customColumnChange="handleCustomColumnChange"
      />
    </div>
    <RCSDialog
      key="RCSDialogPrint"
      :title="$t('button.print')"
      :visible="printDialogVisible"
      :before-close="rcsDialogbeforeClose['print']"
      :destroy-on-close="true"
    >
      <template #default>
        <TradePrint
          v-if="printSelectRow"
          ref="tradePrint"
          :deal-id="printSelectRow?.dealId"
          :product="printSelectRow?.product"
          :instrument="printSelectRow?.instrument"
        />
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="rcsDialogBtnEvent['print']"
          >{{ $t('button.print') }}</el-button>
        </div>
      </template>
    </RCSDialog>
    <RCSDialog
      key="RCSDialogTrack"
      :title="$t('button.track')"
      :visible="trackDialogVisible"
      :before-close="rcsDialogbeforeClose['track']"
      :destroy-on-close="true"
    >
      <template #default>
        <TradeTrace
          v-if="trackSelectRow"
          :deal-id="trackSelectRow?.dealId"
        />
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            @click="rcsDialogBtnEvent['trackClose']"
          >{{ $t('button.close') }}</el-button>
        </div>
      </template>
    </RCSDialog>
  </div>
</template>

<script>
import FormSearch from '../../../components/formSearch/index.vue';
import PublicTable from '../../../components/table/index.vue';
import FormTools from '../../../utils/FormTools';
import RCSDialog from '@/components/RCSDialog';
import TradePrint from '../components/TradePrint';
import TradeTrace from '../components/TradeTrace';
import HighLight from '../components/TableFields/HighLight';

export default {
  name: 'DcsDailyTradeQuery',
  components: {
    FormSearch,
    PublicTable,
    RCSDialog,
    TradePrint,
    TradeTrace,
  },
  data() {
    return {
      formArr: [
        {
          type: 'select',
          prop: 'type',
          span: 4,
          attrs: {
            needStar: true,
            label: '类型',
            multiple: true,
            'collapse-tags': true,
          },
          options: [],
          rules: { required: true, message: '不能为空' },
        },
        {
          type: 'pickerDateSingle',
          prop: 'dateStart',
          span: 4,
          attrs: {
            needStar: true,
            label: '开始日期',
            'value-format': 'yyyyMMdd',
            rules: { required: true, message: '不能为空' },
          },
        },
        {
          type: 'pickerDateSingle',
          prop: 'dateEnd',
          span: 4,
          attrs: {
            needStar: true,
            label: '结束日期',
            'value-format': 'yyyyMMdd',
          },
          rules: { required: true, message: '不能为空' },
        },
        {
          type: 'selectTreeTable',
          prop: 'folder',
          span: 4,
          attrs: {
            label: '账户',
            placeholder: '请选择',
            info: { title: '账户检索' },
          },
          options: [],
        },
        {
          type: 'selectTransfer',
          prop: 'cptys',
          span: 4,
          attrs: {
            label: '交易对手',
            multiple: true,
            placeholder: '请选择',
            info: { title: '交易对手检索' },
            'collapse-tags': true,
          },
          options: [],
        },
        {
          type: 'selectTransfer',
          prop: 'products',
          span: 4,
          attrs: {
            label: '产品',
            multiple: true,
            placeholder: '请选择',
            'collapse-tags': true,
            transfer: { title: '产品检索' },
          },
          options: [],
        },
        {
          type: 'input',
          prop: 'underlyingSearch',
          span: 4,
          attrs: {
            label: '标的',
            placeholder: '请输入',
          },
          options: [],
        },
        {
          type: 'select',
          prop: 'dealStatuss',
          span: 4,
          attrs: {
            label: '交易状态',
            multiple: true,
            placeholder: '请选择',
            'collapse-tags': true,
          },
          options: [],
        },
        {
          type: 'select',
          prop: 'dealFlags',
          span: 4,
          attrs: {
            label: '交易性质',
            multiple: true,
            placeholder: '请选择',
            'collapse-tags': true,
          },
          options: [],
        },
        {
          type: 'input',
          prop: 'dealId',
          span: 4,
          attrs: {
            label: '交易流水号',
          },
        },
        {
          type: 'input',
          prop: 'globalId',
          span: 4,
          attrs: {
            label: '外部流水号',
          },
        },
        {
          type: 'input',
          prop: 'contractId',
          span: 4,
          attrs: {
            label: '组合号',
          },
        },
      ],
      // 默认值
      formData: {

      },

      // 获取列表前是否loading加载
      loading: false,

      tableInfo: {
        fileConfig: {
          uploadParams: {
            moduleName: 'dcsDailyTradeQuery',
            param: { 'multiple': false },
          },
        },
        tableHeight: document.documentElement.clientHeight - 286,
      },
      // table数据源
      tableData: [],

      // 表格项绑定的属性
      columns: [],
      // 操作栏自定义按钮
      operations: [
        {
          text: '打印',
          type: 'text',
          class: 'el-text-color',
          callback: (row) => {
            this.handleOpertions['print'](row);
          },
        },
        {
          text: '跟踪',
          type: 'text',
          class: 'el-text-color',
          callback: (row) => {
            this.handleOpertions['track'](row);
          },
        },
        {
          text: '生命周期',
          type: 'text',
          class: 'el-text-color',
          callback: (row) => {
            this.handleOpertions['lifeCycle'](row);
          },
        },
      ],
      tableTopButton: [

      ],

      // 搜索查询的参数
      pageParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      filtersMap: {},

      printDialogVisible: false,
      printSelectRow: null,
      trackDialogVisible: false,
      trackSelectRow: null,
      handleOpertions: {
        'track': (data) => {
          this.trackSelectRow = {
            dealId: data.dealId,
          };
          this.trackDialogVisible = !this.trackDialogVisible;
        },
        'print': (data) => {
          this.printSelectRow = {
            dealId: data.dealId,
            product: data.product,
            instrument: data.instrument,
          };
          this.printDialogVisible = !this.printDialogVisible;
        },
        'lifeCycle': (data) => {
          const dealId = data.dealId;
          const product = data.product;
          const instrument = data.instrument;

          // TODO this.$menuMap is null now
          // const id = this.$menuMap.get('/dcs/dcsLifeCycle');
          const id = '888970226';
          const path = 'dcs/dcsLifeCycle';
          this.$router.push(`/${id}/${path}?dealId=${dealId}&product=${product}&instrument=${instrument}&title=生命周期`);
        },
      },
      rcsDialogbeforeClose: {
        'print': (done) => {
          console.log('print before-close');
          this.printSelectRow = null;
          this.printDialogVisible = false;
          console.log('this.printDialogVisible', this.printDialogVisible);
        },
        'track': (done) => {
          console.log('track before-close');
          this.trackSelectRow = null;
          this.trackDialogVisible = false;
        },
      },
      rcsDialogBtnEvent: {
        'print': () => {
          this.$refs.tradePrint.print();
        },
        'trackClose': () => {
          this.trackDialogVisible = false;
        },
      },
    };
  },
  created() {
    this.initPage();
  },
  mounted() {
    this.queryPage();
  },
  methods: {
    comonfilter(value, row, column) {
      console.log('value', row, column);
      return row[column.property] === value;
    },
    /**
     * 初始化页面数据
     */
    async initPage() {
      await this.initFormData();
      this.queryComboxData();
    },
    /**
     * 初始化表单数据
     */
    async initFormData() {
      const date = FormTools.getNowStr();
      this.formData = {
        type: ['deal'],
        dateStart: date,
        dateEnd: date,
      };
    },
    /**
     * 查询 Table 数据
     */
    async queryPage() {
      const params = {
        'queryParam.moduleName': 'dcsDailyTradeQuery',
        'queryParam.type': FormTools.checkEmpty(this.formData['type'], ['deal']),
        'queryParam.dateStart': FormTools.format('date:yyyyMMdd', this.formData['dateStart']),
        'queryParam.dateEnd': FormTools.format('date:yyyyMMdd', this.formData['dateEnd']),
        'queryParam.folder': FormTools.checkEmpty(this.formData['folder'], ''),
        'queryParam.underlyingSearch': FormTools.checkEmpty(this.formData['underlyingSearch'], ''),
        'queryParam.dealId': FormTools.checkEmpty(this.formData['dealId'], ''),
        'queryParam.globalId': FormTools.checkEmpty(this.formData['globalId'], ''),
        'queryParam.contractId': FormTools.checkEmpty(this.formData['contractId'], ''),
        'queryParam.moreCondition': '{}',
        'queryParam.excludeGroup': 'Y',
        'queryParam.cptys': FormTools.checkEmpty(this.formData['cptys'], []),
        'queryParam.products': FormTools.checkEmpty(this.formData['products'], []),
        'queryParam.dealStatuss': FormTools.checkEmpty(this.formData['dealStatuss'], []),
        'queryParam.dealFlags': FormTools.checkEmpty(this.formData['dealFlags'], []),
        'queryParam.pageStart': FormTools.checkEmpty(this.pageParams.pageNum, 0),
        'queryParam.pageLimit': this.pageParams.pageSize,
      };

      this.loading = true;
      const res = await this.$apis.dcsQueryPage(params);
      if (res.success) {
        this.tableData = res.data.result.datals;
        this.pageParams.total = Number(res.data.result.total);
        this.loading = false;

        await this.initFiltersData(this.tableData);
        await this.initColunm();
      }
    },
    /**
     * 获取数据字典
     */
    async queryComboxData() {
      const params = {
        codifierGrpCodes: 'DailyType,folderTreeAuthWithGrp,cptys,productList,dealStatusList,DealFlagRcs,BondsIssueDirection,RepoDirectionRcs,BRRDirection,DealStatusRcs',
      };
      const res = await this.$apis.queryComboxData(params);
      if (res.success) {
        const result = res.data?.result;

        const filedOptionMap = new Map([
          ['type', 'DailyType'],
          ['dealStatuss', 'dealStatusList'],
          ['dealFlags', 'DealFlagRcs'],
          ['folder', 'folderTreeAuthWithGrp'],
          ['cptys', 'cptys'],
          ['products', 'productList'],
        ]);
        this.formArr.forEach(item => {
          if (filedOptionMap.has(item.prop) && result[filedOptionMap.get(item.prop)]) {
            item.options = result[filedOptionMap.get(item.prop)].map(sitem => ({ ...sitem, label: sitem.text, value: sitem.value }));
          }
        });

        this.$message.success('请求成功');
      }
    },
    /**
     * 初始化 table column 筛选数据
     * @param list
     */
    async initFiltersData(list) {
      const filterHeader = {
        'productStr': new Set([]),
        'dealId': new Set([]),
        'folder': new Set([]),
        'cptyStr': new Set([]),
        'underlying': new Set([]),
        'buySellStr': new Set([]),
        'valueDateStr': new Set([]),
        'maturityDateStr': new Set([]),
        'dealStatusStr': new Set([]),
      };
      const filtersMap = {
        'productStr': [],
        'dealId': [],
        'folder': [],
        'cptyStr': [],
        'underlying': [],
        'buySellStr': [],
        'valueDateStr': [],
        'maturityDateStr': [],
        'dealStatusStr': [],
      };
      list.forEach(item => {
        Object.keys(filterHeader).forEach(key => {
          if (!filterHeader[key].has(item[key])) {
            filterHeader[key].add(item[key]);
            filtersMap[key].push({ value: item[key], text: item[key] });
          }
        });
      });
      this.filtersMap = filtersMap;
      // console.log('filtersMap', filtersMap);
      this.initColunm();
    },
    /**
     * 初始化 table 列信息
     */
    async initColunm() {
      this.columns = [
        {
          prop: 'productStr',
          minWidth: '100px',
          align: 'center',
          label: '产品',
          filters: this.filtersMap.productStr,
          'filter-method': this.comonfilter,
          'filter-placement': 'bottom-end',
        },
        {
          prop: 'dealId',
          minWidth: '100px',
          align: 'center',
          label: '交易流水号',
          filters: this.filtersMap.dealId,
          'filter-method': this.comonfilter,
          'filter-placement': 'bottom-end',
          render: (h, context) => {
            // console.log('context h');
            return h(HighLight, {
              props: {
                dialogTitle: '交易详情',
                value: context.row['dealId'],
                action: 'detail',
                rowData: context.row,
              },
            });
          },
        },
        {
          prop: 'folder',
          minWidth: '200px',
          align: 'center',
          label: '账户',
          filters: this.filtersMap.folder,
          'filter-method': this.comonfilter,
          'filter-placement': 'bottom-end',
        },
        {
          prop: 'cptyStr',
          minWidth: '100px',
          align: 'center',
          label: '交易对手',
          filters: this.filtersMap.cptyStr,
          'filter-method': this.comonfilter,
          'filter-placement': 'bottom-end',
        },
        {
          prop: 'underlying',
          minWidth: '100px',
          align: 'center',
          label: '标的',
          filters: this.filtersMap.underlying,
          'filter-method': this.comonfilter,
          'filter-placement': 'bottom-end',
        },
        {
          prop: 'buySellStr',
          minWidth: '200px',
          align: 'center',
          label: '交易方向',
          filters: this.filtersMap.buySellStr,
          'filter-method': this.comonfilter,
          'filter-placement': 'bottom-end',
        },
        {
          prop: 'ccy1AmountStr',
          minWidth: '100px',
          align: 'center',
          label: '金额1',
        },
        {
          prop: 'ccy2AmountStr',
          minWidth: '100px',
          align: 'center',
          label: '金额2',
        },
        {
          prop: 'valueDateStr',
          minWidth: '200px',
          align: 'center',
          label: '起息日',
          filters: this.filtersMap.valueDateStr,
          'filter-method': this.comonfilter,
          'filter-placement': 'bottom-end',
        },
        {
          prop: 'maturityDateStr',
          minWidth: '100px',
          align: 'center',
          label: '到期日',
          filters: this.filtersMap.maturityDateStr,
          'filter-method': this.comonfilter,
          'filter-placement': 'bottom-end',
        },
        {
          prop: 'dealStatusStr',
          minWidth: '200px',
          align: 'center',
          label: '交易状态',
          filters: this.filtersMap.dealStatusStr,
          'filter-method': this.comonfilter,
          'filter-placement': 'bottom-end',
        },
        {
          prop: 'amount1Str',
          minWidth: '100px',
          align: 'center',
          label: '拆美元金额',
        },
      ];
    },
    searchSubmit(val) {
      this.queryPage();
    },
    resetForm() {
      this.formData = {};
    },
    outOperation(val, index, prop, num) {
      console.log(val, index, prop, num);
    },

    // 页面展示条数改变事件-pageSize
    handleSizeChange(pageSize) {
      this.pageParams.pageSize = pageSize;
      this.queryPage();
    },
    // 页面切换事件-pageNum
    handleCurrentChange(pageNum) {
      this.pageParams.pageNum = pageNum;
      this.queryPage();
    },
    // 数据列确定修改事件
    handleCustomColumnChange(val) {
      // console.log('数据列确定修改事件',val);
    },
  },
};
</script>

  <style lang="scss" scoped>
  .RCSbox {
    width: 100%;
    height: 100%;
    display: flex;
    .cright {
      width: 100%;
      .table {
        margin-top: 8px;
        border-radius: 4px;
      }
    }
  }
  </style>
