<template>
    <div class="rulesDetail">
        <el-dialog title="考评得分规则详情" v-model="editEvaluaVisible" width="70vw" :close-on-click-modal="false">
            <div class="rulesDetailAll">
                <div class="rulesDetailBtn">
                    <div class="PeriodBtn">
                        <el-row :gutter="10" style="padding-left: 10px;">
                             <!-- v-if="$utils.havePurview('scoringRules:twoLevel:add')" -->
                            <el-col :span="1.5" v-if="$utils.havePurview('scoringRules:twoLevel:add')">
                                <el-button
                                type="primary"
                                size="mini"
                                @click="handleAdd"
                                >
                                <img :src="addW" style="margin-right: 10px">
                                <span>新增</span>
                                </el-button>
                            </el-col>
                             <!-- v-if="$utils.havePurview('scoringRules:twoLevel:save')" -->
                            <el-col :span="1.5" v-if="$utils.havePurview('scoringRules:twoLevel:save')">
                                <el-button
                                type="success"
                                size="mini"
                                @click="handleEdit"
                                :disabled="changeDateSelect.length === 0 || changeDateSelect.length>1"
                                >
                                <img :src="editW" style="margin-right: 10px">
                                <span>修改</span>
                                </el-button>
                            </el-col>
                             <!-- v-if="$utils.havePurview('scoringRules:twoLevel:delete')" -->
                            <el-col :span="1.5" v-if="$utils.havePurview('scoringRules:twoLevel:delete')">
                                <el-button
                                type="danger"
                                size="mini"
                                :disabled="changeDateSelect.length === 0"
                                @click="handleDelete"
                                >
                                <img :src="deleteW" style="margin-right: 10px">
                                <span>删除</span>
                                </el-button>
                            </el-col>
                        </el-row>
                    </div>
                    <div class="rulesDetailTableData">
                        <el-table :data="indicatoroptions" style="width: 100%" @select="rowClick" @select-all="rowClick">
                            <el-table-column type="selection" label="操作" align="center"></el-table-column>
                            <el-table-column label="子指标名称" prop="range" />
                            <el-table-column label="规则公式" prop="regularExpression" />
                            <!-- <el-table-column label="创建者" prop="createBy" />
                            <el-table-column label="创建时间" prop="createTime" /> -->
                            <el-table-column label="规则描述" width="500">
                                <template #default="scope">
                                    <span>{{scope.row.ruleDescription}}</span>
                                </template>
                            </el-table-column>
                        </el-table>
                        <!-- <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="page.currentPage"
                            :page-size="page.pagesize"
                            layout="total, prev, pager, next, jumper"
                            :total="page.total">
                        </el-pagination> -->
                    </div>
                    <div class="onlyDialog">
                        <el-dialog :title="title" v-model="dialogVisible" width="50vw" :close-on-click-modal="false">
                            <div class="periodFrom">
                                <div class="fromLeft">
                                    <el-tabs type="border-card">
                                        <el-tab-pane label="子指标">
                                                <!-- @row-dblclick="rowDbclick" -->
                                            <el-table
                                                size="mini"
                                                :show-header="false"
                                                :highlight-current-row="true"
                                                :stripe="false"
                                                :border="false"
                                                height="240"
                                                ref="multipleTable"
                                                :data="indicItemoptions"
                                                @select-all="onSelectAll"
                                                @selection-change="selectItem"
                                                @row-click="onSelectOp"
                                            >
                                                <el-table-column type="selection" width="55" align="center" />
                                                <el-table-column prop="childName" />
                                                <el-table-column prop="childCode" />
                                            </el-table>
                                        </el-tab-pane>
                                        <el-tab-pane label="指标项">
                                            <el-table
                                                size="mini"
                                                :show-header="false"
                                                :highlight-current-row="true"
                                                :stripe="false"
                                                :border="false"
                                                height="240"
                                                @row-dblclick="rowDbclick"
                                                :data="multipleSelectionObj?multipleSelectionObj.list:[]"
                                            >
                                                <el-table-column prop="optionName" />
                                                <el-table-column prop="optionCode" />
                                            </el-table>
                                        </el-tab-pane>
                                        <el-tab-pane label="函数">
                                            <el-table
                                                size="mini"
                                                fit
                                                :show-header="false"
                                                :highlight-current-row="true"
                                                :stripe="false"
                                                :border="false"
                                                height="240"
                                                @row-dblclick="tabFuncRowClickHandle"
                                                :data="funcMsg"
                                            >
                                                <el-table-column min-width="40%">
                                                    <template #default="scope">
                                                        <el-popover trigger="hover" placement="bottom">
                                                        <p>描述：{{ scope.row.formulaName }}</p>
                                                        <!-- <p>参数：{{ scope.row.param }}</p> -->
                                                        <template #reference>
                                                            <span size="medium" transition="fade-in-linear">{{
                                                            scope.row.formulaName
                                                            }}</span>
                                                        </template>
                                                        </el-popover>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column min-width="60%">
                                                    <template #default="scope">
                                                        <el-popover trigger="hover" placement="bottom">
                                                        <p>描述：{{ scope.row.description }}</p>
                                                        <!-- <p>参数：{{ scope.row.param }}</p> -->
                                                        <template #reference>
                                                            <span size="medium" transition="fade-in-linear">{{
                                                            scope.row.description
                                                            }}</span>
                                                        </template>
                                                        </el-popover>
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                        </el-tab-pane>
                                        <el-tab-pane label="运算符">
                                            <el-button-group>
                                                <el-button
                                                v-for="item in operator"
                                                :key="item"
                                                plain
                                                @click="scorRuleSplit(item)"
                                                style="width: 60px; margin: 7px 12px; height: 40px; border: 1px solid #409EFF;"
                                                >
                                                {{ item }}
                                                </el-button>
                                            </el-button-group>
                                        </el-tab-pane>
                                    </el-tabs>
                                </div>
                                <div class="fromRight">
                                    <div>
                                        <div style="display:flex">
                                            <el-checkbox style="margin-right: 10px" v-model="isrepresentation" @change="changeRep" />
                                            <el-tag style="margin-bottom: 5px">公式</el-tag>
                                        </div>
                                        <el-input
                                        type="textarea"
                                        rows="10"
                                        v-model="itemForm.representation"
                                        id="representation"
                                        />
                                    </div>
                                    <div style="margin-top: 10px">
                                        <div style="display:flex">
                                            <el-checkbox style="margin-right: 10px" disabled v-model="isrange" @change="changeRank" />
                                            <el-tag style="margin-bottom: 5px">子指标名称</el-tag>
                                        </div>
                                        <el-input
                                        type="textarea"
                                        rows="4"
                                        v-model="itemForm.range"
                                        disabled
                                        id="range"
                                        />
                                    </div>
                                </div>
                            </div>
                            <div style="margin-top: 10px">
                                <el-tag style="margin-bottom: 5px">描述</el-tag>
                                <el-input
                                type="textarea"
                                rows="4"
                                v-model="itemForm.desc"
                                />
                            </div>
                            <template #footer>
                                <span class="dialog-footer">
                                    <el-button @click="dialogVisible = false">取 消</el-button>
                                    <el-button type="primary" @click="saverulesDetailMsg()">确 定</el-button>
                                </span>
                            </template>
                        </el-dialog>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import addW from '../../assets/btnIcon/addW.png'
import editW from '../../assets/btnIcon/editW.png'
import deleteW from '../../assets/btnIcon/deleteW.png'
import {apiGetintervaltableList, apiGetindicatorselectByCode, apiGetintervalscoringsaveOrUpdate, apiGetintervalscoringRemove, apiGetfunctionList} from '../../api/api'
export default {
    data() {
        return {
            addW: addW,
            editW: editW,
            deleteW: deleteW,
            editEvaluaVisible: false,
            isSave: false,
            changeDateSelect: [],
            indicatoroptions: [],
            indicItemoptions: [],
            indicItem: '',
            isrepresentation: true,
            isrange: false,
            funcMsg: [],
            operator: [],
            itemForm: {
                representation: '',
                range: '',
                desc: ''
            },
            page:{
                pagesize: 12,
                currentPage: 1,
                total: 0
            },
            evalradio: {},
            rowevalradio: {},
            dialogVisible: false,
            multipleSelection: [],
            multipleSelectionObj: {}
        }
    },
    created() {
        this.operator = ["+", "-", "*", "/", "(", ")", ">", ">=", "<", "<=", "==", "!=",
            "&&", "||", "!", "%", "true", "false", ".", ]
    },
    methods: {
        init(row) {
            this.editEvaluaVisible = true
            this.indicatoroptions = []
            this.indicItemoptions = []
            this.multipleSelection = []
            this.multipleSelectionObj = {}
            this.rowevalradio = row
            this.getrulesDetailData(row)
            this.getindicItemData(row)
            this.getFunData()
        },
        // 函数查询
        getFunData() {
            let that = this
            apiGetfunctionList().then(datas =>{
                if (datas && datas.data) {
                    that.funcMsg = datas.data
                }
            })
        },
        // 查询考评得分规则详情列表
        getrulesDetailData(row) {
            let that = this
            let params = {
                ruleId: row.id
            }
            apiGetintervaltableList(params).then(datas =>{
                if (datas && datas.data) {
                    that.indicatoroptions = datas.data
                    that.changeDateSelect = []
                }
            })
        },
        // 查询指标项条目
        getindicItemData(row) {
            let that = this
            let params = {
                indicatorCede: row.indicatorId
            }
            apiGetindicatorselectByCode(params).then(datas =>{
                if (datas && datas.data) {
                    that.indicItemoptions = datas.data
                    that.multipleSelection = [datas.data[0]]
                    that.multipleSelectionObj = datas.data[0]
                }
            })
        },
        changeRep(val) {
            this.isrange = !val
        },
        changeRank(val) {
            this.isrepresentation = !val
        },
        onSelectAll() {
            this.$refs.multipleTable.clearSelection();
        },
        selectItem(rows) {
            if (rows.length > 1) {
                const newRows = rows.filter((it, index) => {
                if (index == rows.length - 1) {
                    this.$refs.multipleTable.toggleRowSelection(it, true);
                    return true;
                } else {
                    this.$refs.multipleTable.toggleRowSelection(it, false);
                    return false;
                }
                });
                this.multipleSelection = newRows;
            } else {
                this.multipleSelection = rows;
                this.multipleSelectionObj = {}
                this.multipleSelectionObj = rows[0]
            }
        },
        onSelectOp(row) {
            this.$refs.multipleTable.clearSelection();
            this.$refs.multipleTable.toggleRowSelection(row, true);
            this.multipleSelection = [];
            this.multipleSelectionObj = {}
            this.multipleSelectionObj = row;
            debugger
            this.multipleSelection.push(row);
        },
        tabFuncRowClickHandle(row) {
            let elInput = null
            if (this.isrepresentation) {
                elInput = document.getElementById("representation");
            } else {
                elInput = document.getElementById("range");
            }
            let startPos = elInput.selectionStart; //第0个字符到选中的字符
            let endPos = elInput.selectionEnd; //选中字符到末尾字符
            if (startPos === undefined || endPos === undefined) return;
            let txt = elInput.value;
            let func = row.formulaExpresion
            // 将插值添加到选中光标位置
            let result = txt.substring(0, startPos) + func + txt.substring(endPos);
            elInput.value = result;
            elInput.focus();
        },
        rowDbclick(row) {
            this.scorRuleSplit(row.optionCode);
        },
        scorRuleSplit(val) {
            let elInput = null
            if (this.isrepresentation) {
                elInput = document.getElementById("representation");
            } else {
                elInput = document.getElementById("range");
            }
            let startPos = elInput.selectionStart;
            let endPos = elInput.selectionEnd;
            if (startPos === undefined || endPos === undefined) return;
            let txt = elInput.value;
            let txtSplit = val;
            let result = txt.substring(0, startPos) + txtSplit + txt.substring(endPos);
            elInput.value = result;
            elInput.focus();
            elInput.selectionStart = startPos + txtSplit.length;
            elInput.selectionEnd = startPos + txtSplit.length;
        },
        handleAdd() {
            this.dialogVisible = true
            this.isSave = false
            this.title = '新增指标项管理'
            this.$nextTick(() =>{
                this.itemForm = {
                    representation: '',
                    range: '',
                    desc: ''
                }
                this.multipleSelectionObj = this.indicItemoptions[0]
                this.$refs.multipleTable.toggleRowSelection(this.indicItemoptions[0], true);
            })
        },
        handleEdit() {
            this.dialogVisible = true
            this.isSave = true
            this.title = '修改指标项管理'
            this.evalradio = this.changeDateSelect[0]
            this.$nextTick(() =>{
                this.indicItemoptions.forEach(it =>{
                    if (this.evalradio.childCode === it.childCode) {
                        this.multipleSelectionObj = it
                        this.$refs.multipleTable.toggleRowSelection(it, true);
                    }
                })
                this.itemForm = {
                    representation: this.evalradio.regularExpression,
                    range: this.evalradio.range,
                    desc: this.evalradio.ruleDescription
                }
            })
        },
        saverulesDetailMsg() {
            let that = this
            let repre = document.getElementById("representation").value
            // let range = document.getElementById("range").value   range === '' || 
            if (repre === '' || that.itemForm.desc === '') return
            that.saveAndEditIndicatorData()
        },
        //新增/修改指标数据
        saveAndEditIndicatorData() {
            let that = this
            let params = {
                ruleId: that.rowevalradio.id,
                regularExpression: encodeURI(document.getElementById("representation").value),
                // range: encodeURI(document.getElementById("range").value),
                range: that.multipleSelection[0].childName,
                ruleDescription: that.itemForm.desc,
                childCode: that.multipleSelection[0].childCode
            }
            if (that.isSave) {
                params.id = that.evalradio.id
            }
            apiGetintervalscoringsaveOrUpdate(params).then(datas =>{
                if (!that.isSave) {
                    that.$message({
                        message: '指标项新增成功',
                        type: 'success'
                    });
                } else {
                    that.$message({
                        message: '指标项修改成功',
                        type: 'success'
                    });
                }
                that.dialogVisible = false
                that.getrulesDetailData(that.rowevalradio)
            })
        },
        //删除指标数据
        handleDelete() {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let that = this
                let paramsArr = []
                that.changeDateSelect.forEach(it =>{
                    paramsArr.push(it.id)
                })
                apiGetintervalscoringRemove(paramsArr.join(',')).then(datas =>{
                    that.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    that.changeDateSelect = []
                    that.getrulesDetailData(that.rowevalradio)
                })
            })
        },        
        rowClick(selection, row) {
            this.changeDateSelect = selection
        },
        getSeachData() {
            this.page.currentPage = 1
            this.getrulesDetailData(this.rowevalradio)
        },
        resetSeach() {
            this.page.currentPage = 1
            this.indicItem = ''
            this.getrulesDetailData(this.rowevalradio)
        },
        handleSizeChange(val){
            this.page.pagesize = val
        },
        handleCurrentChange(val){
            this.page.currentPage =val
        },
    }
}
</script>

<style lang="less">
.rulesDetail{
    .el-overlay{
        .el-dialog{
            margin-top: 5vh !important;
            .el-dialog__body{
                padding: 0 20px 30px 20px !important;
                .rulesDetailAll{
                    .el-select, .el-input{
                        width: 100%;
                    }
                    .rulesDetailBtn{
                        padding: 10px 20px 0 20px;
                        .PeriodBtn{
                            display: flex;
                            justify-content: end;
                            padding: 20px 0;
                            .is-disabled{
                                opacity: 0.5;
                            }
                        }
                    }
                    .rulesDetailTableData{
                        .el-table{
                            .el-table__body-wrapper{
                                height: 55vh !important;
                            }
                            .el-input__inner{
                                height: 30px !important;
                            }
                            .el-radio__label{
                                display: none;
                            }
                        }
                        .el-pagination{
                            margin-top: 20px;
                            text-align: end;
                            position: relative;
                        }
                    }
                    .onlyDialog{
                        .el-overlay{
                            .el-dialog{
                                margin-top: 10vh !important;
                                .el-dialog__body{
                                    padding: 20px !important;
                                }
                                .periodFrom{
                                    display: flex;
                                    .fromLeft{
                                        width: 55%;
                                        margin-right: 20px;
                                        .el-tabs{
                                            height: 100%;
                                            .el-tabs__content{
                                                .el-table{
                                                    .el-table__body-wrapper{
                                                        .el-checkbox__inner{
                                                            border-radius: 10px;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    .fromRight{
                                        width: 43%;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            .el-dialog__footer{
                .dialog-footer{
                    display: flex;
                    justify-content: center;
                    .el-button{
                        width: 180px !important;
                        height: 40px !important;
                    }
                }
            }
        }
    }
}
</style>