<template>
<div class="content-main">
    <el-row class="addBtnBg">
        <el-button type="primary" @click="isEdit=true" size="small" class="iconfont iconbianzhi" :disabled="isEdit"> 编辑</el-button>
        <el-button type="primary" @click="handleSave" size="small" class="iconfont iconbaocun" :disabled="!isEdit"> 保存</el-button>
        <el-button type="primary" @click="handleCancel" size="small" class="iconfont iconquxiao" :disabled="!isEdit"> 取消</el-button>
    </el-row>
    <el-row style="border:2px solid #006bd5;padding:20px;">
        <el-form :model="configData" :inline="true" ref="form1">
            <el-col :span="14" :gutter="20">
                <el-row>
                    <h1>1. 初始得分设置:</h1>
                    <p style="margin-top:20px">设置 <el-form-item prop="initscore" :rules="rule">
                            <el-input v-model="configData.initscore" style="width:150px" :disabled="!isEdit"></el-input>
                        </el-form-item> 分<br>
                        <span class="explain">（说明：企业若无特殊情况，起始得分为，后面在加上每个合同的得分情况，来计算总分；）</span></p>
                </el-row>
                <el-row style="margin-top:10px">
                    <h1>2. 合同得分设置:</h1>
                    <p>条件1： 状态为“履约”时，横向得分公式： <el-input v-model="configData.formula1" disabled style="width:150px"></el-input> <br>
                        <span class="explain">（说明：其中 a 为履约固有分数；b*交易额/c 为交易额得分；c 为基数；）</span><br>
                        a= <el-form-item prop="a" :rules="rule">
                            <el-input style="width:150px" size="small" v-model="configData.a" :disabled="!isEdit"></el-input>
                        </el-form-item><br>
                        b= <el-form-item prop="b" :rules="rule">
                            <el-input style="width:150px" size="small" v-model="configData.b" :disabled="!isEdit"></el-input>
                        </el-form-item><br>
                        c= <el-form-item prop="c" :rules="rule">
                            <el-input style="width:150px" size="small" v-model="configData.c" :disabled="!isEdit"></el-input>
                        </el-form-item><br>
                    </p>
                    <p>条件2： 状态为“部分履约”时，横向得分公式： <el-select :disabled="!isEdit" v-model="configData.formula2" style="width:160px">
                            <el-option v-for="item in formulas" :key="item" :label="item" :value="item"></el-option>
                        </el-select> <span>（说明如上）</span> <br>
                    </p>
                    <p>条件3： 状态为“违约”时，横向得分规定如下：<br>
                        <el-input type="textarea" v-model="condition.default" :autosize="{minRows:2}" disabled></el-input>
                    </p>
                    <p>条件4： 状态为“违规”时，横向得分规定如下：<br>
                        <el-input type="textarea" v-model="condition.violations" :autosize="{minRows:2}" disabled></el-input>
                    </p>
                    <p>条件5： 状态为“终止”时，横向得分规定如下：<br>
                        <el-input type="textarea" v-model="condition.terminate" :autosize="{minRows:2}" disabled></el-input>
                    </p>
                </el-row>
            </el-col>
            <el-col :span="10">
                <el-row>
                    <h1>3. 企业分级设置：</h1>
                    <p>
                        <ul>
                            <li v-for="(item,index) in grades" :key="index">
                                <div style="display:inline-block;width:150px;"><span v-if="index!=0">{{keys[index-1]}} ≤ </span> 企业总得分 <span v-if="index!=keys.length"> ＜ {{keys[index]}} </span>
                                </div>, <el-form :model="item" style="display:inline" ref="form2">
                                    <el-form-item prop="grade" :rules="rule">
                                        <el-input v-model="item.grade" style="width:180px;" :disabled="!isEdit"></el-input>
                                    </el-form-item>
                                </el-form>
                                <span v-show="isEdit">
                                    <span v-if="index<keys.length">
                                        <el-tooltip class="item" effect="light" content="新增" placement="top">
                                            <el-button type="primary" @click="handleAdd(index)" class="operate_show_btn iconfont iconxinzeng" size="small"></el-button>
                                        </el-tooltip>
                                        <el-tooltip class="item" effect="light" content="删除" placement="top" v-if="index>0">
                                            <el-button v-if="true" @click="handleDel(index)" type="primary" class="operate_delete_btn iconfont iconshanchu" size="small"></el-button>
                                        </el-tooltip>
                                    </span>
                                </span>
                            </li>
                        </ul>其中: <span class="explain">（说明: 变量值由小到大填写）</span><br>
                        <ul>
                            <li v-for="(item,index) in values" :key="index">
                                {{keys[index]}} = <el-form :model="item" style="display:inline" ref="form3">
                                    <el-form-item prop="v" :rules="{ trigger: 'change', validator: checkNum }">
                                        <el-input v-model="item.v" style="width:180px;" :disabled="!isEdit" class="check_num" @blur="handleDynaBlur"></el-input>
                                    </el-form-item>
                                </el-form>
                            </li>
                        </ul>
                    </p>
                </el-row>
            </el-col>
        </el-form>
    </el-row>
</div>
</template>

<script>
import {
    confadd,
    confupdate,
    getconfig
} from '@/api/transaction/creditAssess/creditEvaluationRules/index'
const stringify = JSON.stringify.bind(JSON)
const parse = JSON.parse.bind(JSON)
const letters = 'defghijklmnopqrstuvwxyz'
const log = console.log.bind(console)
export default {
    data() {
        return {
            // checkNum: { trigger: 'change', validator: checkNum },
            rule: {
                required: true,
                message: '必填项',
                trigger: 'blur'
            },
            isEdit: false,
            isNew: false,
            paraCode: 1045,
            condition: {
                default: '违约合同的成交时间在去年的1月1日到今天之内的，横向得分：“违约”，企业违约日期之前的总得分清零，企业得分从违约日期开始按照规则累加。',
                violations: '横向得分：“违规”，企业违规日期之前的总得分清零，直到企业违规标志被清除为止。',
                terminate: '横向得分：“合同终止”，横向得分：-0.5。',
            },
            formulas: ['a+b*交易额/c', 'b*交易额/c'],
            configData: {
                initscore: 2,
                formula1: 'a+b*交易额/c',
                formula2: 'b*交易额/c',
                a: 0.02,
                b: 3,
                c: 75000000,
            },
            grades: [{
                grade: 'B级：违规企业'
            }, {
                grade: 'A级：缴纳双倍保证金'
            }, {
                grade: '2A级：正常企业'
            }, {
                grade: '3A级：优质企业'
            }],
            keys: ['d', 'e', 'f'],
            values: [{
                v: 0
            }, {
                v: 2
            }, {
                v: 4
            }]
        }
    },
    created() {
        this.getconfig()
    },
    methods: {
        handleDynaBlur() {
            this.values = this.values.map(item => ({
                v: +item.v + 1
            }))
            setTimeout(() => {
                this.values = this.values.map(item => ({
                    v: +item.v - 1
                }))
            })
        },
        checkNum(rule, value, callback) {
            if (!value && value !== 0) {
                return callback(new Error('必填项'));
            }
            setTimeout(() => {
                if (isNaN(value)) {
                    callback(new Error('请输入数字值'));
                } else {
                    var _vals = this.values.map(item => item.v)
                    var _idx = _vals.indexOf(value)
                    var _left = _vals[_idx - 1]
                    var _right = _vals[_idx + 1]
                    var hasLeft = typeof _left != 'undefined'
                    var hasRight = typeof _right != 'undefined'

                    if (hasLeft && hasRight) {
                        if (_right > value && value > _left) callback()
                        else callback(new Error('变量值应大于前一项,小于后一项'))
                    }
                    if (!hasLeft && hasRight) {
                        if (_right > value) callback()
                        else callback(new Error('变量值应大于前一项,小于后一项'))
                    }
                    if (hasLeft && !hasRight) {
                        if (_left < value) callback()
                        else callback(new Error('变量值应大于前一项,小于后一项'))
                    }
                }
            }, 300)
        },
        handleCancel() {
            this.isEdit = false
            this.getconfig()
        },
        handleAdd(index) {
            console.log(letters.length,this.keys.length,'44512')
            if (this.keys.length >= letters.length) {
                this.$message.error('超过添加限制,请联系管理员')
                return
            }
            this.grades.splice(this.keys.length, 0, {
                grade: ''
            })
            let letter = letters[letters.indexOf(this.keys[this.keys.length - 1]) + 1]
            this.keys.push(letter)
            this.values.splice(this.keys.length, 0, {
                v: ''
            })
        },
        handleDel(index) {
            this.grades.splice(index, 1)
            this.keys.pop()
            this.values.splice(index, 1)
        },
        handleSave() {
            let form1, form2, form3
            let configData = this.configData,
                grades = this.grades
            let values = this.values
            // form1
            for (let key in this.configData) {
                let val = this.configData[key]
                if (!val && val !== 0) {
                    form1 = true;
                    break
                }
            }

            // form2
            let agrades = grades.map(item => item.grade)
            for (let i = 0, l = agrades.length; i < l; i++) {
                if (!agrades[i]) {
                    form2 = true
                    break
                }
            }
            // form3
            let avalues = values.map(item => item.v)
            for (let i = 0, l = avalues.length; i < l; i++) {
                if (!avalues[i] && avalues[i] !== 0) {
                    form3 = true
                    break
                }
            }
            if (form1 || form2 || form3) {
                this.$message.warning('请先填写必填项')
                return
            }
            let params = {
                configNameEn: stringify(this.grades),
                configValue: stringify(this.keys),
                configName: stringify(this.values),
                configLastValue: stringify(this.configData),
                orderBy: '1',
                configCode: this.paraCode + '0001',
                paraCode: this.paraCode
            }
            
            if (this.isNew) {
                this.confadd(params)
                return
            }
            this.confupdate(params)
        },
        confadd(params) {
            confadd(params).then(res => {
                if (res.infoCode === 200) {
                    this.$message.success('保存成功')
                    this.isEdit = false
                    return
                }
                this.$message.error(res.msg)
            })
        },
        confupdate(params) {
            confupdate(params).then(res => {
                if (res.infoCode === 200) {
                    this.$message.success('保存成功')
                    this.getconfig()
                    this.isEdit = false
                    return
                }
                this.$message.error(res.msg)
            })
        },
        getconfig() {
            let self = this
            getconfig(this.paraCode).then(res => {
                if (res.infoCode === 200) {
                    if (res.data.length) {
                        let d = res.data[0];
                        try{
                            self.grades = parse(d.configNameEn)
                            self.keys = parse(d.configValue)
                            self.values = parse(d.configName)
                            self.configData = parse(d.configLastValue)
                        }catch(err){

                        }
                        return
                    }
                    this.isNew = true
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
h1 {
    font-weight: bold;
}

p {
    line-height: 3em;
    padding-left: 2em;

    .explain {
        color: gray;
        font-size: 12px;
    }
}
</style>
