<!-- 会员机构管理-机构管理-机构资料管理 -->
<template>
    <app-view>
        <template #header>
            <app-filter :option="filterOption">
                <template #starttime="{ item }">
                    <el-form-item :label="item.label" prop="date">
                        <el-date-picker type="daterange" v-model="dateValue" value-format="YYYYMMDD"
                            :start-placeholder="t('member.institution.user.startdate')"
                            :end-placeholder="t('member.institution.user.enddate')" />
                    </el-form-item>
                </template>
            </app-filter>
        </template>
        <app-table :data="dataList" :columns="tableColumns" :loading="loading">
            <!-- 操作 -->
            <template #operate="{ row }">
                <app-operation size="small" :data-list="handleOperateButtons(row)"
                    @click="(code: string) => openComponent(code, row)" circle />
            </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 }" @closed="closeComponent"
            v-if="componentId" />
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef } from 'vue'
import { ElMessage } from 'element-plus'
import { formatDate } from '@/filters'
import { useDataFilter } from '@/hooks/datatable-v2'
import { useRequest } from '@/hooks/request'
import { useMarket } from '@/hooks/market'
import { useOperation } from '@/hooks/operation'
import { useEnum } from '@/hooks/enum'
import { queryOrganDetailList } from '@/services/api/member'
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'

const { getMarketOptions } = useMarket()
const areastatusEnum = useEnum('areastatus') // 机构状态
const roleTypeEnum = useEnum('roleType') // 机构角色

const { global: { t } } = i18n
const dateValue = shallowRef<string[] | null>([])

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

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

const tableColumns = shallowRef<Model.TableColumn[]>([
    { field: 'userid', label: 'member.institution.user.userid' },
    { field: 'accountname', label: 'member.institution.user.accountname' },
    { field: 'accountstatus', label: 'member.institution.user.accountstatus', formatValue: (val) => areastatusEnum.getEnumTypeName(val) },
    {
        field: 'roleIds',
        label: 'member.institution.user.roleIds',
        formatValue: (val: string) => {
            if (val) {
                const arr = val.split(',').map((id) => roleTypeEnum.getEnumTypeName(Number(id)))
                return arr.join(',')
            }
            return val
        }
    },
    { field: 'userName', label: 'member.institution.user.userName' },
    { field: 'createtime', label: 'member.institution.user.createtime', formatValue: (val) => formatDate(val) },
    { field: 'modifytime', label: 'member.institution.user.modifytime', formatValue: (val) => formatDate(val) },
    { field: 'operate', label: 'common.operate', width: 200, fixed: 'right' }
])

const { filterOption, getQueryParams, resetFilters } = useDataFilter<Member.OrganDetailListReq>({
    filters: [
        {
            field: 'accountName',
            label: t('member.institution.user.accountname')
        },
        {
            field: 'accountStatus',
            label: t('member.institution.user.accountstatus'),
            options: () => areastatusEnum.getEnumOptions()
        },
        {
            field: 'markets',
            label: t('member.institution.user.markets'),
            options: () => getMarketOptions()
        },
        {
            field: 'starttime',
            label: t('member.institution.user.starttime'),
        },
        {
            field: 'roles',
            label: t('member.institution.user.roles'),
            multiple: true,
            options: () => roleTypeEnum.getEnumOptions()
        },
    ],
    buttons: [
        { label: t('operation.search'), className: 'el-button--primary', onClick: () => onSearch() },
        { label: t('operation.reset'), className: 'el-button--primary', validateEvent: false, onClick: () => onReset() }
    ]
})

// 处理操作按钮
const handleOperateButtons = (row: Member.OrganDetailListRsp) => {
    const buttons = ['member_institution_user_details', 'member_institution_user_account', 'member_institution_user_login']

    if (row.accountstatus === 6) {
        buttons.push('member_institution_user_recover')
    } else {
        buttons.push('member_institution_user_modify')
        if (!row.roleIds) {
            buttons.push('member_institution_user_close')
        }
    }

    if (row.roleIds?.split(',').includes('6')) {
        buttons.push('member_institution_user_terminal')
    }

    return getActionButtons(buttons)
}

const onSearch = () => {
    const qs = getQueryParams()
    const [startDate, endDate] = dateValue.value || []
    qs.starttime = startDate
    qs.endtime = endDate

    if (Array.isArray(qs.roles)) {
        qs.roles = qs.roles.join(',')
    }

    run(qs)
}

const onReset = () => {
    dateValue.value = []
    resetFilters()
}
</script>