<!-- 报表查询-平台分润报表-机构分润统计明细 -->
<template>
    <teleport to="#appPageTeleport">
        <app-view>
            <app-table :data="dataList" :columns="tableColumns" :loading="loading" :highlight-current-row="false"
                :span-method="arraySpanMethod" :summary-method="getSummaries" show-summary>
                <template #headerLeft>
                    <span>{{ `${formatDate}【${record.areaname}】分润明细月报表` }}</span>
                </template>
                <template #headerRight>
                    <div>
                        <el-button @click="emit('closed')">关闭</el-button>
                    </div>
                </template>
                <!-- 商品/市场 -->
                <template #goodscode="{ row }">
                    <el-link type="primary" @click="showComponent('Details', row)">
                        {{ row.goodscode || row.goodsid }}
                    </el-link>
                </template>
            </app-table>
            <component ref="componentRef" :is="componentMap.get(componentId)" v-bind="componentProps"
                @closed="closeComponent" v-if="componentId" />
        </app-view>
    </teleport>
</template>

<script lang="ts" setup>
import { ref, reactive, PropType, computed, defineAsyncComponent } from 'vue'
import { ElMessage } from 'element-plus'
import { getQuarterName } from '@/constants/report'
import { useEnum } from '@/hooks/enum'
import { useComponent } from '@/hooks/component'
import { useRequest } from '@/hooks/request'
import { shareAmountQuery } from '@/services/api/report'
import { useComposeTable } from '@pc/components/base/table'
import moment from 'moment'
import AppTable from '@pc/components/base/table/index.vue'

const props = defineProps({
    queryParams: {
        type: Object as PropType<Model.ShareAmountQueryPlatReq>,
        required: true
    },
    record: {
        type: Object as PropType<Model.ShareAmountQueryPlatRsp>,
        required: true
    }
})

const emit = defineEmits(['closed'])

const componentMap = new Map<string, unknown>([
    ['Details', defineAsyncComponent(() => import('@pc/views/report/instprofitshare/components/details/index.vue'))], // 机构分润单据明细
])

const roleTypeEnum = useEnum('roleType') // 角色
const divideFeekindEnum = useEnum('divide_feekind') // 费用类型

// 组件属性
const componentProps = reactive<{ queryParams: Partial<Model.ShareAmountQueryReq>; record: Partial<Model.ShareAmountQueryRsp>; }>({
    queryParams: {
        areaid: props.record.areaid,
        cycletype: props.queryParams.cycletype,
        tradedate: props.queryParams.tradedate,
        quarter: props.queryParams.quarter
    },
    record: {}
})

const { componentRef, componentId, openComponent, closeComponent } = useComponent()

const { getSummaries } = useComposeTable<Model.ShareAmountQueryRsp>({
    rowKey: 'areaaccountid',
    sumText: '汇总',
    summaryFields: [{ fieldName: 'totalcount', decimals: 0 }, 'totalfee', 'divideamount']
})

const { dataList, loading } = useRequest(shareAmountQuery, {
    params: componentProps.queryParams,
    onError: (err) => {
        ElMessage.error(err)
    }
})

// 计算行合并值
const arraySpanMethod = (data: { row: Model.ShareAmountQueryRsp; rowIndex: number; columnIndex: number; }) => {
    if (data.columnIndex < 2) {
        let rowspan = 1
        // 统计当前行与后续行中相同名称的数量
        for (let i = data.rowIndex + 1; i < dataList.value.length; i++) {
            if (dataList.value[i].areatype === data.row.areatype) {
                rowspan++
            } else {
                break
            }
        }
        // 如果上一行和当前行名称相同
        if (data.rowIndex > 0 && dataList.value[data.rowIndex - 1].areatype === data.row.areatype) {
            return [0, 0] // 隐藏单元格
        }
        return [rowspan, 1] // 合并行数，列数保持为 1
    }
}

const tableColumns = ref<Model.TableColumn[]>([
    { field: 'areatype', label: 'report.profitshare.areatype', formatValue: (val) => roleTypeEnum.getEnumTypeName(val) },
    { field: 'areaaccountid', label: 'report.profitshare.areaaccountid' },
    { field: 'goodscode', label: 'report.profitshare.goodsname' },
    { field: 'tradefeetype', label: 'report.profitshare.searchtype', formatValue: (val) => divideFeekindEnum.getEnumTypeName(val) },
    { field: 'totalcount', label: 'report.profitshare.totalcount' },
    { field: 'totalfee', label: 'report.profitshare.totalfee' },
    { field: 'divideamount', label: 'report.profitshare.divideamount' }
])

const showComponent = (code: string, row: Model.ShareAmountQueryRsp) => {
    componentProps.record = row
    openComponent(code)
}

const formatDate = computed(() => {
    const { tradedate, quarter } = props.queryParams

    const formats = new Map([
        [4, { parse: 'YYYY', output: 'YYYY年' }],
        [6, { parse: 'YYYYMM', output: 'YYYY年MM月' }],
        [8, { parse: 'YYYYMMDD', output: 'YYYY年MM月DD日' }],
    ])

    const formatConfig = formats.get(tradedate.length)

    if (formatConfig) {
        const { parse, output } = formatConfig
        return moment(tradedate, parse).format(output) + (quarter ? getQuarterName(quarter) : '')
    }

    return tradedate
})
</script>