<template>
    <div>
        <el-dialog :title="dialogTitle" center :visible.sync="targetConfirms" width="600px"
            :before-close="handleCloseDialog">
            <div v-if="currentNode">
                <el-form ref="form" label-width="80px" size="small">
                    <el-form-item label="启用">
                        <el-switch v-model="currentNode.enable"></el-switch>
                    </el-form-item>

                    <div class="handler-list">
                        <el-tag v-for="(item, index) in currentNode.children" :key="index"
                            :type="childIndex === index ? '' : 'info'" closable @close="handleTagDelete(index)"
                            @click="handleTagClick(item, index)">
                            {{ item.assigneeType | filterType }}
                        </el-tag>
                        <el-button v-show="currentNode.enable" icon="el-icon-plus" size="mini"
                            style="margin-bottom: 10px;" @click="addTagList()"></el-button>
                    </div>

                    <el-form-item :label="formLabel">
                        <el-radio-group v-model="currentNode.children[childIndex].assigneeType"
                            :disabled="!currentNode.enable" @change="changeAssigneeType">
                            <el-radio-button label="leader">管理员</el-radio-button>
                            <el-radio-button label="user">指定人员</el-radio-button>
                            <el-radio-button label="self">被考核人</el-radio-button>
                            <el-radio-button label="post">岗位</el-radio-button>
                            <el-radio-button label="deptLeader">部门</el-radio-button>
                        </el-radio-group>
                    </el-form-item>


                    <el-form-item v-if="currentNode.children[childIndex].assigneeType === 'leader'">
                        <el-select v-model="selected_manager_ids" placeholder="请选择管理员" :disabled="!currentNode.enable"
                            filterable style="width: 300px;" @change="changeManagerIds">
                            <el-option v-for="item in levelOptions" :key="item.value" :label="item.label"
                                :value="item.value" style="width: 300px;"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item v-if="currentNode.children[childIndex].assigneeType === 'user'">
                        <el-select v-model="selected_employee_ids" placeholder="请选择指定人员" multiple
                            :disabled="!currentNode.enable" filterable style="width: 300px;"
                            @change="changeEmployeeIds">
                            <el-option v-for="item in employeeMap" :key="item.id" :label="item.name" :value="item.id"
                                style="width: 300px;"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item v-if="currentNode.children[childIndex].assigneeType === 'post'">
                        <el-select v-model="selected_post_ids" placeholder="请选择岗位" multiple
                            :disabled="!currentNode.enable" filterable style="width: 300px;" @change="changePostIds">
                            <el-option v-for="item in postList" :key="item.id" :label="item.name" :value="item.id"
                                style="width: 300px;"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item v-if="currentNode.children[childIndex].assigneeType === 'deptLeader'">
                        <el-cascader ref="deptSelectRef" v-model="selected_dept_ids" size="small" style="width: 300px;"
                            :options="deptList" :props="cascaderProps" placeholder="请选择部门" filterable clearable
                            @change="deptChange" :disabled="!currentNode.enable"></el-cascader>
                    </el-form-item>

                    <el-form-item label="多人时">
                        <el-radio-group v-model="currentNode.children[childIndex].multipleType"
                            :disabled="!currentNode.enable">
                            <el-radio-button label="or">任一人确认(或签)</el-radio-button>
                            <el-radio-button label="parallel">按顺序确认(会签)</el-radio-button>
                            <el-radio-button label="sequence">同时确认(会签)</el-radio-button>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="允许">
                        <el-checkbox-group v-model="currentNode.children[childIndex].allows"
                            :disabled="!currentNode.enable">
                            <el-checkbox-button label="edit">修改指标</el-checkbox-button>
                            <el-checkbox-button label="transfer">转交</el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer">
                <el-button type="primary" @click="submitForm" size="small">确 定</el-button>
                <el-button @click="handleCloseDialog" size="small">取 消</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { mapGetters } from 'vuex';
import EmployeeSelector from '@/components/EmployeeSelector'; // 选择部门组件
// 引入lodash库
import _ from 'lodash';
export default {
    components: {
        EmployeeSelector,
    },
    model: {
        prop: 'targetConfirms',
        event: 'close-dialog'
    },
    props: {
        targetConfirms: {
            type: Boolean,
            default: false
        },
        dialogTitle: {
            type: String,
            default: ''
        },
        nodeType: {
            type: String,
            default: ''
        },
        formLabel: {
            type: String,
            default: ''
        },
        templateId: {
            type: String | Number,
            default: ''
        },
        indicatorId: {
            type: String | Number,
            default: ''
        },
        tagIndex: {
            type: String | Number,
            default: 0
        },
        selectNodes: {
            type: Array,
            default: () => []
        }
    },
    computed: {
        ...mapGetters(['user_info'])
    },
    data() {
        return {
            cascaderProps: {
                multiple: true, // 启用多选
                checkStrictly: true, // 父子节点不联动
                emitPath: false, // 选中值只返回当前节点的值
            },
            levelOptions: [
                {
                    value: 1,
                    label: '直接管理员'
                },
                {
                    value: 2,
                    label: '二级管理员'
                },
                {
                    value: 3,
                    label: '三级管理员'
                },
                {
                    value: 4,
                    label: '四级管理员'
                },
                {
                    value: 5,
                    label: '五级管理员'
                },
                {
                    value: 6,
                    label: '六级管理员'
                }
            ],
            deptList: JSON.parse(localStorage.getItem("deptList")), // 部门列表 - 树形结构
            dept_list: JSON.parse(localStorage.getItem("dept_list")), // 部门列表
            employeeMap: this.$getEmployeeMap(), // 员工列表
            postList: JSON.parse(localStorage.getItem("postList")), // 岗位列表
            selected_dept_ids: [], // 选择的部门列表
            selected_manager_ids: '', // 选择的管理员列表
            selected_post_ids: [], // 选择的岗位列表
            selected_employee_ids: [], // 选择的员工列表
            childIndex: 0,
            currentNode: null,
        }
    },
    filters: {
        filterType(v) {
            if (v == 'leader') return v = "管理员"
            if (v == 'self') return v = "被考核人"
            if (v == 'post') return v = "岗位"
            if (v == 'user') return v = "指定人员"
            if (v == 'deptLeader') return v = "部门"
        }
    },
    watch: {
        'targetConfirms'(v) {
            if (v) this.initData()
        },

    },
    mounted() {
        this.initData();
    },
    methods: {
        initData() {
            this.selectNodes.forEach(select => {
                // 正在操作的节点
                if (select.type == this.nodeType) this.currentNode = _.cloneDeep(select)
            })
            this.selected_manager_ids = 1;
            this.selected_employee_ids = [];
            this.selected_post_ids = [];
            this.selected_dept_ids = [];
            this.childIndex = this.tagIndex;
            this.currentNode.children.forEach(child => {
                this.selected_employee_ids = child.assigneeType === 'user' ? child.assigneeIds : [];
                this.selected_post_ids = child.assigneeType === 'post' ? child.assigneeIds : [];
                this.selected_dept_ids = child.assigneeType === 'deptLeader' ? child.assigneeIds : [];
            });
            console.log("表单信息");
            console.log(this.currentNode);
        },




        // 选择管理员
        changeManagerIds(v) {
            this.currentNode.children[this.childIndex].assigneeIds = []
            this.currentNode.children[this.childIndex].leaderLevel = v ? v : 1
        },


        // 选择员工
        changeEmployeeIds(v) {
            this.currentNode.children[this.childIndex].assigneeIds = []
            this.currentNode.children[this.childIndex].assigneeIds = v ? v : []
        },

        // 选择岗位
        changePostIds(v) {
            this.currentNode.children[this.childIndex].assigneeIds = []
            this.currentNode.children[this.childIndex].assigneeIds = v ? v : []
        },

        // 选择部门
        deptChange(val) {

            // 获取当前选中的节点
            const checkedNodes = this.$refs.deptSelectRef.getCheckedNodes();
            this.selected_dept_ids = checkedNodes.map((node) => node.value);
            this.currentNode.children[this.childIndex].assigneeIds = []
            this.currentNode.children[this.childIndex].assigneeIds = this.selected_dept_ids.length ? this.selected_dept_ids : []
        },

        changeAssigneeType(v) {
            this.currentNode.children[this.childIndex].assigneeIds = []
            this.currentNode.children[this.childIndex].leaderLevel = 1
            this.selected_manager_ids = 1;
            this.selected_employee_ids = [];
            this.selected_post_ids = [];
            this.selected_dept_ids = [];
            this.currentNode.children.forEach((child, index) => {
                if (index == this.childIndex) {
                    this.selected_manager_ids = child.assigneeType === 'leader' ? child.leaderLevel : 1;
                    this.selected_employee_ids = child.assigneeType === 'user' ? child.assigneeIds : [];
                    this.selected_post_ids = child.assigneeType === 'post' ? child.assigneeIds : [];
                    this.selected_dept_ids = child.assigneeType === 'deptLeader' ? child.assigneeIds : [];
                }
            });
        },


        changeFormEnable(v) {
            this.currentNode.enable = v;
        },

        // 添加子节点
        addTagList() {
            let id, type;
            if (this.nodeType == 'targetConfirms') {
                id = "TC_" + Date.now() + Math.floor(Math.random() * 10000);
                type = "targetConfirm"
            }
            if (this.nodeType == 'scores') {
                id = "S_" + Date.now() + Math.floor(Math.random() * 10000);
                type = "score"
            }
            if (this.nodeType == 'reviews') {
                id = "R_" + Date.now() + Math.floor(Math.random() * 10000);
                type = "review"
            }

            let obj = {
                allows: [],
                assigneeIds: [],
                assigneeType: 'self',
                children: [],
                enable: true,
                id,
                leaderLevel: 1,
                multipleType: "or",
                type,
                weight: 0,
            }
            this.currentNode.children.push(obj);
            this.childIndex = this.currentNode.children.length - 1;
            this.selected_manager_ids = 1; // 选择的管理员
            this.selected_dept_ids = []; // 选择的部门列表
            this.selected_post_ids = [] // 选择的岗位列表
            this.selected_employee_ids = [] // 选择的员工列表
        },

        handleTagClick(item, index) {
            this.childIndex = index;
            this.selected_manager_ids = 1;
            this.selected_employee_ids = [];
            this.selected_post_ids = [];
            this.selected_dept_ids = []; // 选择的部门列表
            // 回显下拉框数据
            this.selected_employee_ids = item.assigneeType === 'user' ? item.assigneeIds : [];
            this.selected_post_ids = item.assigneeType === 'post' ? item.assigneeIds : [];
            this.selected_dept_ids = item.assigneeType === 'deptLeader' ? item.assigneeIds : [];
        },

        handleTagDelete(index) {
            // 最后一个不能删除
            if (this.currentNode && this.currentNode.children.length > 1) {
                let selectChildId = this.currentNode.children[this.childIndex].id;
                this.childIndex = 0;
                this.currentNode.children = this.currentNode.children.filter((_, i) => i !== index);
                if (selectChildId) {
                    this.currentNode.children.forEach((child, i) => {
                        if (child.id === selectChildId) this.childIndex = i;
                    })
                }

            }

        },
        handleCloseDialog() {
            this.currentNode = null
            this.selected_manager_ids = 1;
            this.selected_employee_ids = [];
            this.selected_post_ids = [];
            this.selected_dept_ids = [];
            this.$emit('close-dialog', false)
        },
        submitForm() {
            

            // 验证表单数据
            if (this.currentNode.children && this.currentNode.children.length > 0) {
                for (let i = 0; i < this.currentNode.children.length; i++) {
                    if (this.currentNode.children[i].assigneeType === 'self') {
                        this.currentNode.children[i].assigneeIds.push(this.user_info.id);
                        // 去重
                        this.currentNode.children[i].assigneeIds = Array.from(new Set(this.currentNode.children[i].assigneeIds))
                    }

                    let flag = this.currentNode.children[i].assigneeIds && this.currentNode.children[i].assigneeIds.length > 0
                    
                    if (this.currentNode.children[i].assigneeType === 'leader') {
                        if (!this.currentNode.children[i].leaderLevel) return this.$message.error("请选择管理员")
                    }
                    if (this.currentNode.children[i].assigneeType === 'deptLeader') {
                        if (!flag) return this.$message.error("请选择部门")
                    }
                    if (this.currentNode.children[i].assigneeType === 'user') {
                        if (!flag) return this.$message.error("请选择指定人员")
                    }
                    if (this.currentNode.children[i].assigneeType === 'post') {
                        if (!flag) return this.$message.error("请选择岗位")
                    }
                }
            }

            let nodes = []            
            this.selectNodes.forEach(select => {
                // 正在操作的节点
                if (select.type == this.nodeType) { 
                    select = this.currentNode
                    console.log(select)
                } 
                nodes.push(select)
            })
            let data = {
                indicatorId: this.indicatorId, // 指标ID
                nodes
            }
            this.$emit("onConfirm", data);
            this.handleCloseDialog();
        },
        handleFormData() {

        }
    }
}

</script>

<style lang="scss" scoped>
.handler-list {
    width: 500px;
    margin: 0 auto 16px auto;
    border-radius: 6px;
    border: 1px solid #d7dae2;
    padding: 10px 0 0 10px;
    box-sizing: border-box;
    display: flex;
    flex-wrap: wrap;

    .el-tag {
        margin: 0 10px 10px 0;
    }
}
</style>