<template>
    <el-dialog v-model="show" width="1100" align-center class="structure-dialog" >
        <div style="height: 600px;" v-htfx-loading="loading" >
            <div style="position: relative;">
                <el-input v-model="searchParams.str" clearable style="width: 400px;margin-right: 20px;" />
                <el-button type="primary" @click="toStructureData" >{{ t('form.search') }}</el-button>
                <el-button v-if="userList" @click="userList = null" >{{ t('form.collapse') }}</el-button>
                <div style="position: absolute;left: 0;top: 40px;width: 1000px;height: 500px;" v-if="userList">
                    <el-table-v2 :columns="[{key: 'content', dataKey: 'content'}]" :data="userList" :width="1000" :height="500" :header-height="0" :row-event-handlers="handleRow" >
                        <template #row="{ rowData }" >
                            <div v-html="rowData.content"></div>
                        </template>
                    </el-table-v2>
                </div>
            </div>
            <div style="overflow-x: auto;" ref="pannelRef" v-show="!userList">
                <el-cascader-panel ref="selectRef" style="width: fit-content;height: 540px;margin-top: 20px;" :options="options" :props="cascaderProps" v-model="qcc" >
                    <template #default="{ node, data }" >
                        <div class="user-node" :class="{'user-node-active': (selected_value && selected_value.id == data.id && selected_value.level == data.level) 
                        || (selected_value && selected_value.pid && selected_value.pid.length > data.level && selected_value.pid[data.level] == data.id) }" @click="handleChange(data)" >
                            <img v-if="data.icon" class="node-icon" :src="data.icon" />
                            <div class="node-label" >{{ data.label }}</div>
                            <el-icon v-if="!data.leaf" style="margin-left: auto;margin-right: 8px;"><ArrowRight /></el-icon>
                        </div>
                    </template>
                </el-cascader-panel>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="ok">
                    {{ t('common.okText') }}
                </el-button>
                <el-button class="dark-btn" @click="clean">{{ t('common.cleanText') }}</el-button>
                <el-button @click="show = false;searchParams.str = undefined;userList = null;">{{ t('common.cancelText') }}</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import useUserStore from '@/store/modules/user'
import { useLocale } from 'element-plus'
import { serverLang } from '@/utils/i18n'
import { defineModel, ref, watch } from 'vue'
import { 
    getStructureUserByFuzzy,
    getStructureUserSuperior,
    getSubToTreeByIbId,
    getSubToTreeBySalesman,
    getSalesmanToTree,
    getOrgToTree
} from '@/api/structure'
import { isEmpty, getBlank } from '@/utils/htfx'

const userStore = useUserStore()
const { t } = useLocale()
const show = defineModel("show")
const structureValue = defineModel("structureValue")
const structureType = defineModel("structureType")
const userInfo = ref(userStore.userInfo)

const pannelRef = ref()
const selectRef = ref()
const selected_value = ref(null)
const qcc = ref([])
let qcc_tmp = []
const userList = ref(null)

const icon1 = new URL('@/assets/images/icon-user-type-1.png', import.meta.url).href
const icon2 = new URL('@/assets/images/icon-user-type-2.png', import.meta.url).href
const icon3 = new URL('@/assets/images/icon-directly-under.png', import.meta.url).href
const icon4 = new URL('@/assets/images/icon-structure.png', import.meta.url).href

const emit = defineEmits(['ok', 'clean'])

const loading = ref(false)

const props = defineProps({
    pageDataPower: {
        type: Number,
        default: null
    },
    pageId: {
        type: String
    }
})

const searchParams = ref({
    str: undefined,
    qcc_page_id: props.pageId
})

async function toStructureData() {
    loading.value = true
    const resp = await getStructureUserByFuzzy(searchParams.value)
    loading.value = false
    let tmp = []
    if (resp.data) {
        tmp = resp.data.filter(v => v.id != userInfo.value.id).map(i => {
            let email = '';
            if(!isEmpty(i.email)) email = '<span class="font-11 float-right">('+getBlank(i.email)+')</span>';
            return {
                content: i.name + getStructureUserTypeHtml(i.user_type) + email,
                id: i.id
            }
        })
    }
    userList.value = tmp
}

function getStructureUserTypeHtml(value) {
    if(isEmpty(value)) return '';
    if(value==0 || value=='0'){
        return '<span class="ui-badge font-10" style="background-color: #556ee6;color: #fff;border-radius: 3px;margin: 0 10px;padding: 1px 5px;">'+t('common.emp')+'</span>'
    }else if(value==1 || value=='1'){
        return '<span class="ui-badge font-10" style="background-color: #34c38f;color: #fff;border-radius: 3px;margin: 0 10px;padding: 1px 5px;">'+t('common.ib')+'</span>'
    }else if(value==2 || value=='2'){
        return '<span class="ui-badge font-10" style="background-color: #f1b44c;color: #fff;border-radius: 3px;margin: 0 10px;padding: 1px 5px;">'+t('common.customer')+'</span>'
    }else{
        return '';
    }
}

const options = ref([])

const cascaderProps = {
    lazy: true,
    lazyLoad: (node, resolve) => {
        if (node.data.type === 'sub') {
            return clickSubStructure(node, resolve)
        } else if (node.data.type === 'org') {
            return clickOrgStructure(node, resolve)
        } else if (node.data.type === 'sales') {
            return clickSalesmanStructure(node, resolve)
        } else {
            resolve()
        }
    },
    checkStrictly: true,
    value: 'key'
}

function getSysStructureJsonData() {
    if (selected_value.value) {
        const { type, id, pid, level } = selected_value.value
        if (type == 'sub') {
            if (id == 'directly_under') {
                if (props.pageDataPower >= 2) {
                    if (pid.length) {
                        structureValue.value = pid.slice(-1)[0]
                    } else {
                        structureValue.value = 'login_user_id'
                    }
                } else {
                    structureValue.value = pid.slice(-1)[0]
                }
                structureType.value = 'directly_under'
            } else if (id == 'down_line') {
                if (props.pageDataPower >= 2) {
                    if (pid.length) {
                        structureValue.value = pid.slice(-1)[0]
                    } else {
                        structureValue.value = 'login_user_id'
                    }
                } else {
                    structureValue.value = pid.slice(-1)[0]
                }
                structureType.value = 'down_line'
            } else {
                structureValue.value = id
                structureType.value = 'ic_id'
            }
        } else if (type == 'sales') {
            structureValue.value = id
            structureType.value = 'salesman_id'
        } else if (type == 'org') {
            structureValue.value = id
            structureType.value = 'org_id'
        }
    } else {
        structureType.value = ''
        structureValue.value = ''
    }
}

function clean() {
    options.value = []
    selected_value.value = null
    qcc.value = null
    qcc_tmp = []
    searchParams.value.str = undefined;
    userList.value = null;
    selectRef.value.clearCheckedNodes()
    getSysStructureJsonData()
    show.value = false
    emit('clean')
}

function ok() {
    getSysStructureJsonData()
    show.value = false
    searchParams.value.str = undefined;
    userList.value = null;
    emit('ok')
}

function loadData() {
    loading.value = true
    if (userInfo.value.user_type > 0 && props.pageDataPower >= 2) {
        if (props.pageDataPower == 2) {
            getSubToTreeByIbId({
                qcc_page_id: props.pageId,
                qcc_language: serverLang(),
                superior_id: 'login_user_id'
            }).then(resp => {
                let tmp = []
                if (resp.data && resp.data.length) {
                    tmp.push({
                        label: t('structure.down_line'),
                        id: 'down_line',
                        icon: icon4,
                        leaf: true,
                        type: 'sub',
                        level: 0,
                        pid: [],
                        key: '0__down_line',
                        value: {
                            id: 'down_line',
                            type: 'sub',
                            level: 0,
                            pid: [],
                            key: '0__down_line',
                        }
                    })
                    tmp.push({
                        label: t('structure.directly_under'),
                        id: 'directly_under',
                        icon: icon3,
                        leaf: true,
                        type: 'sub',
                        level: 0,
                        pid: [],
                        key: '0__directly_under',
                        value: {
                            id: 'directly_under',
                            type: 'sub',
                            level: 0,
                            pid: [],
                            key: '0__directly_under'
                        }
                    })
                    for (let index = 0; index < resp.data.length; index++) {
                        const row = resp.data[index];
                        let label, id, leaf, icon, sub_num, type, level;
                        level = 0
                        type = 'sub'
                        leaf = !row.sub_num > 0
                        id = row.id
                        sub_num = row.sub_num
                        label = row.name
                        icon = row.user_type == 1 ? icon1 : icon2
                        let item = {
                            label, id, sub_num, leaf, icon, type, level, pid: [], value: {
                                id, type, level, pid: []
                            }
                        }
                        item.key = item.level + '__' + item.id
                        tmp.push(item)
                    }
                }
                options.value = tmp
                loading.value = false
            })
        } else if (props.pageDataPower == 3) {
            getSubToTreeByIbId({
                qcc_page_id: props.pageId,
                qcc_language: serverLang(),
                superior_id: 'login_user_id'
            }).then(resp => {
                let tmp = []
                if (resp.data && resp.data.length) {
                    tmp.push({
                        label: t('structure.directly_under'),
                        value: 'directly_under',
                        icon: icon3,
                        leaf: true,
                        type: 'sub',
                        level: 0,
                        pid: [],
                        key: '0__directly_under',
                        value: {
                            id: 'directly_under',
                            type: 'sub',
                            level: 0,
                            pid: [],
                            key: '0__directly_under',
                        }
                    })
                    for (let index = 0; index < resp.data.length; index++) {
                        const row = resp.data[index];
                        let label, value, leaf, icon, sub_num, type, level;
                        level = 0
                        type = 'sub'
                        leaf = true
                        value = row.id
                        sub_num = row.sub_num
                        label = row.name
                        icon = row.user_type == 1 ? icon1 : icon2
                        let item = {
                            label, value, sub_num, leaf, icon, type, level, pid: [], value: {
                                id, type, level, pid: []
                            }
                        }
                        item.key = item.level + '__' + item.id
                        tmp.push(item)
                    }
                }
                options.value = tmp
                loading.value = false
            })
        } else if (props.pageDataPower == 4) {
            options.value = []
            loading.value = false
        }
    } else {
        getOrgToTree({
            qcc_page_id: props.pageId,
            qcc_language: serverLang()
        }).then(resp => {
            let tmp = []
            if (resp.data && resp.data.length) {
                for (let index = 0; index < resp.data.length; index++) {
                    const row = resp.data[index];
                    let label, id, leaf, icon, sub_num, type, level;
                    level = 0
                    type = 'org'
                    leaf = !row.sub_num > 0
                    id = row.id
                    sub_num = row.sub_num
                    label = row.org_name
                    icon = false
                    let item = {
                        label, id, sub_num, leaf, icon, type, level, pid: [], value: {
                            id, type, level, pid: []
                        }
                    }
                    item.key = item.level + '__' + item.id
                    tmp.push(item)
                }
            }
            options.value = tmp
            loading.value = false
        })
    }
}

function clickSubStructure(node, resolve) {
    loading.value = true
    const { id, level, pid } = node.data
    getSubToTreeByIbId({
        qcc_page_id: props.pageId,
        qcc_language: serverLang(),
        superior_id: id
    }).then(resp => {
        let tmp = []
        if (resp.data && resp.data.length) {
            tmp.push({
                label: t('structure.down_line'),
                id: 'down_line',
                icon: icon4,
                leaf: true,
                type: 'sub',
                level: level + 1,
                pid: [...pid, id],
                key: level+1+'__down_line',
                value: {
                    id: 'down_line',
                    type: 'sub',
                    level: level + 1,
                    pid: [...pid, id]
                }
            })
            tmp.push({
                label: t('structure.directly_under'),
                id: 'directly_under',
                icon: icon3,
                leaf: true,
                type: 'sub',
                level: level + 1,
                pid: [...pid, id],
                key: level+1+'__directly_under',
                value: {
                    id: 'directly_under',
                    type: 'sub',
                    level: level + 1,
                    pid: [...pid, id]
                }
            })
            for (let index = 0; index < resp.data.length; index++) {
                const row = resp.data[index];
                let label, leaf, icon, sub_num, type;
                type = 'sub'
                leaf = !row.sub_num > 0
                sub_num = row.sub_num
                label = row.name
                icon = row.user_type == 1 ? icon1 : icon2
                let item = {
                    label, id: row.id, sub_num, leaf, icon, type, level: level + 1, pid: [...pid, id], value: {
                        id: row.id, type, level: level + 1, pid: [...pid, id]
                    }
                }
                item.key = item.level + '__' + item.id
                tmp.push(item)
            }
        }
        loading.value = false
        resolve(tmp)
    })
}

function clickOrgStructure(node, resolve) {
    loading.value = true
    const { id, level, pid } = node.data
    getSalesmanToTree({
        org_id: id,
        qcc_page_id: props.pageId,
        qcc_language: serverLang()
    }).then(resp => {
        let tmp = []
        if (resp.data && resp.data.length) {
            for (let index = 0; index < resp.data.length; index++) {
                const row = resp.data[index];
                let label, leaf, icon, sub_num, type;
                type = 'sales'
                leaf = !row.sub_num > 0
                sub_num = row.sub_num
                label = row.name
                icon = false
                let item = {
                    label, id: row.id, sub_num, leaf, icon, type, level: level + 1, pid: [...pid, id], value: {
                        id: row.id, type, level: level + 1, pid: [...pid, id]
                    }
                }
                item.key = item.level + '__' + item.id
                tmp.push(item)
            }
        }
        loading.value = false
        resolve(tmp)
    })
}

function clickSalesmanStructure(node, resolve) {
    loading.value = true
    const { id, level, pid } = node.data
    getSubToTreeBySalesman({
        salesman_id: id,
        qcc_page_id: props.pageId,
        qcc_language: serverLang()
    }).then(resp => {
        let tmp = []
        if (resp.data && resp.data.length) {
            for (let index = 0; index < resp.data.length; index++) {
                const row = resp.data[index];
                let label, leaf, icon, sub_num, type;
                type = 'sub'
                leaf = !row.sub_num > 0
                sub_num = row.sub_num
                label = row.name
                icon = row.user_type == 1 ? icon1 : icon2
                let item = {
                    label, id: row.id, sub_num, leaf, icon, type, level: level + 1, pid: [...pid, id], value: {
                        id: row.id, type, level: level + 1, pid: [...pid, id]
                    }
                }
                item.key = item.level + '__' + item.id
                tmp.push(item)
            }
        }
        loading.value = false
        resolve(tmp)
    })
}

watch( [() => props.pageId, show], (n, o) => {
    if (n[0]) {
        loadData()
    }
}, {
    immediate: true
    // deep: true
})

function handleChange(data) {
    selected_value.value = data
}

const handleRow = {
    async onClick(e) {
        const { rowKey } = e
        selected_value.value = null
        qcc.value = null
        qcc_tmp = []
        searchParams.value.str = undefined;
        userList.value = null;
        selectRef.value.clearCheckedNodes()
        const list = await clickStructureFuzzyUser(rowKey)
        let type = 'sub'
        let pid = []
        let level = list.length
        if (props.pageDataPower < 2) {
            if (list[0].user_type == 0) {
                type = 'sales'
            }
            pid.push(list[0].org_id)
            for (let index = list.length - 1; index >= 0; index--) {
                const element = list[index];
                pid.push(element.id)
            }
        } else {
            for (let index = list.length - 3; index >= 0; index--) {
                const element = list[index];
                pid.push(element.id)
            }
        }
        qcc.value = qcc_tmp.reverse()
        let sv = {
            type,
            id: list[0].id,
            pid,
            level
        }
        selected_value.value = sv
    }
}

async function clickStructureFuzzyUser(id) {
    loading.value = true
    userList.value = null
    let optionsList = []
    const resp = await getStructureUserSuperior({ id: id })
    if (resp.data && resp.data.length) {
        if (props.pageDataPower < 2) {
            optionsList = await getOrgList(resp.data)
        } else {
            const v = resp.data.slice(-2, -1)[0]
            let item = {
                label: v.name, id: v.id, sub_num: resp.data.length, leaf: resp.data.length > 0, type: 'sub', level: 0, pid: [], value: {
                    id: v.id, type: 'sub', level: 0, pid: []
                }
            }
            item.key = item.level + '__' + item.id
            optionsList = await getSubList2(item, resp.data, resp.data.length - 3)
        }
    }
    loading.value = false
    options.value = optionsList
    return resp.data;
}

async function getOrgList(list) {
    let i = list.length - 1
    let tmp = []
    const resp = await getOrgToTree({
        qcc_page_id: props.pageId,
        qcc_language: serverLang()
    })
    if (resp.data && resp.data.length) {
        for (let index = 0; index < resp.data.length; index++) {
            const row = resp.data[index];
            let label, id, leaf, icon, sub_num, type, level;
            level = 0
            type = 'org'
            leaf = !row.sub_num > 0
            id = row.id
            sub_num = row.sub_num
            label = row.org_name
            icon = false
            let item = {
                label, id, sub_num, leaf, icon, type, level, pid: [], value: {
                    id, type, level, pid: []
                }
            }
            item.key = item.level + '__' + item.id
            if (!leaf && list[i].org_id == item.id) {
                item.children = await getSalesList(item, list, i)
                qcc_tmp.push(item.key)
            }
            tmp.push(item)
        }
    }
    return tmp;
}

async function getSalesList(data, list, i) {
    let tmp = []
    if (i < 0) {
        return tmp;
    }
    const { id, level, pid } = data
    const resp = await getSalesmanToTree({
        org_id: id,
        qcc_page_id: props.pageId,
        qcc_language: serverLang()
    })
    if (resp.data && resp.data.length) {
        for (let index = 0; index < resp.data.length; index++) {
            const row = resp.data[index];
            let label, leaf, icon, sub_num, type;
            type = 'sales'
            leaf = !row.sub_num > 0
            sub_num = row.sub_num
            label = row.name
            icon = false
            let item = {
                label, id: row.id, sub_num, leaf, icon, type, level: level + 1, pid: [...pid, id], value: {
                    id: row.id, type, level: level + 1, pid: [...pid, id]
                }
            }
            item.key = item.level + '__' + item.id
            if (!leaf && item.id == list[i].id) {
                item.children = await getSalesSubList(item, list, i - 1)
                qcc_tmp.push(item.key)
            }
            tmp.push(item)
        }
    }
    return tmp;
}

async function getSalesSubList(data, list, i) {
    let tmp = []
    if (i < 0) {
        return tmp;
    }
    const { id, level, pid } = data
    const resp = await getSubToTreeBySalesman({
        salesman_id: id,
        qcc_page_id: props.pageId,
        qcc_language: serverLang()
    })
    if (resp.data && resp.data.length) {
        for (let index = 0; index < resp.data.length; index++) {
            const row = resp.data[index];
            let label, leaf, icon, sub_num, type;
            type = 'sub'
            leaf = !row.sub_num > 0
            sub_num = row.sub_num
            label = row.name
            icon = row.user_type == 1 ? icon1 : icon2
            let item = {
                label, id: row.id, sub_num, leaf, icon, type, level: level + 1, pid: [...pid, id], value: {
                    id: row.id, type, level: level + 1, pid: [...pid, id]
                }
            }
            item.key = item.level + '__' + item.id
            if (!leaf && list[i].id == item.id) {
                item.children = await getSubList(item, list, i - 1)
                qcc_tmp.push(item.key)
            }
            tmp.push(item)
        }
    }
    return tmp;
}

async function getSubList(data, list, i) {
    let tmp = []
    if (i < 0) {
        return tmp;
    }
    const { id, level, pid } = data
    const resp = await getSubToTreeByIbId({
        qcc_page_id: props.pageId,
        qcc_language: serverLang(),
        superior_id: id
    })
    if (resp.data && resp.data.length) {
        tmp.push({
            label: t('structure.down_line'),
            id: 'down_line',
            icon: icon4,
            leaf: true,
            type: 'sub',
            level: level + 1,
            pid: [...pid, id],
            value: {
                id: 'down_line',
                type: 'sub',
                level: level + 1,
                pid: [...pid, id],
                key: level+1+'__'+'down_line'
            }
        })
        tmp.push({
            label: t('structure.directly_under'),
            id: 'directly_under',
            icon: icon3,
            leaf: true,
            type: 'sub',
            level: level + 1,
            pid: [...pid, id],
            value: {
                id: 'directly_under',
                type: 'sub',
                level: level + 1,
                pid: [...pid, id],
                key: level+1+'__'+'directly_under'
            }
        })
        for (let index = 0; index < resp.data.length; index++) {
            const row = resp.data[index];
            let label, leaf, icon, sub_num, type;
            type = 'sub'
            leaf = !row.sub_num > 0
            sub_num = row.sub_num
            label = row.name
            icon = row.user_type == 1 ? icon1 : icon2
            let item = {
                label, id: row.id, sub_num, leaf, icon, type, level: level + 1, pid: [...pid, id], value: {
                    id: row.id, type, level: level + 1, pid: [...pid, id]
                }
            }
            item.key = item.level + '__' + item.id
            if (!leaf && list[i].id == item.id) {
                item.children = await getSubList(item, list, i - 1)
                qcc_tmp.push(item.key)
            }
            tmp.push(item)
        }
    }
    return tmp;
}

async function getSubList2(data, list, i) {
    let tmp = []
    if (i < 0) {
        return tmp;
    }
    const { id, level, pid } = data
    const resp = await getSubToTreeByIbId({
        qcc_page_id: props.pageId,
        qcc_language: serverLang(),
        superior_id: id
    })
    if (resp.data && resp.data.length) {
        tmp.push({
            label: t('structure.down_line'),
            id: 'down_line',
            icon: icon4,
            leaf: true,
            type: 'sub',
            level: level,
            pid: [],
            value: {
                id: 'down_line',
                type: 'sub',
                level: level,
                pid: [],
                key: level+'__'+'down_line'
            }
        })
        tmp.push({
            label: t('structure.directly_under'),
            id: 'directly_under',
            icon: icon3,
            leaf: true,
            type: 'sub',
            level: level,
            pid: [],
            value: {
                id: 'directly_under',
                type: 'sub',
                level: level,
                pid: [],
                key: level+'__'+'directly_under'
            }
        })
        for (let index = 0; index < resp.data.length; index++) {
            const row = resp.data[index];
            let label, leaf, icon, sub_num, type;
            type = 'sub'
            leaf = !row.sub_num > 0
            sub_num = row.sub_num
            label = row.name
            icon = row.user_type == 1 ? icon1 : icon2
            let item = {
                label, id: row.id, sub_num, leaf, icon, type, level: level, pid: [], value: {
                    id: row.id, type, level: level, pid: []
                }
            }
            item.key = item.level + '__' + item.id
            if (!leaf && list[i].id == item.id) {
                item.children = await getSubList(item, list, i - 1)
                qcc_tmp.push(item.key)
            }
            tmp.push(item)
        }
    }
    return tmp;
}

</script>

<style lang="scss">
.structure-dialog {
    .el-dialog__header {
        display: none;
    }

    .el-dialog__body {
        padding-bottom: 0;
    }

    .el-scrollbar__wrap {
        height: 100%;
        overflow: initial !important
    }
}
.el-cascader-menu:last-child .el-cascader-node {
    padding-right: 0;
}
.el-cascader-node {
    width: 256px;
    padding: 0;
}

.el-cascader-node__label {
    padding: 0;
}

.user-node {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    line-height: 34px;
    height: 34px;
    min-width: 200px;
    padding-left: 8px;

    .node-icon {
        width: 20px;
        height: 20px;
        margin-right: 10px;
    }

    .node-label {
        font-size: 14px;
    }
}

.user-node-active {
    color: var(--el-cascader-menu-selected-text-color);
    font-weight: bold;
}

.el-cascader-node.in-active-path, .el-cascader-node.is-selectable.in-checked-path, .el-cascader-node.is-active {
    color: unset;
    font-weight: unset;
}

.el-cascader-node__prefix, .el-cascader-node__postfix {
    display: none;
}

.structure-dialog .el-scrollbar__wrap {
    overflow: auto !important;
}

.el-cascader-node > .el-radio {
    display: none;
}

.structure-dialog .loading-container {
    background-color: rgba(255, 255, 255, 0.5);
}
</style>