<template>
  <!-- 实时敞口-->
  <mtp-table-scroll>
    <template #header>
      <div class="real-time-header" v-if="isPingAnOem()">
        <span class="dialogSpan">每隔</span>
        <a-select class="typeSelect real-time-select" style="width: 100px" v-model:value="timer" @change="timerChange" placeholder="请选择间隔时间">
          <a-select-option :value="item.id" v-for="item in diffTimes" :key="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
        <span class="dialogSpan">刷新一次，倒计时 </span> <span class="red">{{ num }}</span>
        <a-button type="button" class="operBtn ant-btn" @click="setTimerAction">{{ isStart ? '停止监控' : '开始监控' }}</a-button>
      </div>
      <filterCustomTable @search="updateColumn" v-else> </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 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 #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 #contracttype="{ record }">
      <span>{{ getPlanContractType(record.contracttype) }}</span>
    </template>
  </mtp-table-detail>
</template>

<script lang="ts">
import MtpTableScroll from '@/common/components/tableScroll/index.vue';
import { defineComponent, onUnmounted, ref, watch } 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 { 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 timerUtil from '@/utils/timer/timerUtil';
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,
    filterCustomTable,
  },
  setup() {
    const diffTimes = [
      { id: 1, name: '3秒' },
      { id: 2, name: '5秒' },
      { id: 3, name: '10秒' },
    ];
    const timer = ref<number>(1);
    const num = ref<number>(3);
    const isStart = ref<boolean>(false);
    // 表格列表数据
    const { loading, tableList, queryTable } = queryTableList<ErmcpRealExposureModel>(true, 2);
    // 控制明细显示/隐藏
    const visible = ref(true);
    // 获取列表数据
    const queryTableAction = () => queryTable(QueryActualExposure).then((res) => {
      if (res.length) {
        selectedRow.value = res[0];
      }
    });
    const param: ComposeTableDetailParam = {
      queryFn: queryTableAction, // 查询表格数据
      // tableName: 'table_pcweb_exposure', // 表头key
      menuType: EnumRouterName.exposure_realtime, // 当前tab页对应的code
    };
    if (!isPingAnOem()) {
      param.tableName = 'table_pcweb_exposure';
    }
    // 切换间隔时间
    function timerChange() {
      timerUtil.clearInterval('realTime');
      timerUtil.clearInterval('countdown');
      isStart.value = false;
      num.value = +diffTimes.find((e) => e.id === timer.value)!.name.replace('秒', '');
    }
    function setTimer() {
      timerUtil.clearInterval('realTime');
      if (isStart.value) {
        timerUtil.setInterval(
          () => {
            queryTableAction();
          },
          timer.value * 1000,
          'realTime'
        );
      }
    }
    watch(num, () => {
      if (num.value === 0) {
        timerUtil.clearInterval('countdown');
        num.value = 0;
      }
    });
    onUnmounted(() => {
      timerUtil.clearInterval('realTime');
      timerUtil.clearInterval('countdown');
    });
    const setTimerOut = () => {
      timerUtil.setInterval(
        () => {
          num.value = num.value - 1;
        },
        1000,
        'countdown'
      );
    };
    function setTimerAction() {
      isStart.value = !isStart.value;
      if (isStart.value) {
        setTimerOut();
        setTimer();
      } else {
        timerUtil.clearInterval('realTime');
        timerUtil.clearInterval('countdown');
      }
    }
    const {
      columns,
      updateColumn, //  表头数据
      columnsDetail,
      registerColumnDetail,
      detailTableList, // 明细表头数据
      expandedRowKeys,
      selectedRow,
      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 = [];
      const { code, lable } = tabList[index];
      let fn = null;
      if (code === 'exposure_realtime_spot_details') {
        // 现货明细信息
        if (isPingAnOem()) {
          columnsDetail.value = spotColumns;
        } else {
          // 注册表头
          registerColumnDetail('table_pcweb_exposure_detail');
        }

        fn = QueryActualExposureDetail;

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

        fn = QueryAutualExposurePosition;
        queryResultLoadingAndInfo(fn, loading, { middleGoodsId: selectedRow.value?.MiddleGoodsID }).then((res) => {
          detailTableList.value = res;
        });
      } else {
        console.error(`${lable}没有配置对应的code: ${code},`);
        return;
      }
    }
    watch(selectedRow, () => {
      detailTableList.value = [];
      if (tabList.length) {
        visible.value = true;
        changeTab(tabIndex.value);
      }
    })

    return { loading, tableList, visible, columns, updateColumn, columnsDetail, detailTableList, expandedRowKeys, selectedRow, Rowclick, tabList, changeTab, formatNumber, getBizTypeName, getPlanContractType, getLogType, diffTimes, timer, timerChange, isStart, setTimerAction, isPingAnOem, num };
  },
});
</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 {
    padding: 5px 0 5px 5px;
    text-align: left;
}
.real-time-select {
    margin-left: 5px;
    margin-right: 5px;
}
</style>
