<template>
    <div class="ls-vertical">
        <navbar icon="back" title="运营指标评估" :buttons="isPreview ? [] : btns" @clickbutton="clickbtn"></navbar>
        <div class="ls-container main-container">
            <div class="ls-btn-row"></div>
            <el-form :model="headerInfo" ref="formRef" label-position="left" label-width="110px" size="mini" :rules="rules">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="规则编号">
                            <el-input v-model="headerInfo.gradeNo" placeholder="系统生成,无需输入" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="规则类型" prop="type">
                            <el-select v-model="headerInfo.type" placeholder="请选择" filterable clearable :disabled="isPreview || this.paramForm.action == 'UPDATE'" @change="typeSelectChanged">
                                <el-option v-for="(item, i) in gradeTypes" :key="i" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="规则标题" prop="title">
                            <el-input v-model="headerInfo.title" placeholder="请输入" :disabled="isPreview" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="客户属性" prop="custType">
                            <el-select v-model="headerInfo.custType" multiple placeholder="请选择" filterable clearable :disabled="isPreview">
                                <el-option v-for="(item, i) in custTypes" :key="i" :label="item.key" :value="item.vaule">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="客户等级">
                            <el-select v-model="headerInfo.grades" multiple placeholder="请选择" filterable clearable :disabled="isPreview">
                                <el-option v-for="(item, i) in custGrades" :key="i" :label="item.grade" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="业务范围" prop="range">
                            <el-select v-model="headerInfo.range" placeholder="请选择" filterable clearable :disabled="isPreview">
                                <el-option v-for="(item, i) in businessScope" :key="i" :label="item.key" :value="item.vaule">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="客户状态">
                            <el-select v-model="headerInfo.cmStatus" placeholder="请选择" filterable clearable :disabled="isPreview" multiple>
                                <el-option v-for="(item, i) in custStatus" :key="i" :label="item.key" :value="item.vaule">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="客户审批状态">
                            <el-select v-model="headerInfo.cmAuditStatus" placeholder="请选择" filterable clearable :disabled="isPreview" multiple>
                                <el-option v-for="(item, i) in approveStatus" :key="i" :label="item.key" :value="item.vaule">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="规则说明">
                            <el-input v-model="headerInfo.intro" placeholder="请输入" :disabled="isPreview" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="ls-btn-row">
                <div class="left">
                    <span>请选择指标及分数</span>
                </div>
                <div>
                    <el-button type="primary" size="mini" @click="saveTemplate()" v-show="!isPreview">保存</el-button>
                </div>
            </div>
            <div class="table-wrap">
                <el-table :data="formatTable()" ref="tableRef" size="mini" border @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="50">
                    </el-table-column>
                    <el-table-column type="index" label="序号" width="50" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="targetName" label="指标名称" width="120" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="intro" label="计算说明" width="80" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="targetType" label="指标类型" min-width="70">
                        <template slot-scope="scope">
                            <span>{{formatTargetTypes(scope.row.targetType)}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="isChoose" label="是否选择" min-width="70">
                        <template slot-scope="scope">
                            <el-checkbox v-model="scope.row.isChoose" :disabled="isPreview"></el-checkbox>
                        </template>
                    </el-table-column>
                    <el-table-column prop="isChoose" label="时间类型" min-width="140">
                        <template slot-scope="scope">
                            <el-select v-model="scope.row.timeType" placeholder="请选择" filterable clearable size="mini" :disabled="isPreview">
                                <el-option v-for="(item, i) in timeRange" :key="i" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="" label="时间范围" min-width="400">
                        <template slot-scope="scope">
                            <el-date-picker v-model="scope.row.startTime" type="date" placeholder="选择日期" v-if="scope.row.timeType == 'DAY'" size="mini" :disabled="isPreview" value-format="yyyy-MM-dd">
                            </el-date-picker>
                            <span v-if="scope.row.timeType == 'DAY'">~</span>
                            <el-date-picker v-model="scope.row.endTime" type="date" placeholder="选择日期" v-if="scope.row.timeType == 'DAY'" size="mini" :disabled="isPreview" value-format="yyyy-MM-dd">
                            </el-date-picker>
                            <el-select v-model="scope.row.timeRange" placeholder="请选择时间周期" filterable clearable size="mini" v-if="scope.row.timeType == 'MONTH'" :disabled="isPreview">
                                <el-option v-for="(item, i) in rangeMonth" :key="i" :label="item.key" :value="item.vaule">
                                </el-option>
                            </el-select>
                            <el-select v-model="scope.row.timeRange" placeholder="请选择自然年" filterable clearable size="mini" v-if="scope.row.timeType == 'YEAR'" :disabled="isPreview">
                                <el-option v-for="(item, i) in rangeYear" :key="i" :label="item.key" :value="item.vaule">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页-->
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pager.currPage" :page-sizes="pager.pageOptions" :page-size="pager.pageSize"
                    :total="pager.total" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
            </div>
            <div class="line"></div>
            <div class="ls-btn-row" style="margin-top: 30px;" v-if="isPreview">
                <div class="left">
                    <span>操作日志</span>
                </div>
            </div>
            <log-table :busId="gradeId" v-if="isPreview"></log-table>
        </div>
    </div>
</template>

<script>
import commonSelectList from "@/common/commonSelectList.js";

export default {
    name: "evalute-list",
    mounted() {
        this.gradeId = this.$route.query.gradeId;
        this.paramForm.action = this.$route.query.opera;
        if (this.paramForm.action == "PREVIEW") {
            this.isPreview = true;
        } else {
            this.isPreview = false;
        }
        if (this.gradeId) {
            this.addView = false;
        }
        //初始化字典数据
        this.initDict();
        this.initCustGrades(1);
        this.getDetail();
    },
    methods: {
        formatTable() {
            if (this.paramForm.template && this.paramForm.template.templates) {
                this.pager.total = this.paramForm.template.templates.length;
                return this.paramForm.template.templates.slice(
                    (this.pager.currPage - 1) * this.pager.pageSize,
                    this.pager.currPage * this.pager.pageSize
                );
            } else {
                return Array();
            }
        },
        handleSizeChange(val) {
            this.pager.pageSize = val;
            //this.getTemplates();
        },
        handleCurrentChange(val) {
            this.pager.currPage = val;
            //this.getTemplates();
        },
        typeSelectChanged(val) {
            if ("AGENT_GRADE" == val || "NO_AGENT_GRADE" == val) {
                this.showRuleType = true;
            } else {
                this.showRuleType = false;
            }
            var tempArray = this.globalTemplate;
            var array = tempArray.filter((item) => {
                return item.parentCode.indexOf(val) > -1;
            });
            this.paramForm.template.templates = array;
            this.formatTable();
        },
        //移除阶梯分数
        remove(scopeParent, scopeChild) {
            scopeParent.row.childes.splice(scopeChild.$index, 1);
        },
        //等级类型触发事件
        gradeTypechange(val) {
            this.ruleType = val;
        },
        //获取所有模板
        getTemplates() {
            var param = {
                needShowChoose: !this.isPreview,
                gradeId: this.gradeId,
                currPage: this.pager.currPage,
                pageSize: this.pager.pageSize,
            };
            var _this = this;
            this.$ajax.post({
                domain: "crmCmUrl",
                url: "cmGrade.getTemplates",
                data: JSON.stringify(param),
                requestType: "body",
                success: function (res) {
                    if (res.errorCode === 200) {
                        this.paramForm.template.templates = res.data.data;
                        this.pager.total = res.data.total;
                    } else {
                        this.$message.error(res.msg);
                    }
                }.bind(_this),
                error: function (res) {
                    _this.$message.error(res.body.msg);
                },
            });
        },
        //查看详情
        getDetail() {
            var _this = this;
            var param = {
                id: this.gradeId,
                from: "SEA",
                action: this.paramForm.action,
            };
            this.$ajax.post({
                domain: "crmCmUrl",
                url: "cmGrade.getDetail",
                data: JSON.stringify(param),
                requestType: "body",
                success: function (res) {
                    if (res.errorCode === 200) {
                        _this.paramForm = res.data;
                        _this.headerInfo = this.paramForm.headerInfo;
                        if (!_this.headerInfo.type) {
                            _this.headerInfo.type = "SEA";
                        }
                        this.globalTemplate = this.paramForm.template.templates;
                        //加载模板
                        this.typeSelectChanged(_this.headerInfo.type);
                        if (res.data.rules && res.data.rules.length == 0) {
                            this.initCustGrades(0);
                        }
                        if (res.data.headerInfo.ruleType) {
                            this.ruleType = res.data.headerInfo.ruleType;
                        }
                        var gradeType = res.data.headerInfo.type;
                        if (gradeType) {
                            this.showRuleType =
                                gradeType == "AGENT_GRADE" ||
                                gradeType == "NO_AGENT_GRADE"
                                    ? true
                                    : false;
                        }
                    } else {
                        this.$message.error(res.msg);
                    }
                    //this.getTemplates();
                }.bind(this),
                error: function (res) {
                    _this.$message.error(res.body.msg);
                },
            });
        },
        formatTargetTypes(val) {
            var res = this.targetTypesMap[val];
            if (res) {
                return res;
            }
            return "";
        },
        //保存等级规则
        saveGradeRule() {
            var _this = this;
            if (!this.checkRuleParam()) {
                return;
            }
            var obj = {
                gradeId: _this.headerInfo.id,
                data: this.paramForm.rules,
                type: _this.headerInfo.ruleType,
                action: this.paramForm.action,
            };
            this.$ajax.post({
                domain: "crmCmUrl",
                url: "cmGrade.saveGradeRule",
                data: JSON.stringify(obj),
                requestType: "body",
                success: function (res) {
                    if (res.errorCode === 200) {
                        this.$message.success("保存成功");
                    } else {
                        this.$message.error(res.msg);
                    }
                }.bind(this),
                error: function (res) {
                    _this.$message.error(res.body.msg);
                },
            });
        },

        async initCustGrades(val) {
            const gradeTypesTemp = [];
            //获取客户等级
            const gradeTypes = await commonSelectList.dictDataGet(
                this,
                "CRM_COMMON_CUST_GRADE_TYPE"
            );
            gradeTypes.forEach((item) => {
                gradeTypesTemp.push({
                    grade: item.key,
                    value: item.vaule,
                    ruleType: 0,
                });
            });
            if (val == 0) {
                this.paramForm.rules = gradeTypesTemp;
            } else {
                this.custGrades = gradeTypesTemp;
            }
        },
        //初始化字典数据
        async initDict() {
            //指标类型
            this.targetTypes = await commonSelectList.dictDataGet(
                this,
                "CRM_COMMON_TARGET_TYPE"
            );
            //客户属性
            this.custTypes = await commonSelectList.dictDataGet(
                this,
                "Crm_Customer_Type"
            );
            //时间周期
            this.rangeMonth = await commonSelectList.dictDataGet(
                this,
                "CRM_COMMON_GRADE_TEMP_CYCLE_TIME"
            );
            this.custStatus = await commonSelectList.dictDataGet(
                this,
                "Crm_Customer_Status"
            );
            this.approveStatus = await commonSelectList.dictDataGet(
                this,
                "Crm_Audit_Status"
            );
            //自然年
            this.rangeYear = await commonSelectList.dictDataGet(
                this,
                "CRM_COMMON_GRADE_TEMP_NATURAL_YEAR"
            );
            //业务范围
            this.businessScope = await commonSelectList.dictDataGet(
                this,
                "CRM_COMMON_BUSINESS_SCOPE"
            );
            //客户等级类型
            const targetTypesMap = new Map();
            this.targetTypes.forEach((item) => {
                targetTypesMap[item.vaule] = item.key;
            });
            this.targetTypesMap = targetTypesMap;
        },
        saveTemplate() {
            var _this = this;
            if (!this.checkTemplateParam()) {
                return;
            }
            this.paramForm.template.action = this.paramForm.action;
            if (this.paramForm.action == "COPY") {
                this.paramForm.template.needSave = false;
            } else {
                this.paramForm.template.needSave = true;
            }
            this.paramForm.template.gradeType = _this.headerInfo.type;
            this.$ajax.post({
                domain: "crmCmUrl",
                url: "cmGrade.saveTemplate",
                data: JSON.stringify(this.paramForm.template),
                success: function (res) {
                    if (res.errorCode === 200) {
                        this.$message.success("阶段分数操作成功");
                    } else {
                        this.$message.error(res.msg);
                    }
                }.bind(this),
                error: function (res) {
                    _this.$message.error(res.body.msg);
                },
            });
        },
        handleSelectionChange(val) {
            if (val.length > 1) {
                this.$refs.tableRef.clearSelection();
                this.$refs.tableRef.toggleRowSelection(val.pop());
            } else {
                this.selectRow = val[0];
            }
        },
        handleAdd() {
            if (this.selectRow && this.selectRow.childes) {
                this.$refs.tableRef.toggleRowExpansion(this.selectRow, true);
                this.selectRow.childes.push({});
            } else {
                this.$message.error("请选择一条模板数据进行新增阶段分数");
            }
        },
        saveGradeBefore() {
            var _this = this;
            _this.$refs.formRef.validate((valid) => {
                if (valid) {
                    var check = this.checkTemplateParam();
                    if (!check) {
                        return;
                    }
                    _this.saveGrade();
                } else {
                    return false;
                }
            });
        },
        saveGrade() {
            var _this = this;
            this.paramForm.headerInfo = _this.headerInfo;
            _this.$ajax.post({
                domain: "crmCmUrl",
                url: "cmGrade.save",
                data: JSON.stringify(_this.paramForm),
                success: function (res) {
                    if (res.errorCode === 200) {
                        _this.gradeId = res.data;
                        _this.$message.success("保存成功");
                        this.$router.push({ name: "gradeApplyList" });
                    } else {
                        _this.$message.error(res.msg);
                    }
                }.bind(_this),
                error: function (res) {
                    if (res.errorCode == 201) {
                        _this.$message.error("保存失败");
                    } else {
                        _this.$message.error(res.body.msg);
                    }
                },
            });
        },
        //校验模板数据
        checkTemplateParam() {
            var flag = true;
            try {
                this.paramForm.template.templates.forEach((item) => {
                    if (
                        item.isChoose &&
                        item.timeType == "" &&
                        true == item.needSetTime
                    ) {
                        this.$message.error(
                            "引用的模板" + item.targetName + "时间类型不能为空!"
                        );
                        flag = false;
                        throw new Error("End");
                    }
                    if (
                        item.isChoose &&
                        item.timeType == "DAY" &&
                        true == item.needSetTime
                    ) {
                        if (
                            item.startTime == null ||
                            !item.startTime ||
                            item.endTime == null ||
                            !item.endTime
                        ) {
                            this.$message.error("引用的模板时间不能为空!");
                            flag = false;
                            throw new Error("End");
                        } else if (
                            item.startTime != null &&
                            item.endTime &&
                            item.startTime > item.endTime
                        ) {
                            this.$message.error("请校验引用的模板时间格式!");
                            flag = false;
                            throw new Error("End");
                        }
                    }
                    if (
                        item.isChoose &&
                        item.timeType != "DAY" &&
                        true == item.needSetTime &&
                        (item.timeRange == null || !item.timeRange)
                    ) {
                        this.$message.error("时间范围不能为空!");
                        flag = false;
                        throw new Error("End");
                    }
                });
            } catch (e) {}
            return flag;
        },
        handleExpend(scope) {
            var row = scope.row;
            row.isOpen = !row.isOpen;
            this.$refs.tableRef.toggleRowExpansion(row);
            this.rowIndex = scope.$index;
        },
        clickbtn(type) {
            switch (type) {
                case "refresh":
                    break;
                case "save":
                    this.saveGradeBefore();
                    break;
            }
        },
    },
    data() {
        return {
            custStatus: [],
            approveStatus: [],
            globalTemplate: [],
            rules: {
                title: [
                    {
                        required: true,
                        message: "请输入规则标题",
                        trigger: "blur",
                    },
                ],
                range: [
                    {
                        required: true,
                        message: "请选择业务范围",
                        trigger: "blur",
                    },
                ],
                custType: [
                    {
                        required: true,
                        message: "请选择客户属性",
                        trigger: "blur",
                    },
                ],
                type: [
                    {
                        required: true,
                        message: "请选择规则类型",
                        trigger: "blur",
                    },
                ],
            },
            pager: {
                currPage: 1,
                pageSize: 10,
                pageOptions: [10, 20, 30, 50],
                total: 0,
            },
            showRuleType: true,
            gradeTypes: [
                {
                    label: "客户公海",
                    value: "SEA",
                },
                {
                    label: "运营标签",
                    value: "MARK",
                },
                {
                    label: "运营画像",
                    value: "BUSINESS",
                },
                {
                    label: "风险预警",
                    value: "RISK_WARNING",
                },
                {
                    label: "其他",
                    value: "OTHER",
                },
            ],
            rowIndex: 0,
            rangeMonth: [
                {
                    label: "近一个月",
                    value: "1",
                },
                {
                    label: "近三个月",
                    value: "3",
                },
                {
                    label: "近六个月",
                    value: "6",
                },
                {
                    label: "近九个月",
                    value: "9",
                },
            ],
            rangeYear: [
                {
                    label: "近一年",
                    value: "1",
                },
                {
                    label: "近两年",
                    value: "2",
                },
                {
                    label: "近三年",
                    value: "3",
                },
                {
                    label: "近四年",
                    value: "4",
                },
                {
                    label: "近五年",
                    value: "5",
                },
            ],
            custTypes: [],
            isPreview: false,
            id: "",
            addView: true,
            paramForm: {
                action: "",
                headerInfo: {},
                rules: [],
                template: {},
            },
            //todo:从字典
            rulesTypes: [
                {
                    label: "等级规则",
                    value: "GRADE_LEVEL",
                },
            ],
            headerInfo: {},
            selectRow: {},
            targetTypesMap: {},
            accountWayMap: {},
            levelRuleTable: [],
            ruleType: "0",
            businessScope: [],
            timeRange: [
                {
                    label: "指定时间段",
                    value: "DAY",
                },
                {
                    label: "时间周期",
                    value: "MONTH",
                },
                {
                    label: "自然年",
                    value: "YEAR",
                },
            ],
            rangeTypes: [
                {
                    label: "范围",
                    value: "RANGE",
                },
                {
                    label: "固定值",
                    value: "FIX",
                },
            ],
            custGrades: [],
            btns: [
                {
                    title: "保存",
                    size: "mini",
                    circle: false,
                    type: "primary",
                    isplain: false,
                    btnEvent: "save",
                    show: true,
                    icon: "",
                },
            ],
            tableData: [{ status: 1 }],
            radioVal: "1",
        };
    },
};
</script>

<style  scoped  lang="scss">
.ls-container {
    .ls-btn-row {
        padding: 8px 0;
    }
    .cell-box {
        display: flex;
        > span {
            margin: 0 5px;
        }
    }
    .el-select {
        width: 100%;
    }
}
</style>
