<!-- 报表查询-平台分润报表 -->
<template>
    <app-view>
        <template #header>
            <app-filter :option="filterOption">
                <!-- 日期 -->
                <template #tradedate="{ item }">
                    <el-form-item :label="item.label" prop="tradedate">
                        <el-date-picker :type="dateType" v-model="item.value" :format="dateFormat"
                            :value-format="dateFormat" :placeholder="t('common.pleasechoice')" />
                    </el-form-item>
                </template>
                <!-- 季度 -->
                <template #quarter="{ item }">
                    <el-form-item :label="item.label" prop="quarter"
                        v-if="queryParams.cycletype === ReportType.Quarter">
                        <el-select v-model="item.value">
                            <el-option v-for="option in getQuarterList()" :key="option.value" :label="option.label"
                                :value="option.value" />
                        </el-select>
                    </el-form-item>
                    <template v-else>
                        {{ (item.value = undefined) }}
                    </template>
                </template>
                <!-- 会员代码/名称 -->
                <template #areaname="{ item }">
                    <el-form-item :label="item.label">
                        <app-select-member v-model="item.value" :params="{ usertype: '1,2' }" />
                    </el-form-item>
                </template>
                <!-- 所属营销中心 -->
                <template #yxareauserid="{ item }">
                    <el-form-item :label="item.label">
                        <app-select-member v-model="item.value" :params="{ roles: '3' }" />
                    </el-form-item>
                </template>
            </app-filter>
        </template>
        <app-table :data="dataList" :columns="tableColumns" :loading="loading" :highlight-current-row="false"
            :span-method="arraySpanMethod">
            <template #headerLeft>
                <app-operation :data-list="getActionButtons(['query_internal_profitshare_export'])"
                    @click="(code: string) => openComponent(code)" />
            </template>
            <!-- 会员/机构 -->
            <template #areaname="{ row }">
                <el-link type="primary" @click="openComponent('Details', row)">{{ row.areaname }}</el-link>
            </template>
        </app-table>
        <component :is="componentMap.get(componentId)" v-bind="{ record, queryParams }" @closed="closeComponent"
            v-if="componentId" />
    </app-view>
</template>

<script lang="ts" setup>
import { computed, ref, defineAsyncComponent } from 'vue'
import { ElMessage } from 'element-plus'
import { useEnum } from '@/hooks/enum'
import { useDataFilter } from '@/hooks/datatable-v2'
import { useRequest } from '@/hooks/request'
import { formatDate } from '@/filters'
import { shareAmountQueryPlat } from '@/services/api/report'
import { useOperation } from '@/hooks/operation'
import { i18n } from '@/stores'
import { getReportTypeList, ReportType, getQuarterList } from '@/constants/report'
import AppTable from '@pc/components/base/table/index.vue'
import AppOperation from '@pc/components/base/operation/index.vue'
import AppFilter from '@pc/components/base/table-filter-v2/index.vue'
import AppSelectMember from '@pc/components/modules/select-member/index.vue'

const roleTypeEnum = useEnum('roleType') // 角色

const t = i18n.global.t

const { componentMap, componentId, record, openComponent, closeComponent, getActionButtons } = useOperation<Model.ShareAmountQueryPlatRsp>({
    onClose: () => onSearch()
})

// 机构分润统计明细
componentMap.set('Details', defineAsyncComponent(() => import('./components/details/index.vue')))

const { dataList, loading, run } = useRequest(shareAmountQueryPlat, {
    manual: true,
    onError: (err) => {
        ElMessage.error(err)
    }
})

const { queryParams, filterOption, getQueryParams, resetFilters } = useDataFilter<Model.ShareAmountQueryPlatReq>({
    filters: [
        {
            field: 'cycletype',
            label: t('report.profitshare.cycletype'),
            value: 0,
            options: () => getReportTypeList(),
            onChange: () => resetFilters('tradedate', 'quarter')
        },
        {
            field: 'tradedate',
            label: t('report.profitshare.tradedate'),
            required: true
        },
        {
            field: 'quarter',
            label: t('report.profitshare.quarter'),
            required: true
        },
        {
            field: 'areaname',
            label: '会员代码/名称',
        },
        {
            field: 'yxareauserid',
            label: '所属营销中心',
        }
    ],
    buttons: [
        { label: t('operation.search'), className: 'el-button--primary', onClick: () => onSearch() },
        { label: t('operation.reset'), className: 'el-button--primary', validateEvent: false, onClick: () => resetFilters() }
    ]
})

// 日期类型
const dateType = computed(() => {
    switch (queryParams.value.cycletype) {
        case ReportType.Week:
            return 'week'
        case ReportType.Month:
            return 'month'
        case ReportType.Quarter:
        case ReportType.Year:
            return 'year'
        default:
            return 'date'
    }
})

// 日期格式
const dateFormat = computed(() => {
    switch (queryParams.value.cycletype) {
        case ReportType.Month:
            return 'YYYYMM'
        case ReportType.Quarter:
        case ReportType.Year:
            return 'YYYY'
        default:
            return 'YYYYMMDD'
    }
})

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

const tableColumns = ref<Model.TableColumn[]>([
    { field: 'areaname', label: '会员/机构' },
    { field: 'areatype', label: 'report.profitshare.areatype', formatValue: (val) => roleTypeEnum.getEnumTypeName(val) },
    { field: 'areaaccountid', label: 'report.profitshare.areaaccountid' },
    { field: 'totalcount', label: 'report.profitshare.totalcount' },
    { field: 'totalfee', label: 'report.profitshare.totalfee' },
    { field: 'divideamount', label: 'report.profitshare.divideamount' }
])

const onSearch = () => {
    const qs = getQueryParams()
    qs.tradedate = formatDate(qs.tradedate, dateFormat.value) // 处理日期格式
    run(qs)
}
</script>