<template>
    <ProDialog ref="proDialogRef" @handle-cancel="handleCancel" @handle-confirm="handleConfirm">
        <el-form ref="formRef" :rules="rules" :model="form" label-position="right" label-width="120">
            <el-form-item label="所属组织" prop="organizationId">
                <el-tree-select
                    v-model="form.organizationId"
                    :data="data"
                    :props="defaultProps"
                    :render-after-expand="false"
                    default-expand-all
                    style="width: 100%"
                />
            </el-form-item>
            <el-form-item label="账号名称" prop="username">
                <el-input v-model="form.username" autocomplete="off" placeholder="请输入" maxlength="20" show-word-limit />
            </el-form-item>
            <el-form-item label="联系电话" prop="mobile">
                <el-input v-model="form.mobile" autocomplete="off" placeholder="请输入" maxlength="11" show-word-limit />
            </el-form-item>
            <el-form-item label="岗位" prop="postIds">
                <el-checkbox-group v-model="form.postIds">
                    <el-checkbox v-for="option in positionOptions" :key="option.id" :label="option.id" name="type">
                        {{ option.name }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <template v-if="form.postIds.includes(5)">
                <el-form-item prop="dataFlow">
                    <template #label>
                        <div class="flex items-center gap-[6px] cursor-pointer">
                            <span>有效数据流向</span>
                            <el-tooltip effect="dark" placement="top">
                                <icon name="el-icon-QuestionFilled" />
                                <template #content>
                                    <div>电销有效数据流向：</div>
                                    <ul>
                                        <li v-for="(tooltip, index) in channelTooltips" :key="index" class="flex items-center gap-[4px]">
                                            <span class="w-[6px] h-[6px] bg-white rounded-[8px]"></span>
                                            {{ tooltip }}
                                        </li>
                                    </ul>
                                </template>
                            </el-tooltip>
                        </div>
                    </template>
                    <el-radio-group v-model="form.dataFlow">
                        <el-radio v-for="option in channelOptions" :key="option.value" :label="option.value">{{ option.label }}</el-radio>
                    </el-radio-group>
                    <template v-if="form.dataFlow == 1">
                        <el-select class="mt-[10px]" v-model="form.designatedTeacherId" placeholder="请选择指定招生老师">
                            <el-option v-for="item in recrutList" :key="item.id" :label="item.username" :value="item.id" />
                        </el-select>
                    </template>
                </el-form-item>
            </template>
            <el-form-item label="账号状态" prop="isDisable">
                <el-radio-group v-model="form.isDisable">
                    <el-radio v-for="option in accountStatusOptions" :key="option.value" :label="option.value">{{ option.label }}</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
    </ProDialog>
</template>

<script setup lang="ts">
import { organzationLists } from '@/api/account_center/organization'
import { postLists } from '@/api/account_center/postion'
import { subAccountAdd, subAccountDetail, subAccountEdit, subAccountList } from '@/api/account_center/sub_account'
import ProDialog, { type IParams } from '@/components/ProDialog/index.vue'
import { DataFlowEnum, isDisabledEnum } from '@/enums'
import { validateContact } from '@/utils/validate'
import type { FormInstance } from 'element-plus'

export interface IAccount {
    organizationId: number | string
    username: string
    mobile: string
    postId: number[]
    dataFlow: number
    isDisable: number
    teacher: string
}
const proDialogRef = ref<InstanceType<typeof ProDialog>>()

const emit = defineEmits(['confirmAfter'])
const data = ref([])
const defaultProps = {
    label: 'name', // 显示字段
    value: 'id', // 值字段
    children: 'children', // 子节点字段
    disabled: 'disabled'
}
const positionOptions = ref()
const channelOptions = ref([
    { label: '默认组织', value: DataFlowEnum.DEFAULT },
    { label: '组织指定', value: DataFlowEnum.SPECIFIC }
])
const accountStatusOptions = ref([
    { label: '启用', value: isDisabledEnum.NO },
    { label: '停用', value: isDisabledEnum.YES }
])
const channelTooltips = ['选择默认组织则数据流向到所属组织下的所有招生老师；', '选择组织指定则可选择将数据流向到所属组织下的指定招生老师；']
const form = ref({
    id: '',
    organizationId: '',
    username: '',
    mobile: '',
    postIds: [],
    dataFlow: 0,
    isDisable: 0,
    designatedTeacherId: ''
})
const fetchPostionData = async (callback?: (params: []) => void) => {
    try {
        const result = await postLists()
        positionOptions.value = result.lists
        callback && callback(result.lists)
    } catch (error) {}
}
const fetchOrganizationData = async (organizationId: number) => {
    try {
        const result = await organzationLists()
        setDsiabled(result)
        data.value = result
        const targetNode = findNodeById(data.value, organizationId)
        if (targetNode) {
            const { id, disabled } = targetNode
            form.value.organizationId = !disabled ? id : ''
        }
    } catch (error) {}
}
// 三级节点可选中，其余禁止选中
const setDsiabled = (nodes: any[]) => {
    nodes.forEach(node => {
        const ancestorArray = node.ancestors ? node.ancestors.split(',') : []
        const level = ancestorArray.length - 1
        node.disabled = level < 2 || node.isDisable == isDisabledEnum.YES
        if (node.children && node.children.length > 0) {
            setDsiabled(node.children)
        }
    })
}
const fetchDetail = async (data: any) => {
    const { id } = data
    try {
        const result = await subAccountDetail({ id })
        setFormData(result)
    } catch (error) {}
}
const setFormData = result => {
    for (const key in result) {
        if (Object.prototype.hasOwnProperty.call(form.value, key)) {
            form.value[key] = result[key]
        }
        if (key == 'postIds') {
            form.value.postIds = result[key].split(',').map((item: string) => Number(item))
        }
    }
}
// 根据组织id查找对应的节点
const findNodeById = (nodes: any[], id: number): any | undefined => {
    for (const node of nodes) {
        if (node.id === id) {
            return node
        }
        if (node.children && node.children.length > 0) {
            const foundNode = findNodeById(node.children, id)
            if (foundNode) {
                return foundNode
            }
        }
    }
    return undefined
}
const recrutList = ref<any[]>([])
const fetchRecrutList = async (organizationId: number) => {
    try {
        const params = {
            organizationId,
            postId: 5
        }
        const result = await subAccountList(params)
        recrutList.value = result ?? []
    } catch (error) {}
}
const openDialog = async (params: IParams) => {
    const { organizationId, id } = params.data
    fetchPostionData()
    fetchOrganizationData(organizationId)
    fetchRecrutList(organizationId)
    if (id) fetchDetail(params.data)
    proDialogRef.value?.openDialog(params)
}
const handleCancel = (callback: () => void) => {
    resetForm()
    callback()
}
const formRef = ref<FormInstance>()
const rules = reactive({
    organizationId: { required: true, message: '请选择所属组织', trigger: 'change' },
    username: { required: true, message: '请输入账号名称', trigger: 'change' },
    mobile: [
        { required: true, message: '请输入联系电话', trigger: 'change' },
        { validator: validateContact, trigger: 'change' }
    ],
    postIds: { required: true, message: '请选择岗位', trigger: 'change' }
})
const handleConfirm = (callback: () => void) => {
    formRef.value?.validate(async valid => {
        if (!valid) return
        try {
            const data = {
                ...form.value,
                postIds: form.value.postIds.join(',')
            }
            const api = form.value.id ? subAccountEdit : subAccountAdd
            await api(data)
            callback()
            emit('confirmAfter')
            resetForm()
        } catch (error) {}
    })
}
const resetForm = () => {
    formRef.value?.resetFields()
}
defineExpose({
    openDialog,
    fetchPostionData
})
</script>

<style scoped lang="scss"></style>
