<template>
    <div class="box boxMinHeight">
        <header class="header">
            <div class="header-content flex-box-ce">
                <!-- 返回按钮 -->
                <div class="flex-box-ce header-left">
                    <i class="el-icon-arrow-left fontColorC" @click="$router.go(-1)"></i>
                    <el-tooltip class="item" effect="dark" :content="templateTitle" placement="bottom">
                        <div class="text fontColorB font-flex-word">{{ templateTitle }}</div>
                    </el-tooltip>
                    <el-popover ref="popoverRef" placement="right" width="400" trigger="click">
                        <div class="flex-box-ce">
                            <el-input v-model="title" placeholder="请输入模板名称" size="small"></el-input>
                            <el-button type="primary" size="small" style="margin-left: 10px;"
                                @click="editTitle()">确定</el-button>
                        </div>
                        <i class="el-icon-edit" slot="reference" style="margin-left: 10px; color: #999;"></i>
                    </el-popover>
                </div>

                <!-- 发布按钮 -->
                <div class="header-right">
                    <!-- 某一个指标标题为空，或者评分,审批不开启，不能发起考核 -->
                    <el-button type="primary" @click="publish" :disabled="isTitleNull || isScoreNull">发布考核</el-button>
                </div>
            </div>
        </header>

        <div style="height: 1px; background-color: #DCDFE6; margin-top: 5px;"></div>

        <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="justify-content: space-between; margin-top: 10px;">
            <div class="flex-box-ce">
                <el-button type="primary" size="small" @click="addData()">添加指标</el-button>

                <el-button type="danger" :disabled="!(multipleSelection && multipleSelection.length > 0)"
                    @click="confirmDelete()" size="small">批量删除</el-button>
            </div>


            <div class="flex-box-ce" style="padding: 0 20px; color: #999;">
                <el-popover placement="right" trigger="hover" class="popover" @show="showPopover">
                    <div class="flex-box-ce" style="width: 200px; justify-content: space-between;">
                        <el-checkbox v-model="checkAll" @change="checkAllChangeFn">全选</el-checkbox>
                        <el-button type="text" @click="reset(true)">重置</el-button>
                    </div>
                    <div style="height: 1px; background-color: #DCDFE6; margin: 5px 0;"></div>
                    <el-checkbox-group v-model="checkColumns" @change="changeColumns"
                        style="width: 200px; display: flex; flex-direction: column;">
                        <el-checkbox v-for="(item, key) in this.tableColumn" :label="item.label"
                            :key="item.label"></el-checkbox>
                    </el-checkbox-group>
                    <div class="flex-box-ce" slot="reference">
                        <i class="el-icon-s-tools" style="margin-right: 5px;"></i>流程节点展示
                    </div>
                </el-popover>
            </div>
        </div>

        <el-table :data="tableData" ref="fmeaTableRef" v-table-move="['fmeaTableRef']" v-loading="loading" stripe
            style="width: 100%; margin-top: 10px;" border :header-cell-style="{ background: '#f5f7fa' }"
            @selection-change="handleSelectChange" :height="600">
            <el-table-column type="selection"></el-table-column>
            <template v-for="item in tableColumn">

                <el-table-column v-if="item.isShow && item.label === '规则'" :key="item.prop" :prop="item.prop"
                    :label="item.label" align="center" :min-width="item.width">
                    <template slot-scope="scope">
                        <el-tooltip v-if="scope.row.content" class="item" effect="dark" placement="top">
                            <div v-html="scope.row.content" slot="content"
                                style="max-width: 300px; white-space: pre-line;">
                            </div>
                            <div class="oneLine"
                                @click="editContent(scope.$index, scope.row.content, scope.row.indicatorId)">
                                {{ scope.row.content }}
                            </div>
                        </el-tooltip>
                        <el-button v-else
                            @click="editContent(scope.$index, scope.row.content, scope.row.indicatorId)">编辑规则</el-button>
                    </template>
                </el-table-column>

                <el-table-column v-else-if="item.isShow && ['目标', '权重(%)'].includes(item.label)" :key="item.prop"
                    :prop="item.prop" :label="item.label" align="center" :min-width="item.width">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row[item.prop]" :placeholder="item.label" clearable
                            @blur="handleEdit(item.prop, scope.row[item.prop], scope.row.indicatorId)"
                            oninput="value=value.replace(/[^\d.]/g,'')"></el-input>
                    </template>
                </el-table-column>

                <el-table-column v-else-if="item.isShow && item.label === '计算公式'" prop="formulae" label="计算公式"
                    align="center" min-width="130">
                    <template slot-scope="scope">
                        <el-button @click="openFormula(scope.row, scope.$index)">
                            {{ scope.row.expression && scope.row.expression.formulas.length > 0 ? `公式
                            ${scope.row.expression.formulas.length} 条` : '公式' }}
                        </el-button>
                    </template>
                </el-table-column>

                <el-table-column v-else-if="item.isShow && ['指标', '单位'].includes(item.label)" :key="item.prop"
                    :prop="item.prop" :label="item.label" align="center" :min-width="item.width">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row[item.prop]" :placeholder="item.label" clearable
                            @blur="handleEdit(item.prop, scope.row[item.prop], scope.row.indicatorId)"></el-input>
                    </template>
                </el-table-column>

                <el-table-column v-if="item.isShow && flowColumn.includes(item.label)" :key="item.prop"
                    :prop="item.prop" :label="item.label" :render-header="(h, obj) => renderHeader(h, item, item.prop)"
                    align="center" :min-width="item.width" fixed="right">
                    <template slot-scope="scope">
                        <template v-if="item.label === '确认目标'">
                            <el-switch v-if="!scope.row.flow.nodes[0].enable" :value="scope.row.flow.nodes[0].enable"
                                @input="handleStatusChange(-1, scope.row, 'targetConfirms')"></el-switch>
                            <ShowDataComp v-else-if="scope.row.flow.nodes[0].enable && isDataShow"
                                :show-data="scope.row.flow.nodes[0]" :select-nodes="scope.row"
                                @btnClick="handleBtnClick" />
                        </template>

                        <template v-if="item.label === '录入结果'">
                            <el-switch v-if="!scope.row.flow.nodes[1].enable" :value="scope.row.flow.nodes[1].enable"
                                @input="handleStatusChange(-1, scope.row, 'resultInput')"></el-switch>
                            <ShowDataComp v-else-if="scope.row.flow.nodes[1].enable && isDataShow"
                                :show-data="scope.row.flow.nodes[1]" :select-nodes="scope.row"
                                @btnClick="handleBtnClick" />
                        </template>

                        <template v-if="item.label === '自评'">
                            <el-switch v-model="scope.row.flow.nodes[2].enable"
                                @change="handleScoreSelf(scope.row, scope.$index)"></el-switch>
                        </template>

                        <template v-if="item.label === '互评'">
                            <el-switch :value="scope.row.flow.nodes[3].enable"
                                @input="handleStatusChange(-1, scope.row, 'scoreEachOther')"></el-switch>
                        </template>

                        <template v-if="item.label === '评分'">
                            <el-switch v-if="!scope.row.flow.nodes[4].enable" :value="scope.row.flow.nodes[4].enable"
                                @input="handleStatusChange(-1, scope.row, 'scores')"></el-switch>
                            <ShowDataComp v-else-if="scope.row.flow.nodes[4].enable && isDataShow"
                                :show-data="scope.row.flow.nodes[4]" :select-nodes="scope.row"
                                @btnClick="handleBtnClick" />
                        </template>

                        <template v-if="item.label === '审批'">
                            <el-switch v-if="!scope.row.flow.nodes[5].enable" :value="scope.row.flow.nodes[5].enable"
                                @input="handleStatusChange(-1, scope.row, 'reviews')"></el-switch>
                            <ShowDataComp v-else-if="scope.row.flow.nodes[5].enable && isDataShow"
                                :show-data="scope.row.flow.nodes[5]" :select-nodes="scope.row"
                                @btnClick="handleBtnClick" />
                        </template>

                        <template v-if="item.label === '抄送'">
                            <el-switch v-if="!scope.row.flow.nodes[6].enable" :value="scope.row.flow.nodes[6].enable"
                                @input="handleStatusChange(-1, scope.row, 'cc')"></el-switch>
                            <ShowDataComp v-else-if="scope.row.flow.nodes[6].enable && isDataShow"
                                :show-data="scope.row.flow.nodes[6]" :select-nodes="scope.row"
                                @btnClick="handleBtnClick" />
                        </template>

                    </template>
                </el-table-column>
            </template>

        </el-table>

        <div style="height: 50px;"></div>
        <!-- <TiptapComp /> -->
        <!-- 编辑流程节点 -->
        <!-- <HandleNode v-if="currentIndicator" v-model="dialogVisible" :form-label="formLabel" :dialog-title="dialogTitle"
            :node-type="nodeType" :template-id="templateId" :select-nodes="selectNodes"
            :indicator-id="selectIndicatorId" @closeDialog="closeDialog" :tag-index="tagIndex"
            @onConfirm="finishHandle" /> -->

        <!-- 编辑计算公式 -->
        <FormulaComp v-if="showFormula" v-model="showFormula"
            :fixed-props="[{ key: 'target', name: '目标' }, { key: 'weight', name: '权重' }, { key: 'result', name: '结果值' }]"
            :expressions-props="currentIndicator.expression.formulas || []" @onConfirm="onFormulaConfirm" />

        <!-- 发布考核弹框 -->
        <PublishComp v-if="showPublish" v-model="showPublish" :template-ids="[templateId]" @onConfirm="onPubishConfirm" />

        <!-- 编辑规则 -->
        <EditContentComp v-if="showEditContent" v-model="showEditContent" :content="content"
            :indicator-id="selectIndicatorId" :template-id="templateId" @finishEdit="finishEditContent" />

        <!-- 批量修改流程节点 -->
        <BatchHandleNode v-if="batchHandleDialog" v-model="batchHandleDialog" :template-id="templateId"
            :form-label="formLabel" :dialog-title="dialogTitle" :node-type="nodeType" :handle-node="handleNode"
            @onConfirm="finishBatchHandle" />

        <!-- 编辑确认目标节点 -->
        <TargetConfirms v-if="targetConfirms" v-model="targetConfirms" :form-label="formLabel"
            :dialog-title="dialogTitle" :node-type="nodeType" :template-id="templateId" :select-nodes="selectNodes"
            :indicator-id="selectIndicatorId" @closeDialog="closeDialog" :tag-index="tagIndex"
            @onConfirm="finishHandle" />

        <!-- 编辑录入结果节点 -->
        <ResultInput v-if="resultInput" v-model="resultInput" :form-label="formLabel" :dialog-title="dialogTitle"
            :node-type="nodeType" :template-id="templateId" :select-nodes="selectNodes"
            :indicator-id="selectIndicatorId" @closeDialog="closeDialog" :tag-index="tagIndex"
            @onConfirm="finishHandle" />

        <!-- 编辑互评节点 -->
        <ScoreEachOther v-if="scoreEachOther" v-model="scoreEachOther" :form-label="formLabel"
            :dialog-title="dialogTitle" :node-type="nodeType" :template-id="templateId" :select-nodes="selectNodes"
            :indicator-id="selectIndicatorId" @closeDialog="closeDialog" :tag-index="tagIndex"
            @onConfirm="finishHandle" />

        <!-- 编辑评分节点 -->
        <Scores v-if="scores" v-model="scores" :form-label="formLabel" :dialog-title="dialogTitle" :node-type="nodeType"
            :template-id="templateId" :select-nodes="selectNodes" :indicator-id="selectIndicatorId"
            @closeDialog="closeDialog" :tag-index="tagIndex" @onConfirm="finishHandle" />

        <Reviews v-if="reviews" v-model="reviews" :form-label="formLabel" :dialog-title="dialogTitle" :node-type="nodeType"
            :template-id="templateId" :select-nodes="selectNodes" :indicator-id="selectIndicatorId"
            @closeDialog="closeDialog" :tag-index="tagIndex" @onConfirm="finishHandle" />

        <!-- 编辑审批节点 -->
        <CC v-if="cc" v-model="cc" :form-label="formLabel" :dialog-title="dialogTitle"
            :node-type="nodeType" :template-id="templateId" :select-nodes="selectNodes"
            :indicator-id="selectIndicatorId" @closeDialog="closeDialog" :tag-index="tagIndex"
            @onConfirm="finishHandle" />
    </div>
</template>

<script>
import { mapGetters } from 'vuex';
import FormulaComp from '@/newPerformance/components/TemplateDetails/FormulaComp'; // 计算公式弹框
import HandleNode from '@/newPerformance/components/TemplateDetails/HandleNode'; //单独设置流程节点弹框
import PublishComp from '@/newPerformance/components/TemplateDetails/PublishComp'; // 发布考核弹框
import ShowDataComp from '@/newPerformance/components/PublicComp/ShowData'; // 显示节点数据组件
import EditContentComp from '@/newPerformance/components/TemplateDetails/EditContent'; // 编辑规则组件
import BatchHandleNode from '@/newPerformance/components/TemplateDetails/BatchHandleNode'; // 批量设置流程节点
import TargetConfirms from '@/newPerformance/components/TemplateDetails/TargetConfirms'; // 确认目标流程节点
import ResultInput from '@/newPerformance/components/TemplateDetails/ResultInput'; // 结果录入流程节点
import ScoreEachOther from '@/newPerformance/components/TemplateDetails/ScoreEachOther'; // 互评流程节点
import Scores from '@/newPerformance/components/TemplateDetails/Scores'; // 评分流程节点
import Reviews from '@/newPerformance/components/TemplateDetails/Reviews'; // 审批流程节点
import CC from '@/newPerformance/components/TemplateDetails/CC'; // 审批流程节点

export default {
    components: {
        HandleNode,
        FormulaComp,
        PublishComp,
        ShowDataComp,
        EditContentComp,
        BatchHandleNode,
        TargetConfirms,
        ResultInput,
        ScoreEachOther,
        Scores,
        Reviews,
        CC
    },
    data() {
        return {
            isDataShow: false,
            isShow: false,
            templateTitle: "默认标题",
            loading: false,
            title: "默认标题",
            alertTilte: "可在表格中直接编辑指标，规则 (规则支持富文本) ，目标，单位，权重，计算公式以及流程节点, 注意: 每个指标的标题不能为空！每个指标的评分节点一定要开启！",
            templateId: "", // 模板ID
            tableData: [], // 表格数据
            showFormula: false, // 编辑计算公式弹框显示
            showPublish: false, // 发布考核弹框显示
            dialogVisible: false, // 编辑流程节点弹框显示
            dialogTitle: "", // 编辑流程节点弹框标题
            isDisable: false, // 是否禁用
            nodeType: "", // 节点类型
            currentIndicator: null, // 操作的指标
            selectIndicatorId: "", // 选择的指标ID
            selectNodes: [], // 选中指标所有的节点
            selectIndex: 0, // 表格行索引
            formLabel: "",
            tagIndex: 0,
            multipleSelection: [],
            content: "", // 指标规则
            showEditContent: false, // 编辑指标内容弹框
            deptList: [], // 部门列表 - 树形结构
            dept_list: [], // 部门列表
            postList: [], // 岗位列表
            flowColumn: ["确认目标", "录入结果", "自评", "互评", "评分", "审批", "抄送"],
            tableColumn: [
                { label: "指标", prop: "title", isShow: true, width: 150 },
                { label: "规则", prop: "content", isShow: true, width: 150 },
                { label: "目标", prop: "target", isShow: true, width: 150},
                { label: "单位", prop: "unit", isShow: true, width: 100 },
                { label: "权重(%)", prop: "weight", isShow: true, width: 100 },
                { label: "计算公式", prop: "formulae", isShow: true, width: 100 },
                { label: "确认目标", prop: "targetConfirms", isShow: false, width: 100 },
                { label: "录入结果", prop: "resultInput", isShow: false, width: 100 },
                { label: "自评", prop: "scoreSelf", isShow: false, width: 100 },
                { label: "互评", prop: "scoreEachOther", isShow: false, width: 100 },
                { label: "评分", prop: "scores", isShow: false, width: 100 },
                { label: "审批", prop: "reviews", isShow: false, width: 100 },
                { label: "抄送", prop: "cc", isShow: false, width: 100 }
            ],
            checkColumns: [],
            checkAll: false,
            flowInfo: {},
            handleNode: {},
            batchHandleDialog: false,
            targetConfirms: false,
            resultInput: false,
            scoreEachOther: false,
            scores: false,
            reviews: false,
            cc: false
        }
    },
    computed: {
        ...mapGetters(['user_info']),
        // 指标标题为空不能发起考核
        isTitleNull() {
            return this.tableData.find(item => item.title == '' || item.title == null) ? true : false
        },
        // 指标评分为禁用不能发起考核
        isScoreNull() {
            return this.tableData.find(item => !item.flow.nodes[4].enable) ? true : false
        }
    },


    created() {
        this.templateId = this.$route.params.templateDetailId;
        this.get_template_detail();
        this.get_table_data();
        this.isDataShow = false
        // 请求岗位列表，部门列表
        Promise.all([this.get_dept_list(), this.get_post_list()]).then(([deptRes, postRes]) => {
            if (deptRes.data.code !== 1) return this.$message.error(deptRes.data.msg || "请求部门列表数据出错")
            if (postRes.data.code !== 1) return this.$message.error(postRes.data.msg || "请求岗位列表数据出错")
            this.dept_list = deptRes.data.data.list;
            this.deptList = this.getTreeData(this.dept_list); // 处理成树状结构
            this.postList = postRes.data.data.list
            localStorage.setItem("dept_list", JSON.stringify(this.dept_list))
            localStorage.setItem("deptList", JSON.stringify(this.deptList))
            localStorage.setItem("postList", JSON.stringify(this.postList))
            this.isDataShow = true
        })
    },
    methods: {

        // 处理部门树状结构数据
        getTreeData(data) {
            for (var i = 0; i < data.length; i++) {
                data[i].checked = false;
                if (data[i].children.length < 1) {
                    // children若为空数组，则将children设为undefined
                    data[i].children = undefined;
                } else {
                    // children若不为空数组，则继续 递归调用 本方法
                    this.getTreeData(data[i].children);
                }
            }
            return data;
        },

        // 获取部门
        get_dept_list() {
            return this.$axiosUser('get', '/api/pro/department/tree', '', 'v2')
        },

        // 岗位列表
        get_post_list() {
            let data = {
                page: 1,
                page_size: 999,
                cate_id: -1,
                name: ''
            }
            return this.$axiosUser('get', '/api/pro/post/cate_post_list', data)
        },

        // 自定义表头
        renderHeader(h, item, type) {
            let label = ""
            const labels = {
                'targetConfirms': '确认目标',
                'resultInput': '录入结果',
                'scoreSelf': '自评',
                'scoreEachOther': '互评',
                'scores': '评分',
                'reviews': '审批',
                'cc': '抄送'
            }
            label = labels[type];
            let that = this;
            
            return h('div', {
                style: { display: "flex", alignItems: "center", justifyContent: "center" }
            }, [

                h('el-button', {
                    props: {
                        size: 'small'
                    },
                    on: {
                        click: function () {
                            that.clickButton(type);
                        }
                    }
                }, label),
            ])
        },

        clickButton(nodeType) {
            this.handleNode = this.flowInfo.nodes.find(node => node.type === nodeType)
            let options = {
                'targetConfirms': ['确认目标', '确认人'],
                'resultInput': ['录入结果', '录入人'],
                'scoreSelf': ['自评', ''],
                'scoreEachOther': ['互评', '互评人'],
                'scores': ['评分', '评分人'],
                'reviews': ['审批', '审批人'],
                'cc': ['抄送', '抄送人']
            }
            this.dialogTitle = options[nodeType][0]
            this.formLabel = options[nodeType][1]
            this.nodeType = nodeType; // 节点类型
            this.batchHandleDialog = true;
        },

        // 打开编辑规则内容弹框
        editContent(index, content, indicatorId) {
            this.selectIndex = index;
            this.content = content;
            this.selectIndicatorId = indicatorId;
            this.showEditContent = true
        },

        finishEditContent(content) {
            this.tableData[this.selectIndex].content = content
        },
        
        // 获取模板详情
        get_template_detail() {
            this.$axiosUser("get", `/performance/template/info/${this.user_info.site_id}/` + this.templateId).then(res => {
                let { data: { data: { title, flow } } } = res
                this.templateTitle = title || '默认标题'
                this.title = title || '默认标题'
                this.flowInfo = flow || {}
            })
        },

        // 获取表格数据
        get_table_data() {
            this.loading = true
            this.$axiosUser("get", `/performance/indicator/list/${this.user_info.site_id}/` + this.templateId).then(res => {
                this.loading = false
                this.tableData = res.data.data.list
            })
        },


        editTableData() {
        },
        // 编辑模板标题
        editTitle() {
            let title = this.title
            if (title !== null && title !== '') {
                let url = `/performance/template/title/${this.user_info.site_id}`
                this.$http.post(url, { templateId: this.templateId, title }).then(res => {
                    if (res.code == 1) {
                        this.$refs.popoverRef && this.$refs.popoverRef.doClose();
                        this.get_template_detail();
                    }
                    
                })
            }
        },

        // 编辑指标名称，规则，权重，目标，单位
        handleEdit(props, value, id) {
            let url = '', data = {};
            url = `/performance/indicator/${props}/${this.user_info.site_id}/${this.templateId}`;
            data[props] = value;
            data['indicatorId'] = id;
            this.$http.post(url, data).then(res => {
                if(res.code == 0) return this.$message.error(res.msg || '操作失败')
            })
        },

        handleBtnClick(index, node, row) {
            this.handleStatusChange(index, row, node.type)
        },

        // 自评节点单独操作
        handleScoreSelf(row, index) {
            let { indicatorId, flow: { nodes } } = row
            let data = {
                indicatorId, // 指标ID
                nodes
            }
            let url = `/performance/indicator/flow/${this.user_info.site_id}/${this.templateId}`
            this.$http.post(url, data).then(res => {
                let { code, data } = res
                if (code == 1) {
                    this.tableData.splice(index, 1, data); //替换元素
                    this.$message.success("操作成功");
                } else {
                    this.$message.error(res.message || '操作失败');
                }
            })
        },

        // 操作节点
        handleStatusChange(index, row, nodeType) {
            if (index !== -1) this.tagIndex = index // 子节点索引
            this.currentIndicator = row;
            let { indicatorId } = row;
            this.selectIndicatorId = indicatorId; // 指标ID
            this.selectNodes = row.flow.nodes; // 所有节点
            this.nodeType = nodeType; // 节点类型
            if (nodeType == 'targetConfirms') {
                this.dialogTitle = "确认目标"
                this.formLabel = "确认人"
                this.targetConfirms = true;
            }
            if (nodeType == 'resultInput') {
                this.dialogTitle = "录入结果11"
                this.formLabel = "录入人"
                this.resultInput = true;
            }
            if (nodeType == 'scoreSelf') {
                this.dialogTitle = "自评"
            }
            if (nodeType == 'scoreEachOther') {
                this.dialogTitle = "互评"
                this.formLabel = "互评人"
                this.scoreEachOther = true
            }
            if (nodeType == 'scores') {
                this.dialogTitle = "评分"
                this.formLabel = "评分人"
                this.scores = true

            }
            if (nodeType == 'reviews') {
                this.dialogTitle = "审批"
                this.formLabel = "审批人"
                this.reviews = true
            }
            if (nodeType == 'cc') {
                this.dialogTitle = "抄送"
                this.formLabel = "抄送人"
                this.cc = true
            }
            // this.dialogVisible = true;
        },


        // 添加指标
        addData() {
            let url = `/performance/indicator/create/${this.user_info.site_id}/${this.templateId}`
            this.$http.post(url, {}).then(res => {
                let { data, code } = res
                if (code) this.tableData.push(data)
            })
        },

        handleSelectChange(val) {
            this.multipleSelection = val;
        },
        // 取消删除
        cancelDelete() {
            console.log("取消删除");
        },
        // 确认删除
        confirmDelete() {
            if (this.multipleSelection && this.multipleSelection.length > 0) {
                this.$confirm('确定删除选中的指标吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    // 创建一个包含异步任务的数组，每个任务都是一个 axios 请求
                    const arrays = []
                    this.multipleSelection.forEach(item => {
                        arrays.push(this.deleteIndicator(item))
                    })

                    // 当所有请求都成功完成时，responses 是一个包含所有响应的数组
                    Promise.all(arrays).then(responses => {
                        // console.log(responses)
                        this.get_table_data();
                    }).catch(error => {
                        // 如果任何一个请求失败，将会进入这个 catch 块
                        console.log(error)
                    })
                }).catch(() => { });
            }
            
        },
        // 删除指标
        deleteIndicator(item) {
            let url = `/performance/indicator/remove/${this.user_info.site_id}/${this.templateId}/${item.indicatorId}`
            return this.$axiosUser('post', url).then(res => {
                // if (res.data.code == 1) this.get_table_data();
                return res.data
            })
        },
        // 打开计算公式弹框
        openFormula(row, index) {
            this.currentIndicator = null;
            this.selectIndex = -1;
            this.currentIndicator = row;
            this.selectIndex = index;
            this.showFormula = true;
        },
        // 关闭编辑计算公式弹框
        closeDialog() {
            
        },

        // 全选复选框事件监听
        checkAllChangeFn(val) {
            if (val) {
                // 全选
                this.tableColumn.forEach(item => {
                    item.isShow = true
                })
            } else {
                // 反全选
                this.tableColumn.forEach(item => {
                    if (this.flowColumn.includes(item.label)) {
                        item.isShow = false;
                    } else {
                        item.isShow = true
                    }
                })
            }
            this.showPopover();
        },
        // 重置，flag: Boolean，全部重置为flag
        reset(flag) {
            this.tableColumn.forEach(item => {
                if (this.flowColumn.includes(item.label)) {
                    item.isShow = false;
                } else {
                    item.isShow = true
                }
            })
            this.showPopover();
            this.refreshTable();
        },
        // 表格列是否显示的方法
        showColumn(currentColumn) {
            return this.tableColumn.find(item => item.prop == currentColumn).isShow;
        },
        /* 选择列 */
        changeColumns(val) {
            this.tableColumn.forEach(item => {
                item.isShow = false;
            })
            // columns将val数组存在的值设为true，不存在的设为false
            val && val.forEach(item => {
                let current = this.tableColumn.find(i => i.label == item)
                current.isShow = true;
            })
            // 判断是否全选
            this.judgeIsCheckAll();
            // this.refreshTable();
        },
        // 重新渲染表格
        refreshTable() {
            this.$nextTick(() => {
                if (this.$refs.fmeaTableRef) this.$refs.fmeaTableRef.doLayout();
            })
        },
        // 气泡框出现
        showPopover() {
            this.checkColumns = []
            this.tableColumn.forEach(item => {
                if (item.isShow) {
                    this.checkColumns.push(item.label)
                }
            })
            // 判断是否全选
            this.judgeIsCheckAll();
        },
        // 判断是否全选
        judgeIsCheckAll() {
            // 选中的长度 = 表格列的长度  全选按钮就选中
            if (this.checkColumns.length == this.tableColumn.length)
                this.checkAll = true
            else
                this.checkAll = false
        },
        
        finishHandle(nodes) {
            let data = nodes
            let url = `/performance/indicator/flow/${this.user_info.site_id}/${this.templateId}`
            this.$http.post(url, data).then(res => {
                let { code, data } = res
                if (code == 1) {
                    let { indicatorId } = this.currentIndicator;
                    let index = this.tableData.findIndex(table => table.indicatorId === indicatorId)
                    this.tableData.splice(index, 1, data); //替换元素
                    this.$message.success("操作成功");
                    this.nodeType = ''
                    this.dialogTitle = ''
                    this.selectNodes = []
                    this.currentIndicator = []
                    this.selectIndicatorId = ''
                    this.tagIndex = -1
                } else {
                    this.$message.error(res.message || '操作失败');
                }
            })
        },

        // 批量操作成功
        finishBatchHandle(data) {
            this.flowInfo = data;
            this.get_table_data();
        },

        // 编辑计算公式确定的回调
        onFormulaConfirm(formulas) {
            let url = `/performance/indicator/expression/${this.user_info.site_id}/${this.templateId}`;
            let { indicatorId } = this.currentIndicator;
            let params = {
                indicatorId,
                expression: {
                    formulas: formulas.map(item => {
                        return {
                            condition: item.condition,
                            expression: item.expression
                        }
                    })
                }
            }
            this.$http.post(url, params).then(res => {
                let { data, code } = res
                if (code) {
                    this.tableData.splice(this.selectIndex, 1, data); //替换元素
                }
            })
        },
        // 发布考核
        publish() {
            this.showPublish = true;
        },
        // 发布考核弹框的回调
        onPubishConfirm(params) {
            let templateId = this.templateId;
            let { title, startDate, endDate, cycleType, employeeIds, okrs, cateId } = params
            let employees = employeeIds.map(employee => ({
                employeeId: employee,
                ids: [],
                interviewFlow: {
                    nodes: [
                        {
                            id: "IT_1894283564934688769",
                            type: "interview",
                            allows: [],
                            enable: false,
                            weight: 0,
                            children: [],
                            assigneeIds: [],
                            leaderLevel: 1,
                            assigneeType: "self",
                            multipleType: "or"
                        }
                    ]
                }
            }))

            let requireParams = {
                title,
                cycleType,
                startDate,
                endDate,
                okrs,
                templates: [
                    {
                        templateId,
                        employees
                    }
                ],
                cateId
            }
            // let url = `/performance/review/publish/${this.user_info.site_id}`;
            // console.log(requireParams)
            let url = `/performance/review/publish/templates/${this.user_info.site_id}`;
            this.loading = true
            this.$http.post(url, requireParams).then(res => {
                console.log(res)
                let { data, code } = res
                this.loading = false
                if (code == 1) {
                    this.$message.success("发布成功");
                    setTimeout(() => {
                        this.$router.go(-1)
                    }, 1000);
                }
            })
        }
    }
};
</script>

<style lang="scss">
.box {
    .el-switch__core {
        width: 30px !important;
        height: 16px;
    }

    .el-switch__core::after {
        width: 14px;
        height: 14px;
        margin-top: -1px;
    }

    .el-switch.is-checked .el-switch__core::after {
        margin-left: -15px;
    }
}
</style>
<style scoped="scoped" lang="scss">
.oneLine {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.box {
    padding: 0 20px;
    font-size: 14px;
    background-color: #fff;
    box-sizing: border-box;
    border-radius: 4px;

    /* 设置滚动条的宽度和背景色 */
    ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
        width: 10px;
        height: 10px;
        background-color: #f9f9f9;
    }

    /* 设置滚动条滑块的样式 */
    ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
        border-radius: 6px;
        background-color: #c1c1c1;
    }

    /* 设置滚动条滑块hover样式 */
    ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
        background-color: #a8a8a8;
    }

    /* 设置滚动条轨道的样式 */
    ::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
        box-shadow: inset 0 0 5px rgba(87, 175, 187, 0.1);
        border-radius: 6px;
        background: #ededed;
    }

    /*头部样式*/
    .header-content {
        position: relative;
        box-sizing: border-box;
        height: 60px;
        justify-content: space-between;

        .header-left {
            width: 230px;
            box-sizing: border-box;
            height: 60px;
            cursor: pointer;

            .el-icon-arrow-left {
                font-size: 22px;
            }

            &:hover {
                .el-icon-arrow-left {
                    background-color: #f5f7fa;
                    color: #222;
                }
            }

            .text {
                font-size: 16px;
                font-weight: 600;
                padding-left: 50px;

                &::before {
                    position: absolute;
                    content: '';
                    width: 1px;
                    height: 36px;
                    background-color: #ebebeb;
                    left: 44px;
                    top: 50%;
                    margin-top: -18px;
                }
            }

        }

        .header-right {
            width: 230px;
            text-align: right;
        }
    }

    .plus-button {
        display: block;
        margin: 20px auto;
    }

}
</style>
