<!-- 会员机构管理-子机构管理-子机构管理 -->
<template>
    <div class="g-view-tree">
        <app-view>
            <el-tree ref=treeRef :data="treeList" node-key="userid" :expand-on-click-node="false"
                @node-click="nodeClick" default-expand-all highlight-current>
                <template #default="{ data }">
                    <span :style="{ color: data.accountstatus === 4 ? '' : 'red' }">
                        {{ `(${data.userid}) ${data.accountname}` }}
                    </span>
                </template>
            </el-tree>
        </app-view>
        <app-view>
            <app-operation :data-list="handleHeaderButtons()" @click="openComponent" v-if="selectedParent" />
            <app-table-details :data="selectedParent" :label-width="120" label-align="left" :cell-props="detailProps"
                :column="3" />
            <app-table :data="dataList" :columns="tableColumns">
                <!-- 操作 -->
                <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>
        </app-view>
        <component :is="componentMap.get(componentId)" v-bind="{ selectedParent, record }" @closed="closeComponent"
            v-if="componentId" />
    </div>
</template>

<script lang="ts" setup>
import { shallowRef, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { formatDate, buildTree } from '@/filters'
import { useEnum } from '@/hooks/enum'
import { useOperation } from '@/hooks/operation'
import { useRequest } from '@/hooks/request'
import { getAreaAndAllChilds, queryOrganSon } from '@/services/api/member'
import { CellProp } from '@pc/components/base/table-details/types'
import AppTable from '@pc/components/base/table/index.vue'
import AppTableDetails from '@pc/components/base/table-details/index.vue'
import AppOperation from '@pc/components/base/operation/index.vue'
import AppPagination from '@pc/components/base/pagination/index.vue'

const areastatusEnum = useEnum('areastatus') // 机构状态
const usertype2Enum = useEnum('usertype2') // 机构类型
const userinfotypeEnum = useEnum('userinfotype') // 所有者类型

const treeRef = shallowRef()
const selectedParent = shallowRef<Member.AreaAndAllChildsRsp>() // 已选中的树节点

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

const treeList = computed(() => {
    const [firstNode] = buildTree(nodeList.value, 'userid', 'parentuserid')
    return firstNode ? [firstNode] : []
})

const { dataList: nodeList, run: getNodeList } = useRequest(getAreaAndAllChilds, {
    onSuccess: (res) => {
        // 找出已选中的树节点
        const item = res.data.find((e) => e.userid === selectedParent.value?.userid)
        // 如果不存在默认取第一个节点
        selectedParent.value = item ?? res.data[0]

        const { memberuserid, userid } = selectedParent.value
        treeRef.value.setCurrentKey(userid, true)

        getOrganSonList({
            memberuserid,
            parentuserid: userid
        })
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

const { dataList, total, pageSize, pageIndex, run: getOrganSonList } = useRequest(queryOrganSon, {
    manual: true,
    params: {
        pageNum: 1,
        pageSize: 20
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

const detailProps: CellProp[] = [
    { prop: 'userid', label: 'member.subinstitution.manage.userid' },
    { prop: 'accountname', label: 'member.subinstitution.manage.accountname' },
    { prop: 'accountstatus', label: 'member.subinstitution.manage.accountstatus', formatValue: (val) => areastatusEnum.getEnumTypeName(val) },
    { prop: 'userinfotype', label: 'member.subinstitution.manage.userinfotype', formatValue: (val) => userinfotypeEnum.getEnumTypeName(val) },
    { prop: 'contactname', label: 'member.subinstitution.manage.contactname' },
    { prop: 'pathname', label: 'member.subinstitution.manage.pathname' },
]

const tableColumns = shallowRef<Model.TableColumn[]>([
    { field: 'userid', label: 'member.subinstitution.manage.userid1' },
    { field: 'accountname', label: 'member.subinstitution.manage.accountname1' },
    { field: 'accountstatus', label: 'member.subinstitution.manage.accountstatus1', formatValue: (val) => areastatusEnum.getEnumTypeName(val) },
    { field: 'usertype', label: 'member.subinstitution.manage.usertype', formatValue: (val) => usertype2Enum.getEnumTypeName(val) },
    { field: 'userinfotype', label: 'member.subinstitution.manage.userinfotype1', formatValue: (val) => userinfotypeEnum.getEnumTypeName(val) },
    { field: 'userName', label: 'member.subinstitution.manage.userName' },
    { field: 'modifytime', label: 'member.subinstitution.manage.modifytime', formatValue: (val) => formatDate(val) },
    { field: 'operate', label: 'common.operate', width: 140, fixed: 'right' }
])

// 处理操作按钮
const handleHeaderButtons = () => {
    const { accountstatus, usertype, maxLevel = 0, subarealevelpath = '', cancrossadd, curuserid, userid } = selectedParent.value ?? {}
    const max = maxLevel - 1
    const level = subarealevelpath.split(',').length - 3
    const buttons = ['member_subinstitution_manage_details']

    if (accountstatus === 4 && usertype !== 4 && max > level) {
        if (curuserid === userid || cancrossadd !== 0) {
            buttons.push('member_subinstitution_manage_add')
        }
    }

    return getActionButtons(buttons)
}

// 处理操作按钮
const handleOperateButtons = (row: Member.OrganSonRsp) => {
    const buttons = ['member_subinstitution_manage_details']
    switch (row.modifystatus) {
        case 0:
        case 1:
            if (row.accountstatus === 6) {
                buttons.push('member_subinstitution_manage_recover')
            } else {
                buttons.push('member_subinstitution_manage_modify')
                if (![2, 3].includes(row.accountstatus)) {
                    buttons.push('member_subinstitution_manage_close')
                }
            }
            break
        case 3:
        case 4:
            buttons.push('member_subinstitution_manage_cancel')
            break
        default:
            buttons.push('member_subinstitution_manage_modify')
    }
    return getActionButtons(buttons)
}

const onSearch = (clear = false) => {
    const { memberuserid, userid } = selectedParent.value ?? {}
    if (clear) {
        pageIndex.value = 1
    }
    getOrganSonList({
        memberuserid,
        parentuserid: userid
    })
}

const nodeClick = (data: Member.AreaAndAllChildsRsp) => {
    selectedParent.value = data
    onSearch(true)
}
</script>