<!-- 报表查询-机构资金报表 -->
<template>
    <app-view>
        <template #header>
            <app-filter :option="filterOption" :rules="filterRules">
                <template #reckondate="{ item }">
                    <el-form-item :label="item.label" prop="date">
                        <el-date-picker :type="dateType" v-model="dateValue" :format="dateFormat"
                            :value-format="dateFormat" :placeholder="t('common.pleasechoice')"
                            :start-placeholder="t('common.start')" :end-placeholder="t('common.end')" />
                    </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 #quarterend="{ item }">
                    <el-form-item :label="item.label" prop="quarterend"
                        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 #memberid="{ item }">
                    <el-form-item :label="item.label">
                        <app-select-member v-model="item.value" :params="{ usertype: '2' }" />
                    </el-form-item>
                </template>
                <template #inamount>
                    <el-form-item :label="t('report.investor.inamount')" prop="inamount">
                        <el-input-number v-model="queryParams.inamount" :min="0"
                            :placeholder="t('report.investor.tips1')" style="width: 240px;" />
                    </el-form-item>
                </template>
                <template #outamount>
                    <el-form-item :label="t('report.investor.outamount')" prop="outamount">
                        <el-input-number v-model="queryParams.outamount" :min="0"
                            :placeholder="t('report.investor.tips1')" style="width: 240px;" />
                    </el-form-item>
                </template>
                <template #roles>
                    <el-form-item :label="t('report.institution.roles')" prop="roles">
                        <el-checkbox-group v-model="roles">
                            <el-checkbox :label="t('report.institution.roles1')" value="2" />
                            <el-checkbox :label="t('report.institution.roles2')" value="7" />
                            <el-checkbox :label="t('report.institution.roles3')" value="9" />
                            <el-checkbox :label="t('report.institution.roles4')" value="4" />
                            <el-checkbox :label="t('report.institution.roles5')" value="13" />
                            <el-checkbox :label="t('report.institution.roles6')" value="3" />
                            <el-checkbox :label="t('report.institution.roles7')" value="8" />
                            <el-checkbox :label="t('report.institution.roles8')" value="6" />
                        </el-checkbox-group>
                    </el-form-item>
                </template>
            </app-filter>
        </template>
        <app-table :data="dataList" :columns="tableColumns" :loading="loading">
            <template #headerLeft>
                <app-operation :data-list="getActionButtons(['report_institution_export'])"
                    @click="openComponentOnClick" />
            </template>
            <template #footer>
                <app-pagination :total="total" v-model:page-size="pageSize" v-model:page-index="pageIndex"
                    @change="onSearch" />
            </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 { ref, shallowRef, computed } from 'vue'
import { ElMessage, FormRules } from 'element-plus'
import { useDataFilter } from '@/hooks/datatable-v2'
import { useEnum } from '@/hooks/enum'
import { useRequest } from '@/hooks/request'
import { useOperation } from '@/hooks/operation'
import { investorReportQuery } from '@/services/api/report'
import { getReportTypeList, ReportType, getQuarterList } from '@/constants/report'
import { i18n } from '@/stores'
import AppTable from '@pc/components/base/table/index.vue'
import AppPagination from '@pc/components/base/pagination/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 { global: { t } } = i18n
const accountstatusEnum = useEnum('accountstatus') // 机构状态
const dateValue = shallowRef()
const roles = ref<string[]>([])

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

const { dataList, total, pageSize, pageIndex, loading, run } = useRequest(investorReportQuery, {
    manual: true,
    params: {
        pageNum: 1,
        pageSize: 20,
        usertype: 2,
        flag: 2
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

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

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

const tableColumns = ref<Model.TableColumn[]>([
    { field: 'reckondate', label: 'report.institution.reckondate' },
    { field: 'accountid', label: 'report.institution.accountid' },
    { field: 'accountname', label: 'report.institution.accountname' },
    { field: 'balance', label: 'report.institution.balance' },
    { field: 'currentbalance', label: 'report.institution.currentbalance' },
    { field: 'inamount', label: 'report.institution.inamount' },
    { field: 'outamount', label: 'report.institution.outamount' },
    { field: 'closepl', label: 'report.institution.closepl' },
    { field: 'floatpl', label: 'report.institution.floatpl' },
    { field: 'reckonpl', label: 'report.institution.reckonpl' },
    { field: 'paycharge', label: 'report.institution.paycharge' },
    { field: 'interestCharge', label: 'report.institution.interestCharge' },
    { field: 'otherincome', label: 'report.institution.otherincome' },
    { field: 'usedmargin', label: 'report.institution.usedmargin' },
    { field: 'freezemargin', label: 'report.institution.freezemargin' },
    { field: 'outamountfreeze', label: 'report.institution.outamountfreeze' },
    { field: 'avaiablemoney', label: 'report.institution.avaiablemoney' },
    { field: 'avaiableoutmoney', label: 'report.institution.avaiableoutmoney' },
    { field: 'floatnetvalue', label: 'report.institution.floatnetvalues' },
])

// 表单验证规则
const filterRules: FormRules = {
    date: [{
        required: true,
        validator: () => !!dateValue.value?.length
    }]
}

const { queryParams, filterOption, getQueryParams, resetFilters } = useDataFilter<Model.InvestorReportReq>({
    filters: [
        {
            field: 'cycletype',
            label: t('report.institution.cycletype'),
            value: 0,
            options: () => getReportTypeList(),
            onChange: () => dateValue.value = []
        },
        {
            field: 'reckondate',
            label: t('report.investor.reckondate'),
            required: true
        },
        {
            field: 'quarter',
            label: t('report.institution.quarter'),
            required: true
        },
        {
            field: 'quarterend',
            label: t('report.institution.quarterend'),
            required: true
        },
        {
            field: 'memberid',
            label: t('report.institution.memberid')
        },
        {
            field: 'inamount',
            label: t('report.institution.inamount'),
            placeholder: t('report.institution.tips1')
        },
        {
            field: 'outamount',
            label: t('report.institution.outamount'),
            placeholder: t('report.institution.tips1')
        },
        {
            field: 'accountstatus',
            label: t('report.institution.accountstatus'),
            options: () => accountstatusEnum.getEnumOptions()
        },
        {
            field: 'roles',
            label: t('report.institution.roles'),
        }
    ],
    buttons: [
        { label: t('operation.search'), className: 'el-button--primary', onClick: () => onSearch() },
        { label: t('operation.reset'), className: 'el-button--primary', validateEvent: false, onClick: () => onReset() }
    ]
})

// 处理请求参数
const processRequiredParams = () => {
    const qs = getQueryParams()
    qs.roles = roles.value.join(',')

    if (Array.isArray(dateValue.value)) {
        const [startDate, endDate] = dateValue.value || []
        qs.reckondate = startDate
        qs.reckondateend = endDate
    } else {
        qs.reckondate = dateValue.value
        qs.reckondateend = dateValue.value
    }

    return qs
}

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


const onReset = () => {
    dateValue.value = []
    roles.value = []
    resetFilters()
}

const openComponentOnClick = (code: string) => {
    openComponent(code)
}
</script>