<template>
    <div class="flex flex-col flex-1">
        <template v-if="showEmptyComponent">
            <empty-content @handle-organization="handleOrganization" />
        </template>
        <template v-else>
            <div class="h-[50px] flex items-center border-b-solid-light2 px-[20px] text-[20px] font-bold">
                {{ curOrganization.name }}
            </div>
            <div class="px-[20px] py-[16px] flex justify-between">
                <el-space>
                    <el-button type="primary" :icon="Plus" :disabled="isDisabledAdd" @click="showAccountDialog">新建账号</el-button>
                    <el-button type="danger" plain :icon="Delete" :disabled="isDisabled" @click="handleBatchDelete">批量删除</el-button>
                </el-space>
                <el-space>
                    <el-input :placeholder="`请输入${placeholder}`" v-model="searchForm.keyword" clearable @input="handleInputChange">
                        <template #prepend>
                            <el-select v-model="selectKey" :placeholder="placeholder" class="w-[100px]">
                                <el-option v-for="option in searchOptions" :key="option.field" :label="option.label" :value="option.field" />
                            </el-select>
                        </template>
                    </el-input>
                    <el-select placeholder="请选择岗位名称" v-model="searchForm.postId" clearable @change="handleSelectChange">
                        <el-option v-for="option in positionOptions" :key="option.id" :label="option.name" :value="option.id" />
                    </el-select>
                    <el-select placeholder="请选择账号状态" v-model="searchForm.isDisable" clearable @change="handleSelectChange">
                        <el-option v-for="option in accountStatusOptions" :key="option.value" :label="option.label" :value="option.value" />
                    </el-select>
                </el-space>
            </div>
            <ProTable ref="proTableRef" :columns="columns" :tableData="tableData" :loading="loading" :maxHeight="530">
                <template #username="{ row }">
                    <el-space>
                        <div class="w-[50px] h-[50px] bg-primary rounded-[6px] text-white flex-row-center-center">{{ row.username }}</div>
                        <span>{{ row.username }}</span>
                        <span
                            v-if="isGroupLeader(row.groupLeader)"
                            class="px-[6px] text-green border border-solid border-green rounded-[4px] text-center text-xs"
                        >
                            组长
                        </span>
                    </el-space>
                </template>
                <template #isDisable="{ row }">
                    <el-switch
                        v-model="row.isDisable"
                        :active-value="isDisabledEnum.NO"
                        :inactive-value="isDisabledEnum.YES"
                        :before-change="() => handleStatusChange(row)"
                    />
                </template>
                <template #operation="{ row }">
                    <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
                    <el-button link type="primary" @click="setGroupLeader(row)">{{ btnText(row.groupLeader) }}</el-button>
                    <el-button link type="primary" @click="handleDelete(row)">删除</el-button>
                </template>
            </ProTable>
            <div class="flex justify-end bg-white mt-[20px]">
                <pagination v-model="pager" @change="fetchTableList" />
            </div>
        </template>
    </div>
    <account-dialog ref="accountDialogRef" @confirm-after="confirmAfter" />
    <edit-popup v-if="showEdit" ref="editRef" @success="fetchOrganizationList" @close="showEdit = false" />
</template>

<script setup lang="ts">
import useHandleData from '@/hooks/useHandleData'
import feedback from '@/utils/feedback'
import { Plus, Delete } from '@element-plus/icons-vue'
import accountDialog from '../components/account-list/account-dialog.vue'
import emptyContent from '../components/account-list/empty-content.vue'
import editPopup from '@/views/account_center/organization/edit.vue'

import { useDebounceFn } from '@vueuse/core'
import { subAccountDelete, subAccountEdit, subAccountList, subAccountUpdateStatus } from '@/api/account_center/sub_account'
import { StatusEnum, groupLeaderEnum, isDisabledEnum } from '@/enums'
import { omit } from 'lodash-es'

const props = defineProps({
    curOrganization: {
        type: Object,
        default: () => ({})
    }
})
const emit = defineEmits(['refreshSubAccountNumber', 'fetchOrganizationList'])

const pager = ref({
    page: 1,
    size: 10,
    count: 0
})
const selectKey = ref('username')
const searchOptions = shallowRef([
    { field: 'username', label: '账号名称' },
    { field: 'mobile', label: '联系电话' }
])
const placeholder = computed(() => searchOptions.value.find(item => item.field == selectKey.value)?.label)
const accountStatusOptions = ref([
    { label: '启用', value: isDisabledEnum.NO },
    { label: '停用', value: isDisabledEnum.YES }
])
const loading = ref(false)
const proTableRef = ref()
const tableData = ref<any[]>([])
const columns = reactive([
    { type: 'selection', fixed: 'left', width: 70, reserveSelection: true },
    { prop: 'username', label: '账号名称', width: 180 },
    { prop: 'mobile', label: '联系电话', width: 180 },
    { prop: 'organizationName', label: '所属组织', width: 180 },
    { prop: 'postName', label: '岗位', width: 180 },
    { prop: 'isDisable', label: '账号状态', width: 180 },
    { prop: 'operation', label: '操作', fixed: 'right', width: 250 }
])

const isGroupLeader = computed(() => (groupLeader: number) => groupLeader === groupLeaderEnum.YES)
const btnText = computed(() => (groupLeader: number) => isGroupLeader.value(groupLeader) ? '取消设为组长' : '设置组长')
const isDisabledAdd = computed(() => props.curOrganization.status == StatusEnum.Stop)
const showEmptyComponent = computed(() => {
    const { ancestors } = props.curOrganization
    const ancestorArray = ancestors ? ancestors.split(',') : []
    const level = ancestorArray.length - 1
    return level < 2 && !props.curOrganization?.children
})
const fetchTableList = async (nodeId?: number) => {
    console.log('fetchTableList')

    loading.value = true
    tableData.value = []
    try {
        const newParams = omit(searchForm.value, ['keyword'])
        const params = {
            organizationId: nodeId ?? props.curOrganization.id,
            ...newParams
        }
        const result = await subAccountList(params)
        tableData.value = result ?? []
    } catch (error) {}
    loading.value = false
}
const handleStatusChange = row => {
    console.log(row)
    const { id, isDisable } = row
    return new Promise(async resolve => {
        try {
            const params = {
                id,
                isDisable: isDisable == isDisabledEnum.YES ? isDisabledEnum.NO : isDisabledEnum.YES
            }
            const msg = isDisable == isDisabledEnum.YES ? '启用' : '停用'
            await feedback.confirm(`确定${msg}该账号?`)
            await subAccountUpdateStatus(params)
            feedback.msgSuccess(`${msg}成功`)
            resolve(true)
            fetchTableList()
        } catch (error) {}
    })
}
// 设置组长
const setGroupLeader = async row => {
    const { username, id, groupLeader } = row
    const message = isGroupLeader.value(groupLeader) ? `确定要取消【${username}】的组长身份吗?` : `确定将【${username}】设置为组长?`
    const flag = await useHandleData(message)
    if (!flag) return
    try {
        const params = {
            id,
            groupLeader: isGroupLeader.value(groupLeader) ? groupLeaderEnum.NO : groupLeaderEnum.YES
        }
        await subAccountEdit(params)
        feedback.msgSuccess('设置成功')
        fetchTableList()
    } catch (error) {}
}
const isDisabled = computed(() => proTableRef?.value?.selectedListIds?.length == 0)
const handleBatchDelete = () => {
    deleteCommon()
}
const handleDelete = async row => {
    deleteCommon(row)
}
const deleteCommon = async (row?: any) => {
    if (row) proTableRef.value.tableRef.toggleRowSelection(row, true)
    const ids = proTableRef.value.selectedListIds
    const message = '是否要删除选中的账号?'
    const flag = await useHandleData(message)
    if (flag) {
        try {
            await subAccountDelete({ ids })
            feedback.msgSuccess('删除成功')
            fetchTableList()
            emit('refreshSubAccountNumber')
        } catch (error) {}
    }
    proTableRef.value.tableRef.clearSelection()
}
const confirmAfter = () => {
    fetchTableList()
    emit('refreshSubAccountNumber')
}
const handleEdit = row => {
    showAccountDialog(row)
}
defineExpose({
    fetchTableList
})
const accountDialogRef = ref<InstanceType<typeof accountDialog>>()
const showAccountDialog = (row?: any) => {
    accountDialogRef.value?.openDialog({
        title: row?.id ? '编辑账号' : '新建账号',
        width: 400,
        data: {
            id: row?.id ?? '',
            organizationId: props.curOrganization.id
        }
    })
}
const searchForm = ref({
    keyword: '',
    postId: '',
    isDisable: '',
    username: '',
    mobile: ''
})
const handleInputChange = useDebounceFn(() => {
    const formMap: Record<string, string> = {
        username: '',
        mobile: ''
    }
    formMap[selectKey.value] = searchForm.value.keyword
    searchForm.value[selectKey.value] = formMap[selectKey.value]
    fetchTableList()
}, 500)
const handleSelectChange = () => {
    fetchTableList()
}
const showEdit = ref(false)
const editRef = ref<InstanceType<typeof editPopup>>()
const handleOrganization = async (mode: 'add' | 'edit') => {
    const { id } = props.curOrganization
    showEdit.value = true
    await nextTick()
    if (id) editRef.value?.setFormData({ pid: id })
    editRef.value?.open(mode)
}
const fetchOrganizationList = () => {
    emit('fetchOrganizationList', props.curOrganization)
}
const positionOptions = ref<any[]>([])

onMounted(() => {
    accountDialogRef.value?.fetchPostionData(lists => {
        positionOptions.value = lists ?? []
    })
})
watch(
    () => selectKey.value,
    (newVal, oldVal) => {
        if (newVal != oldVal && searchForm.value.keyword !== '') {
            searchForm.value.keyword = ''
        }
    }
)
</script>
<style scoped></style>
