<template>
	<!-- 新增规则 -->
	<div class="cl">
		<!-- <el-button type="primary" class="mb-10" icon="el-icon-plus" size="medium" @click="dialogVisible = true">新增规则</el-button>
		<el-dialog title="新增规则" :visible.sync="dialogVisible" width="80%"> -->
            <div class="cl mb-20">
                <el-row>
                    <el-col :span="8">
                        <div class="form-box">
                            <label class="mylabel">规则名称：</label>
                            <div class="mycontent">
                                <el-input v-model="form.RuleName" disabled></el-input>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <div class="form-box">
                            <label class="mylabel">优先级：</label>
                            <div class="mycontent">
                                <el-input v-model="form.Priority" disabled></el-input>
                            </div>
                        </div>
                    </el-col>
                </el-row>
                <div class="form-box cl">
                    <label class="mylabel">规则内容：</label>
                    <div class="mycontent">
                        <el-col :span="24">
                            <div style="width: 100%;">
                                <div class="thead-box">
                                    <table class="h-table">
                                        <colgroup>
                                            <col width="50%">
                                            <col width="50%">
                                        </colgroup>
                                        <thead>
                                            <tr>
                                                <th>子规则名称</th>
                                                <th>内容</th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                                <div class="tbody-box">
                                    <table class="b-table" v-show="leftTableData.length>0">
                                        <colgroup>
                                            <col width="50%">
                                            <col width="50%">
                                        </colgroup>
                                        <tbody>
                                            <tr v-for="(item,index) in leftTableData" :key="index" v-show="item.OperateType!='del'">
                                                <td>{{item.DimensionRuleName}}</td>
                                                <td>{{item.ParamText}}</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                    <div class="el-table__empty-block" style="height: 100%; width: 100%;font-size:12px"  v-show="leftTableData.length==0"><span class="el-table__empty-text">暂无数据</span></div>
                                </div>
                            </div>
                        </el-col>
                    </div>
                </div>
                <div class="form-box cl">
                    <label class="mylabel">奖项配置：</label>
                    <div class="mycontent pt-10">
                        <div v-for="(item,index) in AwardOptions" :key="index" v-show="item.OperateType!='del'">
                            <el-checkbox class="mb-10" v-model="ContainAwardsId" :label="item.AwardsId">{{item.AwardsName}}（{{item.ContainsPrize}}）</el-checkbox>
                            <el-row>
                                <el-col :span="10">
                                    <div class="form-box">
                                        <label class="mylabel">中奖率：</label>
                                        <div class="mycontent">
                                            <input type="text" class="el-input__inner" style="width:120px" 
                                            :data-myindex="index" v-winningrate="AwardOptions" v-model="item.Probability">%
                                        </div>
                                    </div>
                                </el-col>
                                <el-col :span="10" v-if="item.AwardsType!=1">
                                    <div class="form-box">
                                        <label class="mylabel">奖品上限：</label>
                                        <div class="mycontent">
                                            <input type="text" class="el-input__inner" style="width:120px" 
                                            :data-myindex="index" v-prizeupper="AwardOptions" v-model="item.Max">
                                        </div>
                                    </div>
                                </el-col>
                            </el-row>
                        </div>
                    </div>
                </div>
                <!-- <el-dialog
                width="600px"
                title="规则设置"
                :visible.sync="innerVisible"
                append-to-body>
                    <component 
                    :is="comp" 
                    ref="ruleModel"
                    @showRulesDialog="showRulesDialog" 
                    @addDataRule="addDataRule" 
                    @editDataRule="editDataRule"></component>
                </el-dialog> -->
            </div>
            <div slot="footer" class="dialog-footer text-r">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="addParticipateRules" :disabled="btnDisabled">确 定</el-button>
            </div>
        <!-- </el-dialog> -->
	</div>
</template>

<script>
import ut from "@/assets/js/utils.js";
import apiHelper from "@/assets/js/apiHelper.js";
import WrActivities from "./WinningRules/WrActivities.vue";
import WrBatch from "./WinningRules/WrBatch.vue";
import WrCodeSegment from "./WinningRules/WrCodeSegment.vue";
import WrDateTime from "./WinningRules/WrDateTime.vue";
import WrGPS from "./WinningRules/WrGPS.vue";
import WrSweepCodeTimes from "./WinningRules/WrSweepCodeTimes.vue";
import WrTimeSlot from "./WinningRules/WrTimeSlot.vue";
import WrWeek from "./WinningRules/WrWeek.vue";
export default {
	name: "AddWinningRule",
    components:{ 
        WrActivities,
        WrBatch,
        WrCodeSegment,
        WrDateTime,
        WrGPS,
        WrSweepCodeTimes,
        WrTimeSlot,
        WrWeek
    },
	data() {
		return {
            dialogVisible:false,
            innerVisible:false,
            comp:"",//子规则model页面名字，根据这个名字显示页面
			form: {
				RuleName: '',
				Priority: ''
			},
            leftTableData: [],//左边表格数据
            rightTableData: [],//右边表格数据
            delData:[],//被删除的数据缓存，需要一起传给后台
            total:0,
            ruleIndex:-1,//区别添加和编辑，-1：添加
            editIndex:-1,//区别左边子规则表格添加和编辑，-1：添加
            ContainAwardsId:[],
            AwardOptions:[],//奖品列表
            row:{},
            btnDisabled:true
		};
    },
    directives:{
        winningrate: {
            inserted: function (el,binding) {
                el.addEventListener('input', function () {
                    if(!/^([0-9]*)\.?\d{0,6}$/.test(el.value)){
                        binding.value[el.dataset.myindex].Probability = "";
                    }
                    if (el.value >100 || el.value < 0) {
                        binding.value[el.dataset.myindex].Probability = "";
                    }
                })
            }
        },
        prizeupper: {
            inserted: function (el,binding) {
                el.addEventListener('input', function () {
                    if(!/^([0-9]*)$/.test(el.value)){
                        binding.value[el.dataset.myindex].Max = "";
                    }
                    if (el.value >1000000000 || el.value < 0) {
                        binding.value[el.dataset.myindex].Max = "";
                    }
                })
            }
        },
    },
	watch: {
        AwardOptions:{
			deep: true,
            handler: function (){
                this.verification();
            }
        },
        leftTableData:{
			deep: true,
            handler: function (){
                this.verification();
            }
        },
        form:{
			deep: true,
            handler: function (){
                this.verification();
            }
        },
        ContainAwardsId(){
            this.verification();
        }
    },
	created () {
	},
	mounted () {
        this.getPriseRuleConfig();
        let AwardOptions = [];
        // option=2是编辑
        if(ut.ssg('AwardOptions')){
            AwardOptions = ut.ssg('AwardOptions');
        }else{
            let activityInfo = ut.ssg("activityInfo");
            AwardOptions = activityInfo.AwardOptions?activityInfo.AwardOptions:[];
        }
        if(AwardOptions.length>0){
            AwardOptions.forEach(v => {
                v.Probability = "";
                v.Max = "";
            });
            this.AwardOptions = AwardOptions;
        }else{
            this.AwardOptions = [];
        }
	},
	methods: {
        // 编辑中奖规则数据
        editWinning(index,row){
            console.log(row);
            this.ruleIndex = index;
            this.row = row;
            if(index !==-1){
                this.form.RuleName = row.RuleName;
                this.form.Priority = row.Priority;
                this.leftTableData = row.ChildRules;
                this.ContainAwardsId = row.ContainAwardsId;
                let Config = row.AwardConfig;
                if(this.AwardOptions.length>0){
                    for(let i=0;i<this.AwardOptions.length;i++){
                        Config.forEach(v => {
                            if(this.AwardOptions[i].AwardsId == v.AwardsId){
                                this.AwardOptions[i].Probability = v.Probability;
                                this.AwardOptions[i].Max = v.Max;
                            }
                        });
                    }
                }
            }else{
                this.ContainAwardsId = [];
                this.form = {
                    RuleName: '',
                    Priority: ''
                };
                this.leftTableData = [];//左边表格数据
                for(let i=0;i<this.AwardOptions.length;i++){
                    this.AwardOptions[i].Probability = "";
                    this.AwardOptions[i].Max = "";
                }
            }
        },
		addRule(row){
            this.comp = row.ViewModel;
            this.innerVisible = !this.innerVisible;
            this.$nextTick(() => {
                this.$refs.ruleModel.editModel(-1,row);
            });
        },
        // 获取参与子规则
        getPriseRuleConfig(page=1,size=5){
            let that = this;
            apiHelper.getPriseRuleConfig(page,size, function(res) {
                if (res.flag) {
                    that.rightTableData = res.data.Rows;
                    that.total = res.data.Total;
                } else {
                    that.rightTableData = [];
                    that.total = 0;
                }
            });
        },
        showRulesDialog(){
            this.innerVisible = !this.innerVisible;
        },
        addDataRule(v){
            this.leftTableData.push(v);
            this.innerVisible = !this.innerVisible;
        },
        delect(index,row){
            row.OperateType = "del";
        },
        edit(index,row){
            if(row.OperateType!="add"){
                row.OperateType!="edit";
            }
            
            this.editIndex = index;
            this.comp = row.ViewModel;
            // this.rowData = row;
            this.innerVisible = !this.innerVisible;
            this.$nextTick(() => {
                this.$refs.ruleModel.editModel(index,row);
            });
        },
        editDataRule(v){
            this.leftTableData.splice(this.editIndex,1,v);
            this.innerVisible = !this.innerVisible;
        },
        test(){
            console.log(this.leftTableData);
        },
        addParticipateRules(){
            if(this.winningRate()){
                this.$message.error('中奖率总和不超过100%');
                return;
            }
            let obj = {};
            let ContainRule = [];//规则内容
            let ContainAwards = [];//奖项内容
            let AwardConfig = [];//奖项配置
            this.leftTableData.forEach(v => {
                if(v.OperateType!='del'){
                    ContainRule.push(v.DimensionRuleName);
                }
                
            });
            this.AwardOptions.forEach(v => {
                if(this.ContainAwardsId.includes(v.AwardsId) && v.OperateType!='del'){
                    ContainAwards.push(v.AwardsName);
                    AwardConfig.push(v);
                }
            });
            obj.RuleId = this.ruleIndex==-1?"":this.row.RuleId;
            obj.RuleName = this.form.RuleName;
            obj.RuleType = 2;//参与规则是1，中奖规则是2
            obj.RuleLevel = 1;//通用规则是1，非通用规则是2
            obj.Priority = this.form.Priority;//优先级
            obj.ChildRules = [...this.leftTableData];
            obj.IsEnable = "1";//状态：1:启用，0:禁用
            obj.Remark = "";
            obj.OperateType = this.row == undefined?"add":"edit";
            obj.ContainRule = ContainRule.join();
            obj.ContainAwards = ContainAwards.join();
            obj.AwardConfig = AwardConfig;
            obj.ContainAwardsId = this.ContainAwardsId;
            if(this.ruleIndex==-1){
                this.$emit("addRuleData",obj);
            }else{
                this.$emit("editRuleData",obj);
            }
            
        },
        cancel(){
            this.$emit("hideAddRuleDialog");
        },
        // 中奖率判断
        winningRate(){
            let wr = 0;
            for(let i=0;i<this.AwardOptions.length;i++){
                for(let k=0;k<this.ContainAwardsId.length;k++){
                    if(this.ContainAwardsId[k] == this.AwardOptions[i].AwardsId){
                        wr = wr.add(Number(this.AwardOptions[i].Probability));
                    }
                }
            }
            if(wr > 100){
                return true;
            }else{
                return false;
            }
        },
        // 子规则数据验证
        verification (){
            let flag = false;
            let operateTypeArr = [];
            let withoutArr = [];
            if(this.form.RuleName=='' || this.form.Priority==''){
                this.btnDisabled = true;
                return;
            }


            for(let a=0;a<this.leftTableData.length;a++){
                operateTypeArr.push(this.leftTableData[a].OperateType);
            }
            withoutArr = _.without(operateTypeArr, "del");
            if(withoutArr.length==0){
                this.btnDisabled = true;
                flag = true;
                return;
            }

            this.btnDisabled = false;

            if(this.ContainAwardsId.length>0){
                for(let i=0;i<this.AwardOptions.length;i++){
                    if(flag){
                        break;
                    }
                    for(let k=0;k<this.ContainAwardsId.length;k++){
                        if(this.AwardOptions[i].AwardsId == this.ContainAwardsId[k] && this.AwardOptions[i].AwardsId!="00000000000000000000000000000000"){
                            if(this.AwardOptions[i].Probability=="" || this.AwardOptions[i].Max == ""){
                                this.btnDisabled = true;
                                flag = true;
                                break;
                            }else{
                                this.btnDisabled = false;
                            }
                        }else if(this.AwardOptions[i].AwardsId == this.ContainAwardsId[k] && this.AwardOptions[i].AwardsId=="00000000000000000000000000000000"){
                            if(this.AwardOptions[i].Probability==""){
                                this.btnDisabled = true;
                                flag = true;
                                break;
                            }else{
                                this.btnDisabled = false;
                            }
                        }else{
                            this.btnDisabled = false;
                        }
                    }
                }
            }
        }
	}
};

</script>
<style scoped>
.text-r{text-align: right;}
.text-c{text-align: center;}
.pos-r{position: relative;}
.dis-ib{display: inline-block;}
.mb-10{margin-bottom: 10px;}
.mb-20{margin-bottom: 20px;}
.pt-10{padding-top: 10px;}
.w-200{width: 200px;}
.card-box{
	border: 1px solid #DCDFE6;
	padding: 20px;
	border-radius: 4px;
}
.delete-btn{
	position: absolute;
	top:10px;
	right: 10px;
}
.t90{
    font-size: 24px;
    transform:rotate(90deg);
    -ms-transform:rotate(90deg); 
}
.form-box{margin-bottom: 20px;}
.form-box .mylabel{
    width: 100px;
    text-align: right;
    vertical-align: middle;
    float: left;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    padding: 0 12px 0 0;
    box-sizing: border-box;
}
.form-box .mycontent{
    margin-left: 100px;
    position: relative;
    font-size: 14px;
}
.lh-285{
    line-height: 285px;
}
.h-table{
    padding: 0px;
    width: 100%;
    border-bottom: 0px;
    text-align: left;
    border-spacing: 0px;
    font-size: 12px;
}
.h-table th{
    height: 38px;
    color: #909399;
    padding: 0 10px;
    border-right: 1px solid #EBEEF5;
}
.h-table th:last-child{
    border-right: none;
}
.b-table{
    width: 100%;
    border-spacing: 0px;
    font-size: 12px;
}
.b-table td{
    height: 42px;
    padding: 0 10px;
    border-bottom: 1px solid #EBEEF5;
    border-right: 1px solid #EBEEF5;
}
.b-table tr td:last-child{
    border-right: none;
}
.tbody-box{
    width: 100%;
    /* height: 244px; */
    overflow-y: auto;
    border: 1px solid #EBEEF5;
}
.thead-box{
    width: 100%;
    border-left: 1px solid #EBEEF5;
    border-top: 1px solid #EBEEF5;
    border-right: 1px solid #EBEEF5;
}
</style>