<!-- 结算管理-分润付款确认-详情 -->
<template>
    <teleport to="#appPageTeleport">
        <app-view>
            <template #header>
                <app-filter :option="filterOption" />
            </template>
            <app-table :data="dataList" :columns="tableColumns" selection-type="multiple" :loading="loading"
                @select="onSelect" @selectable="onSelectable">
                <template #headerLeft>
                    <span>{{ t('settlement.profitsharepay.details.tradedate') }}{{ record.tradedate }}</span>
                </template>
                <template #headerRight>
                    <div>
                        <el-button type="primary" @click="onBatchClick">{{ t('operation.batchconfirm') }}</el-button>
                        <el-button @click="emit('closed')">{{ t('operation.close') }}</el-button>
                    </div>
                </template>
                <!-- 操作 -->
                <template #operate="{ row }">
                    <el-button size="small" icon="Search" @click="showComponent('Details', row)" circle plain />
                </template>
                <template #footer>
                    <app-pagination :total="total" v-model:page-size="pageSize" v-model:page-index="pageIndex"
                        @change="run" />
                </template>
            </app-table>
            <component ref="componentRef" :is="componentMap.get(componentId)" v-bind="{ selectedItem }"
                @closed="closeComponent" v-if="componentId" />
        </app-view>
    </teleport>
</template>

<script lang="ts" setup>
import { shallowRef, PropType, defineAsyncComponent } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useEnum } from '@/hooks/enum'
import { useDataFilter } from '@/hooks/datatable-v2'
import { useComponent } from '@/hooks/component'
import { useRequest } from '@/hooks/request'
import { viewTradingDay, batchPay } from '@/services/api/settlement'
import { useUserStore } from '@/stores'
import AppTable from '@pc/components/base/table/index.vue'
import AppFilter from '@pc/components/base/table-filter-v2/index.vue'
import AppPagination from '@pc/components/base/pagination/index.vue'
import { i18n } from '@/stores'

const { global: { t } } = i18n

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

const roleTypeEnum = useEnum('roleType') // 分润机构角色
const ePayFlagEnum = useEnum('ePayFlag') // 支付状态

const componentMap = new Map<string, unknown>([
    ['Details', defineAsyncComponent(() => import('./details/index.vue'))], // 详情
])

const emit = defineEmits(['closed'])
const userStore = useUserStore()
const loading = shallowRef(false)
const selectedItem = shallowRef<Model.ViewTradingDayRsp>()
const selectedItems = shallowRef<Model.ViewTradingDayRsp[]>([])

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

const { dataList, total, pageSize, pageIndex, run } = useRequest(viewTradingDay, {
    params: {
        pageNum: 1,
        pageSize: 20,
        areatype: userStore.userInfo.releType === 1 ? undefined : 12,
        tradedate: props.record.tradedate
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

const tableColumns = shallowRef<Model.TableColumn[]>([
    { field: 'shareorgname', label: 'settlement.profitsharepay.details.shareorgname' },
    { field: 'areatype', label: 'settlement.profitsharepay.details.areatype', formatValue: (val) => roleTypeEnum.getEnumTypeName(val) },
    { field: 'totalcount', label: 'settlement.profitsharepay.details.totalcount' },
    { field: 'totalfee', label: 'settlement.profitsharepay.details.totalfee' },
    { field: 'divideamount', label: 'settlement.profitsharepay.details.divideamount' },
    { field: 'paystatus', label: 'settlement.profitsharepay.details.status', formatValue: (val) => ePayFlagEnum.getEnumTypeName(val) },
    { field: 'operate', label: 'common.operate', fixed: 'right' }
])

const { filterOption, getQueryParams, resetFilters } = useDataFilter<Model.ViewTradingDayReq>({
    filters: [
        {
            field: 'paystatus',
            label: t('settlement.profitsharepay.details.paystatus'),
            options: () => ePayFlagEnum.getEnumOptions()
        },
        {
            field: 'shareorgname',
            label: t('settlement.profitsharepay.details.shareorgname'),
        }
    ],
    buttons: [
        { label: t('operation.search'), className: 'el-button--primary', onClick: () => onSearch() },
        { label: t('operation.reset'), className: 'el-button--primary', onClick: () => resetFilters() }
    ]
})

const showComponent = (code: string, row?: Model.ViewTradingDayRsp) => {
    selectedItem.value = row
    openComponent(code)
}

const onSelect = (rows: Model.ViewTradingDayRsp[]) => {
    selectedItems.value = rows
}

const onSelectable = (row: Model.ViewTradingDayRsp, callback: (value: boolean) => boolean) => {
    row.paystatus === 1 ? callback(true) : callback(false)
}

const onSearch = () => {
    const qs = getQueryParams()
    run(qs)
}

// 批量确认
const onBatchClick = () => {
    if (selectedItems.value.length) {
        ElMessageBox({
            title: t('common.alert'),
            message: t('settlement.profitsharepay.details.tips2'),
            showCancelButton: true,
            beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                    instance.confirmButtonLoading = true
                    batchPay({
                        data: {
                            areaids: selectedItems.value.map((e) => e.areaid).join(','),
                            tradedate: props.record.tradedate
                        }
                    }).then((res) => {
                        ElMessage.warning(res.message)
                        onSearch()
                    }).catch((err) => {
                        ElMessage.error(t('common.tips22') + err)
                    }).finally(() => {
                        done()
                    })
                } else {
                    done()
                }
            }
        })
    } else {
        ElMessage.warning(t('settlement.profitsharepay.details.tips1'))
    }
}
</script>