<template>
    <!-- 套期交易-执行中 -->
    <mtp-table-scroll>
        <template #header>
            <Filter @search="updateColumn">
                <mtp-table-button class="btn-list-sticky" :buttons="headerButtons" @click="openComponent" />
                <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>
            </Filter>
        </template>
        <template #default="{ scroll }">
            <a-table :columns="columns" class="srcollYTable" :pagination="false" :loading="loading"
                :rowClassName="rowClassName" :expandedRowKeys="expandedRowKeys" :customRow="Rowclick"
                :rowKey="(record, index) => index" :data-source="dataList" :scroll="scroll">
                <template #expandedRowRender="{ record }">
                    <mtp-table-button class="btn-list-sticky" :buttons="tableButtons(record)" :record="record"
                        @click="openComponent" />
                </template>
                <!-- 套期类型 -->
                <template #hedgedtype="{ text }">
                    <span>{{ getHedgedTypeName(text) }}</span>
                </template>
                <!-- 套期商品 -->
                <template #middlegoodsname="{ text }">
                    <span>{{ text || '--' }}</span>
                </template>
                <!-- 未执行套期量 -->
                <template #unexehedgeqty="{ text }">
                    <span>{{ getDecimalsNum(text) }}</span>
                </template>
                <!-- 期货套期量 -->
                <template #futurehedgeqty="{ text }">
                    <span>{{ getDecimalsNum(text) }}</span>
                </template>
                <!-- 期现敞口量 -->
                <template #hiexpsoure="{ text }">
                    <span>{{ getDecimalsNum(text) }}</span>
                </template>
            </a-table>
        </template>
    </mtp-table-scroll>
    <mtp-tab-component class="table-detail" :options="{ selectedRow }" />
    <component :is="componentId" v-if="componentId" v-bind="{ selectedRow }" @cancel="closeComponent"></component>
</template>

<script lang="ts">
import { computed, ref } from 'vue'
import { queryTableList, MtpTableButton, defineAsyncComponent, defineComponent, handleComposeTable } from '@/common/export/commonTable'
import { getHedgedTypeName } from '@/@next/constants/enum/hedgedType'
import { Ermcp8RunningHedgeditemReq, Ermcp2HedgedItemRsp, HedgedItemMiddleGoodsList } from '@/services/go/ermcp/hedgedItem/interface'
import { queryErmcp8RunningHedgeditem } from '@/services/go/ermcp/hedgedItem'
import { useMenu } from '@/@next/hooks/common'
import { getUserId } from '@/services/bus/user'
import { getDecimalsNum } from '@/utils/number'
import MtpTableScroll from '@/common/components/tableScroll/index.vue'
import MtpTabComponent from '@/@next/components/base/tab-component/index.vue'
import Filter from '../components/filter/index.vue'

export default defineComponent({
    components: {
        MtpTabComponent,
        MtpTableButton,
        MtpTableScroll,
        Filter,
        add: defineAsyncComponent(() => import('../components/add/index.vue')), // 新增
        trade: defineAsyncComponent(() => import('@/views/market/futures/compoments/futures-trade/index.vue')), // 期货交易
        ending: defineAsyncComponent(() => import('../components/ending/index.vue')), // 完结项目
    },
    setup() {
        const { authFilter } = useMenu();
        const { loading, tableList, queryTable } = queryTableList<Ermcp2HedgedItemRsp>(true, 2); // 表格列表数据
        const timer = ref(0);
        const second = ref(10); // 倒计时秒数
        const counter = ref(0); // 倒计时计数器
        const isStart = ref(false);

        const headerButtons = authFilter(['add']);
        const tableButtons = (item: Ermcp2HedgedItemRsp) => {
            const buttons = authFilter(['add'], true);
            if (item.wrstandardid) {
                return buttons;
            }
            return buttons.filter((e) => e.code !== 'trade');
        }

        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;
                    queryFn();
                }
            }, 1000);
        }

        const queryFn = () => {
            const param: Ermcp8RunningHedgeditemReq = {
                userid: getUserId(),
            }
            queryTable(queryErmcp8RunningHedgeditem, param).then((res) => {
                const selectedRow = composeTable.selectedRow.value;
                composeTable.selectedRow.value = undefined;

                window.setTimeout(() => {
                    composeTable.selectedRow.value = selectedRow;
                    if (!selectedRow && res.length) {
                        composeTable.selectedRow.value = dataList.value[0];
                    }
                }, 0)
            })
        }

        // 表格通用逻辑
        const composeTable = handleComposeTable<Ermcp2HedgedItemRsp>({
            queryFn,
            tableName: 'table_pcweb_hedgeditem_trade_running',
        })

        const dataList = computed(() => {
            const result: (Ermcp2HedgedItemRsp & HedgedItemMiddleGoodsList)[] = [];
            tableList.value.forEach((item) => {
                const middleGoodsList = item.middlegoodslist;
                if (!middleGoodsList.length) {
                    middleGoodsList.push({
                        futurehedgeqty: 0,
                        hedgeditemid: '',
                        hiexpsoure: 0,
                        middlegoodscode: '',
                        middlegoodsid: 0,
                        middlegoodsname: '',
                        unexehedgeqty: 0,
                    })
                }
                middleGoodsList.forEach((mg) => {
                    result.push({
                        ...mg,
                        ...item,
                    })
                })
            })
            return result;
        })

        // 自定义表格列，合并行选项
        // const columns = computed(() => {
        //     const filters = ['middlegoodsname', 'unexehedgeqty', 'futurehedgeqty', 'hiexpsoure']
        //     const result = composeTable.columns.value;

        //     result.forEach((e) => {
        //         if (!filters.includes(e.dataIndex!)) {
        //             let parentKey = ''; // 初始化前一条记录的key，用来比较当前记录和前一条记录是否相同

        //             e.customRender = (row: { text: string; record: Ermcp2HedgedItemRsp }) => {
        //                 const { text, record } = row;
        //                 const rowSpan = record.middlegoodslist.length; // 通过商品列表数计算需要合并的行数
        //                 const option = {
        //                     children: text,
        //                     props: {
        //                         rowSpan: rowSpan
        //                     }
        //                 }

        //                 if (e.dataIndex === 'hedgedtype') {
        //                     option.children = getHedgedTypeName(record.hedgedtype);
        //                 }

        //                 if (record.hedgeditemid === parentKey) {
        //                     option.props.rowSpan = 0;
        //                 }

        //                 parentKey = record.hedgeditemid;
        //                 return option;
        //             }
        //         }
        //     })

        //     return result;
        // })

        return {
            ...composeTable,
            //columns,
            loading,
            dataList,
            headerButtons,
            tableButtons,
            second,
            counter,
            isStart,
            setTimerAction,
            getDecimalsNum,
            getHedgedTypeName,
        }
    }
})
</script>

<style lang="less" scoped>
.real-time-header {
    margin-left: auto;
    padding: 0;
}

.real-time-select {
    margin-left: 5px;
    margin-right: 5px;

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