<template>
    <div style="width: 600px; margin: 10px auto; position: relative; ">

        <!-- <el-alert class="bounce animated" type="warning" :title="alertTilte" :closable="false" show-icon
            style="width: 100%; margin-top: 10px;"></el-alert> -->
        <div class="flex-box-ce" style="flex-direction: column; justify-content: center;">
            <!-- <div class="" style="font-size: 16px; font-weight: 600; text-align: center;">发起考核</div> -->

            <div style="margin: 0 auto 20px auto; font-size: 16px; font-weight: 600;">填写考核基本信息</div>

            <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px" size="small"
                label-position="right">
                <!-- <el-form-item label="考核标题" prop="title">
                    <el-input v-model="form.title" style="width: 300px;"></el-input>
                </el-form-item> -->
                <el-form-item label="考核人员" prop="employeeIds">
                    <el-select v-model="form.employeeIds" placeholder="请选择指定人员" multiple filterable
                        style="width: 300px;" @change="changeEmployeeIds">
                        <el-option v-for="item in employeeMap" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="周期">
                    <el-radio-group v-model="form.cycleType" @change="changeCircle">
                        <el-radio-button label="0">自定义</el-radio-button>
                        <el-radio-button label="1">年度</el-radio-button>
                        <el-radio-button label="2">半年度 </el-radio-button>
                        <el-radio-button label="3">季度</el-radio-button>
                        <el-radio-button label="4">月度</el-radio-button>
                    </el-radio-group>
                </el-form-item>

                <!-- <el-form-item label="考核分类">
                    <el-select v-model="form.cateId" @change="changeCateId" placeholder="请选择考核分类" style="width: 300px;">
                        <el-option v-for="item in cateList" :key="item.cateId" :label="item.name" :value="item.cateId">
                        </el-option>
                    </el-select>
                </el-form-item> -->

                <el-form-item v-if="form.cycleType == 0" label="开始日期" prop="startDate">
                    <el-date-picker v-model="form.startDate" type="date" value-format="yyyy-MM-dd" placeholder="选择开始日期"
                        style="width: 300px;">
                    </el-date-picker>
                </el-form-item>
                <el-form-item v-if="form.cycleType == 0" label="结束日期" prop="endDate">
                    <el-date-picker v-model="form.endDate" type="date" value-format="yyyy-MM-dd" placeholder="选择结束日期"
                        style="width: 300px;">
                    </el-date-picker>
                </el-form-item>

                <el-form-item v-if="form.cycleType == 1" label="选择年份" prop="year">
                    <el-date-picker v-model="form.year" type="year" value-format="yyyy" placeholder="选择年">
                    </el-date-picker>
                </el-form-item>

                

                <el-form-item v-if="form.cycleType == 4" label="选择月份" prop="month">
                    <el-date-picker v-model="form.month" type="month" placeholder="选择月" value-format="yyyy-MM">
                    </el-date-picker>
                </el-form-item>

                <!-- <InterviewFlow form-label="主持人" dialog-title="面谈" node-type="interview" @onConfirm="finishHandle" /> -->

                <el-form-item label="启用面谈">
                    <el-switch v-model="currentNode.enable"></el-switch>
                </el-form-item>

                <el-form-item label="主持人">
                    <el-radio-group v-model="currentNode.assigneeType" :disabled="!currentNode.enable">
                        <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.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.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.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.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 v-if="form.circle == 1" label="结束日期">
                    <el-date-picker v-model="form.endDate" type="date" placeholder="选择结束日期" style="width: 300px;">
                    </el-date-picker>
                </el-form-item> -->

            </el-form>
            <!-- <div style="margin: 20px auto;" v-if="selectedData && selectedData.length > 0">
                <div class="title">已选择的OKR</div>
                <div class="selected-item" v-for="item in selectedData" @click="changeSelectedOkrs">
                    {{ item.name }}
                </div>
            </div>
            <el-link v-else type="primary" @click="isShowProject = true">请选择关联OKR</el-link> -->
            <div style="margin: 20px auto;">
                <el-button type="primary" @click="submitForm('ruleForm')" size="small">确定</el-button>
                <el-button @click="resetForm('ruleForm')" size="small">取 消</el-button>
            </div>

        </div>



        <el-drawer title="考核分类" :visible.sync="cateDetailsDialog" direction="rtl" :before-close="handleClose">
            <CateDetails v-if="cateDetailsDialog"></CateDetails>
        </el-drawer>


        <!-- 关联OKR -->
        <TargetSearch :visible.sync="isShowProject" @confirm="confirmProject" :selectedCheckList="okrs"
            :showSelectedData="selectedData"></TargetSearch>

    </div>
</template>

<script>
import moment from 'moment'

// 计算某一季度开始日期和结束日期
function getQuarterDates(year, quarter) {
    // 计算季度的开始日期（第一个月的第一天）
    const startDate = moment().year(year).quarter(quarter).startOf('quarter');
    // 计算季度的结束日期（最后一个月的最后一天）
    const endDate = moment().year(year).quarter(quarter).endOf('quarter');

    return {
        start: startDate,
        end: endDate
    };
}

import { mapGetters } from 'vuex';
import TargetSearch from '@/performance/views/assessManagement/TargetSearch'; // 对齐目标

export default {
    components: {
        TargetSearch
    },
    model: {
        prop: 'showPublishDialog',
        event: 'close-dialog'
    },
    props: {
        showPublishDialog: {
            type: Boolean,
            default: false
        },
        templateIds: {
            type: Array,
            default: () => []
        },
    },
    data() {
        return {
            alertTilte: "如果有一个指标标题为空，将会发布不成功，请仔细检查数据！",
            employeeMap: this.$getEmployeeMap(), // 员工列表
            cateDetailsDialog: false, // 考核分类弹框
            form: {
                title: "",
                employeeIds: [],
                startDate: "",
                endDate: "",
                cycleType: "0", // 周期类型 0-未定义 1-年度 2-半年度 3-季度 4-月度
                year: "",
                cateId: 0
            },
            isShowProject: false,
            rules: {
                title: [
                    { required: true, message: '请输入考核标题', trigger: 'blur' },
                ],
                employeeIds: [
                    { required: true, message: '请选择考核人员', trigger: 'change' }
                ],
                startDate: [
                    { required: true, message: '请选择开始日期', trigger: 'change' }
                ],
                endDate: [
                    { required: true, message: '请选择结束日期', trigger: 'change' }
                ],
                year: [
                    { required: true, message: '请选择年份', trigger: 'change' }
                ],
                month: [
                    { required: true, message: '请选择月份', trigger: 'change' }
                ],
            },
            dateOptions: [],
            dateParameter: {
                year: moment().format('YYYY'),
                cycle_type: 0,
                dateId: 1,
                name: '选择年度',
            },
            cateList: [], // 考核分类列表,
            interview: false,
            params: null,
            okrs: [], // 关联的OKRS,
            selectedData: [],

            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: [], // 选择的员工列表
            currentNode: {
                id: "IT_" + Date.now() + Math.floor(Math.random() * 10000),
                type: "interview",
                allows: [],
                enable: true,
                weight: 0,
                children: [],
                assigneeIds: [],
                leaderLevel: 1,
                assigneeType: "self",
                multipleType: "or"
            }
        }
    },

    computed: {
        ...mapGetters(['user_info'])
    },

    watch: {
        showPublish(v) {
            // if (v) this.getCateList()
        }
    },

    mounted() {
        // this.getCateList()
    },

    methods: {
        // 考核分类列表
        getCateList() {
            let url = `/performance/cate/list/${this.user_info.site_id}`;
            // this.loading = true
            this.$axiosUser('get', url, {}).then(res => {
                let { data: { code, data: { list, total } } } = res
                if (code == 1) {
                    this.cateList = list
                    this.form.cateId = this.cateList[0].cateId || 0
                }
            })
        },

        // 选择考核分类
        changeCateId(v) {
            console.log(v)
        },
        // 选择员工
        changeEmployeeIds(v) {
            if (v && v.length > 0) {
                v.forEach(item => {
                    this.form.employeeIds.push(item)
                })
            }
            this.form.employeeIds = Array.from(new Set(this.form.employeeIds)); // 去重
        },

        changeCircle(v) {
            if (v == 2) this.dateOptions = [
                { name: '上半年', id: 1, cycle_type: 3 },
                { name: '下半年', id: 2, cycle_type: 3 },
            ]
            if (v == 3) this.dateOptions = [
                { name: '第一季度', id: 1, cycle_type: 2 },
                { name: '第二季度', id: 2, cycle_type: 2 },
                { name: '第三季度', id: 3, cycle_type: 2 },
                { name: '第四季度', id: 4, cycle_type: 2 }
            ]
        },



        dateConfirm(date) {
            let { year, name } = date;
            this.dateParameter.year = year;
            this.dateParameter.name = name;
            // 上半年度
            if (name === "上半年") {
                let startOfYear = moment().year(year).startOf('year'); // 获取年初
                let endOfFirstHalfYear = moment().year(year).startOf('year').add(6, 'months').subtract(1, 'days'); // 获取上半年结束日（6月30日）
                this.form.startDate = startOfYear.format('YYYY-MM-DD');
                this.form.endDate = endOfFirstHalfYear.format('YYYY-MM-DD');
            }
            // 下半年度
            if (name === "下半年") {
                let startOfSecondHalfYear = moment().year(year).startOf('year').add(6, 'months'); // 获取下半年开始日（7月1日）
                let endOfYear = moment().year(year).endOf('year'); // 获取年末
                this.form.startDate = startOfSecondHalfYear.format('YYYY-MM-DD');
                this.form.endDate = endOfYear.format('YYYY-MM-DD');
            }
            // 第一季度
            if (name === "第一季度") {
                const dates = getQuarterDates(year, 1);
                this.form.startDate = dates.start.format('YYYY-MM-DD');
                this.form.endDate = dates.end.format('YYYY-MM-DD');
            }

            // 第一季度
            if (name === "第二季度") {
                const dates = getQuarterDates(year, 2);
                this.form.startDate = dates.start.format('YYYY-MM-DD');
                this.form.endDate = dates.end.format('YYYY-MM-DD');
            }

            // 第三季度
            if (name === "第三季度") {
                const dates = getQuarterDates(year, 3);
                this.form.startDate = dates.start.format('YYYY-MM-DD');
                this.form.endDate = dates.end.format('YYYY-MM-DD');
            }

            // 第四季度
            if (name === "第四季度") {
                const dates = getQuarterDates(year, 4);
                this.form.startDate = dates.start.format('YYYY-MM-DD');
                this.form.endDate = dates.end.format('YYYY-MM-DD');
            }

        },

        handleClose() {
            this.cateDetailsDialog = false
        },

        // 关闭弹窗
        handleCloseDialog() {
            this.$emit('close-dialog', false);
        },


        // 选择管理员
        changeManagerIds(v) {
            this.currentNode.leaderLevel = v
        },


        // 选择员工
        changeEmployeeIds(v) {
            if (v && v.length > 0) {
                this.currentNode.assigneeIds = v
            }
        },

        // 选择岗位
        changePostIds(v) {
            if (v && v.length > 0) {
                this.currentNode.assigneeIds = v
            }
        },

        // 选择部门
        deptChange(val) {
            if (val && val.length > 0) {
                // 获取当前选中的节点
                const checkedNodes = this.$refs.deptSelectRef.getCheckedNodes();
                this.selected_dept_ids = checkedNodes.map((node) => node.value);
                this.currentNode.assigneeIds = this.selected_dept_ids
                this.currentNode.assigneeIds = Array.from(new Set(this.currentNode.assigneeIds)); // 去重
            }

        },


        checkInterviewNode() {

            // 验证表单数据
            this.currentNode.assigneeIds = []
            // 回显选中的管理者
            if (this.currentNode.assigneeType == 'leader') {
                if (this.selected_manager_ids) this.currentNode.leaderLevel = this.selected_manager_ids
                else return this.$message.error("请选择管理员")
            }

            // 回显选中的被考核人
            if (this.currentNode.assigneeType == 'self') {
                this.currentNode.assigneeIds.push(this.user_info.id);
            }

            // 回显选中的岗位
            if (this.currentNode.assigneeType == 'post') {
                if (this.selected_post_ids && this.selected_post_ids.length > 0)
                    this.selected_post_ids.forEach(postId => {
                        this.currentNode.assigneeIds.push(postId);
                    })
                else return this.$message.error("请选择岗位")
            }

            // 回显选中的指定人员
            if (this.currentNode.assigneeType == 'user') {
                if (this.selected_employee_ids && this.selected_employee_ids.length > 0)
                    this.selected_employee_ids.forEach(employeeId => {
                        this.currentNode.assigneeIds.push(employeeId);
                    })
                else return this.$message.error("请选择指定人员")
            }

            // 回显选中的部门列表
            if (this.currentNode.assigneeType == 'deptLeader') {
                if (this.selected_dept_ids && this.selected_dept_ids.length > 0)
                    this.selected_dept_ids.forEach(dept_id => {
                        this.currentNode.assigneeIds.push(dept_id);
                    })
                else return this.$message.error("请选择部门")
            }

            // 去重
            this.currentNode.assigneeIds = Array.from(new Set(this.currentNode.assigneeIds))

            // let nodes = [this.currentNode];
            console.log(this.currentNode)
        },

        // 确定按钮
        submitForm(formName) {

            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // 周期类型 0 - 未定义 1 - 年度 2 - 半年度 3 - 季度 4 - 月度
                    // 年度
                    if (this.form.cycleType == 1) {
                        let { year } = this.form;
                        // 计算年份的开始时间（即1月1日）
                        const startOfYear = moment().year(year).startOf('year');
                        this.form.startDate = startOfYear.format('YYYY-MM-DD');
                        // 计算年份的结束时间（即12月31日）
                        const endOfYear = moment().year(year).endOf('year');
                        // 年度结束时间
                        this.form.endDate = endOfYear.format('YYYY-MM-DD');
                    }


                    // 月
                    if (this.form.cycleType == 4) {
                        let [year, month] = this.form.month.split("-");
                        // 计算开始时间（该月的第1天）
                        const startOfMonth = moment(`${year}-${month}-01`);
                        this.form.startDate = startOfMonth.format('YYYY-MM-DD');

                        // 计算结束时间（该月的最后一天）
                        const endOfMonth = moment(startOfMonth).endOf('month');
                        this.form.endDate = endOfMonth.format('YYYY-MM-DD');
                    }

                    this.params = {
                        templateIds: this.templateIds,
                        ...this.form,
                        okrs: this.okrs
                    }
                    this.checkInterviewNode()
                    this.params = {
                        ...this.params,
                        interviewFlow: {
                            nodes: [...this.currentNode]
                        }
                    },
                    // this.interview = true
                    this.$emit('onConfirm', this.params);
                    // this.handleCloseDialog();
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });


        },
        // 重置表单
        resetForm(formName) {
            
            this.$refs[formName].resetFields();
            this.handleCloseDialog();
        },

        finishHandle(nodes) {
            this.params = {
                ...this.params,
                interviewFlow: {
                    nodes
                }
            },

            this.$emit('onConfirm', this.params, this.selectedData);
            this.handleCloseDialog();
        },

        changeSelectedOkrs() {
            this.isShowProject = true
        },

        confirmProject(okrs, selectedData) {
            this.okrs = okrs;
            this.selectedData = selectedData;
        }
    }
}
</script>

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

.selectBox {
    width: 300px;
    height: 40px;
    border-radius: 40px;
    border: 1px solid #eee;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
}
.status-btn-box {
    width: 120px;
    height: 40px;
    z-index: 10;
    position: absolute;
    top: 20px;
    left: 20px;

    .status-btn {
        width: 100%;
        height: 100%;
        background: transparent;
        border: 2px dashed;
        text-align: center;
        font-size: 20px;
        line-height: 40px;
    }
}

.title {
    margin-bottom: 5px;
}

.selected-item {
    padding: 5px;
    box-sizing: border-box;
    border-radius: 4px;
    background: #f7f7f7;
    margin-bottom: 5px;

    &:hover {
        cursor: pointer;
    }
}
</style>
