<template>
  <!-- 实时敞口-->
  <mtp-table-scroll>
    <template #header>
      <filterCustomTable @search="updateColumn" @update="queryTableAction">
        <div class="real-time-header">
          <span class="dialogSpan">每隔</span>
          <a-input-number class="commonInput real-time-select" :min="10" :max="60" :disabled="isStart" v-model:value="second"></a-input-number>
          <span class="dialogSpan">秒刷新一次，倒计时 </span> <span class="red">{{ counter }}</span>
          <a-button class="operBtn ant-btn" @click="setTimerAction">{{ isStart ? '停止监控' : '开始监控' }}</a-button>
        </div>
      </filterCustomTable>
    </template>
    <template #default="{ scroll }">
      <a-table :columns="columns" class="srcollYTable" :pagination="false" :expandedRowKeys="expandedRowKeys" :customRow="Rowclick" :rowKey="(record,index)=>index" :data-source="tableList" :scroll="scroll">
        <template #expandedRowRender="{ record }">
          <mtp-table-button class="btn-list-sticky" :buttons="buttons" :record="record" @click="openComponent" />
        </template>
        <template v-if="isPingAnOem()" #index="{ index }">
          <span>{{ index + 1 }}</span>
        </template>
      </a-table>
    </template>
  </mtp-table-scroll>
  <!-- 明细 -->
  <mtp-table-detail :columns="columnsDetail" :data-source="detailTableList" :tabs="tabList" v-model:visible="visible" @change="changeTab">
    <!-- 交易用户 -->
    <template #accountid="{record}">
      <span>{{record.accountid + '/' + record.hedgeaccountcode}}</span>
    </template>
    <template #convertfactor="{record}">
      <span>{{record.convertratio}}</span>
    </template>
    <template #goodsname="{ record }" v-if="!isPingAnOem()">
      <span>{{ record.goodsname + '/' + record.goodscode }}</span>
    </template>
    <template v-if="isPingAnOem()" #index="{ index }">
      <span>{{ index + 1 }}</span>
    </template>
    <template #changeQty="{ record }">
      <span>{{ record.changeQty.toFixed(2) }}</span>
    </template>
    <template #diffhedgeqty="{ record }">
      <span>{{ record.diffhedgeqty.toFixed(2) }}</span>
    </template>
    <!-- 类型 -->
    <template #contracttype="{ record }">
      <span>{{ getPlanContractType(record.contracttype) }}</span>
    </template>
  </mtp-table-detail>
  <component :is="componentId" v-if="componentId" :selectedRow="selectedRow" @cancel="closeComponent"></component>
</template>

<script lang="ts">
import MtpTableScroll from '@/common/components/tableScroll/index.vue';
import { defineComponent, onUnmounted, ref, watch, defineAsyncComponent } from 'vue';
import filterCustomTable from './filter.vue';
import { QueryActualExposure, QueryActualExposureDetail, QueryAutualExposurePosition } from '@/services/go/ermcp/exposure/index';
import { ErmcpRealExposureModel } from '@/services/go/ermcp/exposure/interface';
import { queryTableList } from '@/common/setup/table';
import { ComposeTableDetailParam } from '@/common/setup/table/interface';
import { MtpTableButton } from '@/common/export/commonTable';
import { handleComposeTable_detail } from '@/common/setup/table/compose';
import { queryResultLoadingAndInfo } from '@/common/methods/request/resultInfo';
import { EnumRouterName } from '@/common/constants/enumRouterName';
import { initData } from '@/common/methods';
import { formatNumber } from '@/common/methods/format';
import { getBizTypeName, getLogType } from '@/common/constants/enumsName';
import { getPlanContractType } from '@/views/business/plan/setup';
import { isPingAnOem } from '@/common/config/projectName';
import { pingan_realTime_columns } from './setup';
import { getTableButton } from '@/common/setup/table/button';
import MtpTableDetail from '@/common/components/tableDetail/index.vue';

export default defineComponent({
  name: EnumRouterName.exposure_realtime,
  components: {
    MtpTableScroll,
    MtpTableDetail,
    MtpTableButton,
    filterCustomTable,
    exposure_realtime_index_add: defineAsyncComponent(() => import('@/views/market/futures/compoments/futures-trade/index.vue')), // 下单
  },
  setup() {
    const userId = ref(0);
    const timer = ref(0);
    const second = ref(10); // 倒计时秒数
    const counter = ref(0); // 倒计时计数器
    const isStart = ref(false);
    const visible = ref(true); // 控制明细显示/隐藏
    const { loading, tableList, queryTable } = queryTableList<ErmcpRealExposureModel>(true, 2); // 表格列表数据
    const buttons = getTableButton(['exposure_realtime_index_add']); // 权限按钮

    // 获取列表数据
    const queryTableAction = (userid = 0) => {
      userId.value = userid;
      queryTable(QueryActualExposure, userid).then((res) => {
        if (res.length) {
          selectedRow.value = res[0];
        } else {
          changeTab(tabIndex.value)
        }
      })
    }

    const param: ComposeTableDetailParam = {
      queryFn: queryTableAction, // 查询表格数据
      // tableName: 'table_pcweb_exposure', // 表头key
      menuType: EnumRouterName.exposure_realtime, // 当前tab页对应的code
    };

    if (!isPingAnOem()) {
      param.tableName = 'table_pcweb_exposure';
    }

    const setTimerAction = () => {
      clearInterval(timer.value)
      isStart.value = !isStart.value;
      counter.value = 0;

      if (isStart.value) {
        counter.value = second.value;
        countdown();
      }
    }

    const countdown = () => {
      timer.value = window.setInterval(() => {
        if (counter.value) {
          counter.value--;
        } else {
          counter.value = second.value;
          queryTableAction();
        }
      }, 1000);
    }

    onUnmounted(() => {
      clearInterval(timer.value)
    });

    const {
      columns,
      updateColumn, //  表头数据
      columnsDetail,
      registerColumnDetail,
      detailTableList, // 明细表头数据
      expandedRowKeys,
      selectedRow,
      componentId,
      openComponent,
      closeComponent,
      Rowclick, // 表格事件
    } = handleComposeTable_detail<ErmcpRealExposureModel>(param);

    // 底部明细标签
    const tabList = getTableButton(['exposure_realtime_spot_details', 'exposure_realtime_futures_details', 'exposure_realtime_params_details']);
    // 当前选中的标签
    const tabIndex = ref(0);

    const { listColumns, spotColumns } = pingan_realTime_columns();
    initData(() => {
      if (isPingAnOem()) {
        columns.value = listColumns;
      }
    });

    // 切换明细
    function changeTab(index: number) {
      tabIndex.value = index;
      detailTableList.value = [];
      visible.value = true;

      const { code, lable } = tabList[index];
      if (code === 'exposure_realtime_spot_details') {
        // 现货明细信息
        if (isPingAnOem()) {
          columnsDetail.value = spotColumns;
        } else {
          // 注册表头
          registerColumnDetail('table_pcweb_exposure_detail');
        }

        if (selectedRow.value) {
          queryResultLoadingAndInfo(QueryActualExposureDetail, loading, { userid: userId.value, middlegoodsid: selectedRow.value.MiddleGoodsID }).then((res) => {
            detailTableList.value = res;
          });
        }
      } else if (code === 'exposure_realtime_futures_details') {
        // 期货明细
        // 注册表头
        registerColumnDetail('table_pcweb_exposure_futures_detail');

        if (selectedRow.value) {
          queryResultLoadingAndInfo(QueryAutualExposurePosition, loading, { userid: userId.value, middleGoodsId: selectedRow.value.MiddleGoodsID }).then((res) => {
            detailTableList.value = res;
          });
        }
      } else {
        console.error(`${lable}没有配置对应的code: ${code},`);
        return;
      }
    }
    watch(selectedRow, () => changeTab(tabIndex.value))

    return { loading, openComponent, closeComponent, componentId, tableList, visible, columns, buttons, queryTableAction, updateColumn, columnsDetail, detailTableList, expandedRowKeys, selectedRow, Rowclick, tabList, changeTab, formatNumber, getBizTypeName, getPlanContractType, getLogType, second, counter, isStart, setTimerAction, isPingAnOem };
  },
});
</script>

<style lang="less">
.exposure-real-time {
    position: relative;
    overflow: hidden;
    .bottomTable {
        width: 100%;
        .flex;
        flex-direction: column;
        .topTable {
            height: calc(100% - 46px);
            .ant-table {
                background-color: transparent;
            }
        }
    }
}
.real-time-header {
    margin-left: auto;
}
.real-time-select {
    margin-left: 5px;
    margin-right: 5px;

    .ant-input-number-input {
        text-align: center;
    }
}
</style>
