<template>
    <div class="earlyWarningRules">
        <div class="earlyWarningRulesBtn">
            <div class="collectSeach" :style="$utils.collectSeachSty()">
                <div class="exceed">
                    <span class="exceedSpan">业务属性：</span>
                    <el-select v-model="businessStr" placeholder="请选择业务属性" clearable >
                        <el-option
                        v-for="item in binSectionoptions"
                        :key="item.id"
                        :label="item.sectionName"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </div>
                <div class="exceed">
                    <span class="exceedSpan" style="width:100px">预警名称：</span>
                    <el-input v-model="indicatorStr" placeholder="请输入预警名称"></el-input>
                </div>
                <seachs @handleSeach="getSeachData" @handleRest="reset"></seachs>
            </div>
            <div class="PeriodBtn" :style="$utils.PeriodBtnSty()">
                <btns
                :showImport="false"
                :showExport="false"
                :showAdd="$utils.havePurview('earlyWarningRules:oneLevel:add')"
                :showSave="false" :showDelete="false"
                :disSave="true" :disDelete="true" :disImport="true" :disExport="true"
                @handleAdd="handleAdd"
                ></btns>
            </div>
            <div class="earlyWarningRulesTableData">
                <el-table :data="earlyWarningRulesData" style="width: 100%" @row-dblclick="handleEdit" :class="warningTableSty()">
                    <el-table-column label="序号" type="index" align="center" />
                    <el-table-column label="预警名称" prop="ruleName" />
                    <el-table-column label="业务属性" prop="sectionName"  width="200" />
                    <el-table-column label="指标名称" prop="indicatorName" />
                    <el-table-column label="预警类型" prop="type">
                        <template #default="scope">
                            <span v-if="scope.row.type === 'YDKP'" style="font-size: 12px;">月度考评</span>
                            <span v-else-if="scope.row.type === 'JDKP'" style="font-size: 12px;">季度考评</span>
                            <span v-else style="font-size: 12px;">年度考评</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="预警公式" prop="expression" />
                    <el-table-column label="描述">
                        <template #default="scope">
                            <el-tooltip
                                class="box-item"
                                effect="customized"
                                :content="scope.row.ruleDes"
                                placement="top"
                            >
                                <span class="tooltipCC">{{scope.row.ruleDes}}</span>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                        <template #default="scope">
                            <p class="indicitem" @click="handleDelete(scope.row)">删除</p>
                        </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>
            <el-dialog :title="title" v-model="dialogVisible" width="60vw" :close-on-click-modal="false">
                <div class="periodFrom">
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" :validate-on-rule-change="false">
                        <el-form-item label="预警名称" prop="ruleName">
                            <el-input v-model="ruleForm.ruleName" placeholder="请输入预警名称"></el-input>
                        </el-form-item>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="业务属性" prop="binSection">
                                    <el-select v-model="ruleForm.binSection" placeholder="请选择业务属性" :disabled="isSave" @change="changeBinstation">
                                        <el-option
                                        v-for="item in binSectionoptions"
                                        :key="item.id"
                                        :label="item.sectionName"
                                        :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="指标名称" prop="indicatorId">
                                    <!-- multiple collapse-tags -->
                                    <el-select v-model="ruleForm.indicatorId" placeholder="请选择指标名称"
                                    @change="changeIndication"
                                     :disabled="isSave">
                                        <el-option
                                        v-for="item in indicItemoptions"
                                        :key="item.id"
                                        :label="item.indicatorName"
                                        :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="预警等级" prop="warningLevel">
                                    <el-select v-model="ruleForm.warningLevel" placeholder="请选择预警等级">
                                        <el-option
                                        v-for="item in warningLeveloptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="预警类型" prop="warningType">
                                    <el-select v-model="ruleForm.warningType" placeholder="请选择预警类型">
                                        <el-option
                                        v-for="item in warningTypeoptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="触发时间" prop="warningDate">
                                    <el-row style="width:100%">
                                        <el-col :span="22">
                                            <el-date-picker
                                                v-model="ruleForm.warningDate"
                                                value-format="YYYY-MM-DD"
                                                type="date"
                                                placeholder="请选择触发时间"
                                            />
                                        </el-col>
                                        <el-col :span="2" class="questionIcon">
                                            <el-popover
                                                placement="right-start"
                                                title="提示"
                                                :width="200"
                                                trigger="hover"
                                            >
                                            <div>
                                                <p>预警类型为年度：表示每年的今天执行;</p>
                                                <p>预警类型为季度：1,4,7,10月份表示每个季度的第一个月执行,2,5,8,11月份表示每个季度的第二个月执行,3,6,9,12月份表示每个季度的第三个月执行;</p>
                                                <p>预警类型为月度：表示每个月的今天执.</p>
                                            </div>
                                                <template #reference>
                                                    <el-icon :size="20" color="#3B7AD1"><QuestionFilled /></el-icon>
                                                </template>
                                            </el-popover>
                                        </el-col>
                                    </el-row>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="是否启用">
                                    <el-switch v-model="ruleForm.isEnable" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12" class="earlyWarningRight">
                                <el-form-item label="规则配置">
                                    <el-tabs type="border-card">
                                        <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="multipleSelectionArr"
                                            >
                                                <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, 'operator')"
                                                style="width: 60px; margin: 7px 12px; height: 40px; border: 1px solid #409EFF;"
                                                >
                                                {{ item }}
                                                </el-button>
                                            </el-button-group>
                                        </el-tab-pane>
                                    </el-tabs>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="规则公式" prop="representation">
                                    <div style="display:flex">
                                        <span style="font-size: 14px;color: #F65177;font-weight:blod">
                                            *可双击左侧规则配置辅助写公式,符合Excel规则
                                        </span>
                                    </div>
                                    <el-input
                                    type="textarea"
                                    rows="16"
                                    v-model="ruleForm.representation"
                                    id="representation"
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="描述" prop="desc">
                            <el-input v-model="ruleForm.desc" :rows="5" type="textarea" placeholder="请输入描述"></el-input>
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="saveevaluscoringruleMsg('ruleForm')">确 定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import btns from '../elbuttonS.vue'
import seachs from '../seachGroup.vue'
import {apiGetevaluationWarningruleList, apiGetindicatorListAll, apiGetfunctionList,apiGetIndidicList,
apiGetbinsectionList, apiGetevaluationWarningSave, apiPostevaluationwarningruleDelete} from '../../api/api'
export default {
  components: { btns,seachs },
    data() {
        return {
            dialogVisible: false,
            title: '',
            indicItemoptions: [],
            childerindicItemoptions: [],
            warningLeveloptions: [],
            warningTypeoptions: [],
            binSectionoptions: [],
            indicatorStr: '',
            businessStr: '',
            rowdataMsg: {},
            isSave: false,
            funcMsg: [],
            operator: [],
            multipleSelectionArr: [],
            ruleForm: {
                ruleName: '',
                binSection: '',
                indicatorId: '',
                warningLevel: '',
                warningType: '',
                warningDate: '',
                isEnable: true,
                representation: '',
                desc: ''
            },
            rules: {
                ruleName: [
                    { required: true, message: '请输入预警名称', trigger: 'blur' }
                ],
                binSection: [
                    { required: true, message: '请选择业务属性', trigger: 'change' }
                ],
                indicatorId: [
                    { required: true, message: '请选择指标名称', trigger: 'change' }
                ],
                warningLevel: [
                    { required: true, message: '请选择预警等级', trigger: 'change' }
                ],
                warningType: [
                    { required: true, message: '请选择预警类型', trigger: 'change' }
                ],
                warningDate: [
                    { required: true, message: '请选择触发时间', trigger: 'change' }
                ],
                representation: [
                    { required: true, message: '请输入公式', trigger: 'blur' }
                ],
                desc: [
                    { required: true, message: '请输入描述', trigger: 'blur' }
                ]
            },
            earlyWarningRulesData:[],
            page:{
                pagesize: 12,
                currentPage: 1,
                total: 0
            },
            winPix: window.devicePixelRatio,
            innerWidth: window.innerWidth
        }
    },
    created() {
        this.warningLeveloptions = [
            {
                label: '高',
                value: 3
            },
            {
                label: '中',
                value: 2
            },
            {
                label: '低',
                value: 1
            }
        ]
        this.warningTypeoptions = [
            {
                label: '年度考评',
                value: 'NDKP'
            },
            {
                label: '季度考评',
                value: 'JDKP'
            },
            {
                label: '月度考评',
                value: 'YDKP'
            }
        ]
        this.getEvalscoringData()
        this.getDataDictionary()
        this.getEvaluationData()
        this.getFunData()
        this.operator = ["+", "-", "*", "/", "(", ")", ">", ">=", "<", "<=", "==", "!=",
            "&&", "||", "!", "%", "true", "false", ".", ]
    },
    methods:{
        // 查询预警规则数据
        getEvalscoringData() {
            let that = this
            let params = {
                pageNum: that.page.currentPage,
                pageSize: that.page.pagesize,
                ruleName: that.indicatorStr,
                binSection: that.businessStr
            }
            apiGetevaluationWarningruleList(params).then(datas =>{
                if (datas && datas.data) {
                    that.earlyWarningRulesData = datas.data.records
                    that.page.total = datas.data.total
                }
            })
        },
        // 函数查询
        getFunData() {
            let that = this
            apiGetfunctionList().then(datas =>{
                if (datas && datas.data) {
                    that.funcMsg = datas.data
                }
            })
        },
        // 查询模块
        getDataDictionary() {
            let that = this
            apiGetbinsectionList().then(datas =>{
                if (datas && datas.data) {
                    that.binSectionoptions = datas.data
                }
            })
        },
        changeIndication(val) {
            let that = this
            that.multipleSelectionArr = []
            let params = {
                indicatorId: val
            }
            apiGetIndidicList(params).then(datas =>{
                if (datas) {
                    that.multipleSelectionArr = datas
                }
            })
        },
        tabFuncRowClickHandle(row) {
            let elInput = null
            elInput = document.getElementById("representation");
            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, type) {
            let elInput = null
            elInput = document.getElementById("representation");
            let startPos = elInput.selectionStart;
            let endPos = elInput.selectionEnd;
            if (startPos === undefined || endPos === undefined) return;
            let txt = elInput.value;
            // let txtSplit = '['+val+']';
            let txtSplit = ''
            if (type === 'operator') {
                txtSplit = val
            } else {
                txtSplit = '['+val+']'
            }
            let result = txt.substring(0, startPos) + txtSplit + txt.substring(endPos);
            elInput.value = result;
            this.ruleForm.representation = result
            elInput.focus();
            elInput.selectionStart = startPos + txtSplit.length;
            elInput.selectionEnd = startPos + txtSplit.length;
        },
        changeBinstation(val) {
            this.ruleForm.indicatorId = ''
            this.indicItemoptions = []
            this.getEvaluationData(val)
        },
        // 查询指标数据
        getEvaluationData(val) {
            let that = this
            let params = {
                binSection: val
            }
            apiGetindicatorListAll(params).then(datas =>{
                if (datas && datas.data) {
                    that.indicItemoptions = datas.data
                }
            })
        },
        handleAdd() {
            this.dialogVisible = true
            this.isSave = false
            this.title = '新增考评预警规则'
            this.$nextTick(() =>{
                this.ruleForm = {
                    ruleName: '',
                    binSection: '',
                    indicatorId: '',
                    warningLevel: '',
                    warningType: '',
                    warningDate: '',
                    isEnable: true,
                    representation: '',
                    desc: ''
                }
            })
        },
        handleEdit(row) {
            this.dialogVisible = true
            this.isSave = true
            this.title = '修改考评预警规则'
            this.rowdataMsg = row
            this.ruleForm = {
                ruleName: row.ruleName,
                binSection: row.binSection,
                indicatorId: row.indicatorId,
                warningLevel: row.grade,
                warningType: row.type,
                warningDate: row.cronTime,
                isEnable: row.enable,
                representation: row.expression,
                desc: row.ruleDes
            }
            this.getEvaluationData(row.binSection)
        },
        saveevaluscoringruleMsg(formName) {
            let that = this
            that.$refs[formName].validate((valid) => {
                if (valid) {
                    that.saveAndEditIndicatorData()
                }
            });
        },
        //新增/修改指标数据
        saveAndEditIndicatorData() {
            let that = this
            let params = {
                ruleName: that.ruleForm.ruleName,
                binSection: that.ruleForm.binSection,
                indicatorId: that.ruleForm.indicatorId,
                grade: that.ruleForm.warningLevel,
                type: that.ruleForm.warningType,
                cronTime: that.ruleForm.warningDate+' 00:00:00',
                enable: that.ruleForm.isEnable,
                expression: encodeURI(that.ruleForm.representation),
                ruleDes: that.ruleForm.desc
            }
            if (that.isSave) {
                let evalradio = that.rowdataMsg
                params.id = evalradio.id
            }
            apiGetevaluationWarningSave(params).then(datas =>{
                if (!that.isSave) {
                    that.$message({
                        message: '考评预警规则新增成功',
                        type: 'success'
                    });
                } else {
                    that.$message({
                        message: '考评预警规则修改成功',
                        type: 'success'
                    });
                }
                that.dialogVisible = false
                that.getEvalscoringData()
            })
        },
        //删除指标数据
        handleDelete(row) {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let that = this
                let params = {
                    id: row.id
                }
                apiPostevaluationwarningruleDelete(params).then(datas =>{
                    if (datas) {
                        that.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        that.getEvalscoringData()
                    }
                })
            })
        },  
        showCounter() {
            this.$refs.counter.init(this.ruleForm.optionName)
        },
        counterStr(val) {
            this.ruleForm.optionName = val
        },
        getSeachData() {
            this.page.currentPage = 1
            this.getEvalscoringData()
        },
        reset() {
            this.page.currentPage = 1
            this.indicatorStr = ''
            this.businessStr = ''
            this.getEvalscoringData()
        },
        handleSizeChange(val){
            this.page.pagesize = val
            this.getEvalscoringData()
        },
        handleCurrentChange(val){
            this.page.currentPage =val
            this.getEvalscoringData()
        },
        warningTableSty() {
            if (this.winPix === 1.25 || this.innerWidth < 1800) {
                return 'warning125Table'
            } else {
                return 'warning100Table'
            }
        }
    }
}
</script>

<style lang="less">
.earlyWarningRules{
    .earlyWarningRulesBtn{
        .collectSeach{
            display: flex;
            padding: 24px 20px;
            border-bottom: 1px solid#D6DBEA;
                .exceed{
                    display: flex;
                    .exceedSpan{
                        width: 75px;
                        height: 12px;
                        font-size: 14px;
                        font-family: Microsoft YaHei;
                        font-weight: 400;
                        color: #8991B0;
                        line-height: 12px;
                        margin-top: 14px;
                    }
                    .el-input{
                        margin-right:10px;
                        .el-input__inner{
                            height:40px;
                        }
                        .el-input__suffix{
                            .el-select__caret{
                                line-height:30px;
                            }
                        }
                    }
                }
                .el-select{
                    margin-right:10px;
                    .el-input__inner{
                        height:30px;
                    }
                    .el-input__suffix{
                        .el-select__caret{
                            line-height:30px;
                        }
                    }
                }
        }
        span{
            font-size:14px;
        }
        .PeriodBtn{
            display: flex;
            justify-content: flex-end;
            padding: 20px 0;
        }
        .el-button{
            height: 30px;
            // width:100px;
            padding: 0 30px ;
            // padding-top: 8px;
            span{
                margin:0;
            }
        }
    }
    .earlyWarningRulesTableData{
        .warning125Table{
            .el-table__body-wrapper{
                height: 53vh !important;
            }
        }
        .warning100Table{
            .el-table__body-wrapper{
                height: 60vh !important;
            }
        }
        .el-table{
            .el-input__inner{
                height: 30px !important;
            }
            .el-radio__label{
                display: none;
            }
            .tooltipCC{
                width: 400px;
                display: inline-block;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
            .indicitem{
                color: #409EFF;
                font-size: 12px;
                margin-right: 20px;
                cursor:pointer;
                &:hover{
                    text-decoration: underline;
                }
            }
        }
        .el-pagination{
            margin-top: 20px;
            text-align: end;
            position: relative;
        }
    }
    .el-overlay{
        .el-dialog{
            margin-top: 5vh;
            .el-dialog__body{
                padding: 30px 60px 30px 20px;
                .periodFrom{
                    .el-select, .el-input{
                        width: 100%;
                    }
                    .el-input{
                        height: 30px;
                    }
                    .questionIcon{
                        .el-icon{
                            position: relative;
                            top: 3px;
                            left: 10px;
                        }
                    }
                    .earlyWarningRight {
                        width: 100%;
                        .el-tabs{
                            width: 100%;
                            height: 100%;
                            .el-tabs__content{
                                .el-table{
                                    .el-table__body-wrapper{
                                        .el-checkbox__inner{
                                            border-radius: 10px;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>