<template>
    <div class='configRules'>
    <a-spin :spinning="spinning">
      
    
        <div class="toolbox-automate-rules-create-body">
            <div class="toolbox-automate-rules-create-content_title"><h3> 新建空白模板</h3></div>
            <div class="toolbox-automate-rules-create-content">
                <a-form-model
                    ref="ruleForm"
                    :model="form"
                    :rules="rules"
                >
                <div class="moduler">
                    <!-- 应用对象 -->
                    <div class="row-item" >
                        <div class="hint-item"></div>
                        <div class="label-item">
                            <div class="text-item">应用媒体</div>
                            <div class="required-item"></div>
                        </div>
                        <div class="input-item"> 
                             <a-form-model-item ref="eventRuleLevel"  prop="eventRuleLevel">
                                <a-radio-group v-model="form.mediaType" :disabled="form.templateId!=null" @change="mediaTypeAllChange">
                                    <a-radio-button :value="3" >头条</a-radio-button>
                                    <a-radio-button :value="2">快手</a-radio-button>
                                    <!-- <a-radio-button :value="3">头条内广</a-radio-button>
                                    <a-radio-button :value="4">快手内广</a-radio-button> -->
                                   
                                </a-radio-group>
                            </a-form-model-item>
                        </div>
                    </div>
                    <div class="row-item" >
                        <div class="hint-item"></div>
                        <div class="label-item">
                            <div class="text-item">模板名称</div>
                            <div class="required-item"></div>
                        </div>
                        <div class="input-item"> 
                             <a-form-model-item ref="templateName"  prop="templateName">
                                <a-input
                                    v-model="form.templateName"
                                    :allowClear='!currentRuleId'
                                    @blur="blurTemplateName"
                                />
                            </a-form-model-item>
                        </div>
                    </div>
                    <div class="row-item" >
                        <div class="hint-item">
                            <!-- <a-tooltip>
                                <template slot="title">
                                    针对计划或者账户粒度的消耗、成本、转化数等数据设置阈值作为监控条件，方便系统判断当前的计划状态；条件之间为「且」的关系 
                                </template>
                                <a-icon type="question-circle" />
                            </a-tooltip> -->
                        </div>
                        <div class="label-item">
                            <div class="text-item">规则条件</div>
                            <div class="required-item"></div>
                        </div>
                        <div class="input-item  extraClass" style="min-width:80%" > 
                            <!-- v-model="activeKey" defaultActiveKey='0'-->
                            <a-collapse accordion  v-model="activeKey" @change="collapseChange" ref="collapse">
                                <template  v-for="(item,index) in form.ruleList"   >
                                <a-collapse-panel   :header="item.groupName" :style="customStyle" >
                                    <span slot="extra">
                                         <a-popconfirm
                                            :title="`确定删除吗？`"
                                            @confirm="deleteRule($event,item,index)"                            
                                        >
                                            <a-icon  type="delete" @click="deleteIcon($event)"/>
                                        </a-popconfirm>
                                    </span>
                                   
                                   
                                    <div class="row-item" >
                                        <div class="hint-item"></div>
                                        <div class="label-item">
                                            <div class="text-item">规则名称</div>
                                            <div class="required-item"></div>
                                        </div>
                                        <div class="input-item"> 
                                            <!-- :disabled="!!item.groupId" -->
                                            <a-form-model-item ref="groupName"  :prop="'ruleList.'+index+'.groupName'" :rules="[
                                                { required: true, message: '请填写规则名称', trigger: 'blur' },
                                                { min: 1, message: '长度不得小于1', trigger: 'blur' }]">                                               
                                                <a-input
                                                    v-model="item.groupName"
                                                    placeholder="请输入规则名称"
                                                    :allowClear="!item.groupId"
                                                    style="width:400px"
                                                    @blur="blurGroupName(item)"
                                                />
                                            </a-form-model-item>    
                                        </div>
                                    </div>
                                    <div class="row-item" >
                                        <div class="hint-item"></div>
                                        <div class="label-item">
                                            <div class="text-item">规则描述</div>
                                            <div class="required-item"></div>
                                        </div>
                                        <div class="input-item"> 
                                            <!-- :disabled="!!item.groupId" -->
                                            <a-form-model-item ref="remark" :prop="'ruleList.'+index+'.remark'"  :rules="[
                                                { required: true, message: '请填写规则描述', trigger: 'blur' },
                                                { min: 1, message: '长度不得小于1', trigger: 'blur' },
                                            ]" >
                                                <a-textarea
                                                    v-model="item.remark"
                                                    style="width:400px"
                                                    placeholder="输入规则描述"
                                                    :auto-size="{ minRows: 2, maxRows: 5 }"
                                                    @blur="blurGroupName(item)"
                                                />
                                            </a-form-model-item>   
                                        </div>
                                    </div>
                                    <div class="row-item" >
                                        <div class="hint-item"></div>
                                        <div class="label-item">
                                            <div class="text-item">执行操作</div>
                                            <div class="required-item"></div>
                                        </div>
                                        <div class="input-item"> 
                                             <a-form-model-item>
                                                <a-radio-group v-model="item.operation"  @change="mediaTypeChange($event,item)">
                                                    <a-radio-button :value="1">开启</a-radio-button>
                                                    <a-radio-button :value="0">关闭</a-radio-button>
                                                </a-radio-group>
                                            </a-form-model-item>  
                                        </div>
                                    </div>
                                    <div class="row-item" v-if="item.operation == 0">
                                        <div class="hint-item"></div>
                                        <div class="label-item">
                                            <div class="text-item">规则类型</div>
                                            <div class="required-item"></div>
                                        </div>
                                        <div class="input-item"> 
                                             <a-form-model-item ref="ruleType"  prop="ruleType">
                                                <a-radio-group v-model="item.ruleType" @change="ruleTypeChange(item)">
                                                    <a-radio-button value="group">组合</a-radio-button>
                                                    <a-radio-button value="base">基础</a-radio-button>
                                                </a-radio-group>
                                            </a-form-model-item>  
                                        </div>
                                    </div>
                                    <div class="row-item"  v-if="item.operation == 0">
                                        <div class="hint-item"></div>
                                        <div class="label-item">
                                            <div class="text-item">规则必填</div>
                                            <div class="required-item"></div>
                                        </div>
                                        <div class="input-item"> 
                                             <a-form-model-item ref="isRequired"  prop="isRequired">
                                                <a-radio-group v-model="item.isRequired" @change="">
                                                    <a-radio-button :value="1">是</a-radio-button>
                                                    <a-radio-button :value="0">否</a-radio-button>
                                                </a-radio-group>
                                            </a-form-model-item>  
                                        </div>
                                    </div>
                                    <div class="row-item" v-if="item.ruleType=='group'&& item.operation == 0">
                                        <div class="hint-item"></div>
                                        <div class="label-item">
                                            <div class="text-item">规则复建</div>
                                            <div class="required-item"></div>
                                        </div>
                                        <div class="input-item"> 
                                             <a-form-model-item ref="isCopy"  prop="isCopy">
                                                <a-radio-group v-model="item.isCopy">
                                                    <a-radio-button :value="1">是</a-radio-button>
                                                    <a-radio-button :value="0">否</a-radio-button>
                                                </a-radio-group>
                                            </a-form-model-item>  
                                        </div>
                                    </div>
                                    <div class="toolbox-automate-rules-create-content_rules-and-condition_rules">
                                        <div class="title">                                            
                                            <a-form-model-item ref="ruleRelationship"  prop="ruleRelationship">
                                                <span class="condition-title">{{item.operation==1?'触发机制':'如果'}}</span>
                                                <a-select  style="width: 300px" v-model="item.ruleRelationship" :disabled="!!item.groupId">
                                                    <a-select-option  value='and'>满足以下所有条件</a-select-option>
                                                    <!-- <a-select-option  value='or'>满足以下任意条件</a-select-option> -->
                                                </a-select>

                                            </a-form-model-item>                                
     
                                        </div>
                                        <div class="content">
                                            <div class="rules-list" v-for="(ele,ind) in item.ruleDetail" :key='ind'>
                                                
                                                    <div class="rules-list-item">
                                                        <div class="rules-list-item-subject" style="width:180px">
                                                            <a-form-model-item ref="baseIndex"   :prop="'ruleList.'+index+'.ruleDetail.'+ind+'.baseIndex'"  :rules="[
                                                                { required: true, message: '请选择指标', trigger: 'blur' },
                                                            ]">
                                                                <a-cascader
                                                                    v-model="ele.baseIndex"
                                                                    :options="item.rulesFieldList"
                                                                    placeholder="选择指标"
                                                                    @change="baseIndexChange(ele,item)"
                                                                    expand-trigger="click"
                                                                    :disabled="!!ele.ruleId"
                                                                    :fieldNames="{ label:'name', value: 'code',children: 'children'}"
                                                                />
                                                            </a-form-model-item>  
    
                                                        </div>
                                                        <template >
                                                        
                                                        <div class="rules-list-item-subject" >
                                                            <a-form-model-item ref="ruleCondition" :prop="'ruleList.'+index+'.ruleDetail.'+ind+'.ruleCondition'"  :rules="[
                                                                { required: true, message: '请选择运算符', trigger: 'blur' },
                                                            ]">
                                                                <a-select   v-model="ele.ruleCondition" placeholder="运算符" :disabled="!!ele.ruleId">
                                                                    <a-select-option  v-for="item in ele.conditionList" :key="item.id" :value='item.ruleCondition'>{{item.conditionName}}</a-select-option>
                                                                </a-select>
                                                            </a-form-model-item>  

                                                        </div>
                                                        <div class="rules-list-item-subject" >
                                                            <a-form-model-item ref="variableType"  prop="variableType">
                                                                <a-select   default-value="0"  :disabled="!!ele.ruleId">
                                                                    <a-select-option  value='0'>当天数据</a-select-option>
                                                                    <!-- <a-select-option  :value='1'>变量</a-select-option> -->
                                                                </a-select>
                                                            </a-form-model-item>                                                             
                                                        </div>
                                                        <div class="rules-list-item-subject" v-if="item.operation==1&&ele.baseIndex&&(ele.baseIndex[ele.baseIndex.length-1]=='cost'||ele.baseIndex[ele.baseIndex.length-1]=='charge')">
                                                            <a-form-model-item ref="variableType"  prop="variableType">
                                                                <a-select   v-model="ele.cindicatorCode" :disabled="!!ele.ruleId">
                                                                    <a-select-option  value='charge'>金额</a-select-option>
                                                                    <a-select-option  value='dayBudget'>预算</a-select-option>
                                                                </a-select>
                                                            </a-form-model-item>                                                             
                                                        </div>
                                                        <div class="rules-list-item-subject" v-if="item.operation==1&&ele.baseIndex&&ele.baseIndex[ele.baseIndex.length-1]=='convertCost'">
                                                            <a-form-model-item ref="variableType"  prop="variableType">
                                                                <a-select   v-model="ele.cindicatorCode" :disabled="!!ele.ruleId">
                                                                    <a-select-option  value='bid'>出价</a-select-option>
                                                                    <a-select-option  value='cost'>成本</a-select-option>
                                                                </a-select>
                                                            </a-form-model-item>                                                             
                                                        </div>
                                                        <!-- <div class="rules-list-item-subject" >
                                                            <a-form-model-item ref="variableType"  prop="variableType">
                                                                <a-select   v-model="ele.variableType" :disabled="!!ele.ruleId">
                                                                    <a-select-option  :value='0'>常量</a-select-option>
                                                                    <a-select-option  :value='1'>变量</a-select-option>
                                                                </a-select>
                                                            </a-form-model-item>                                                             
                                                        </div>
                                                        <div class="rules-list-item-subject" >
                                                            <a-form-model-item ref="judgeFormat"  prop="judgeFormat">
                                                                <a-select   v-model="ele.judgeFormat" placeholder="" :disabled="!!ele.ruleId">
                                                                    <a-select-option  :value='0'>筛选条件</a-select-option>
                                                                    <a-select-option  :value='1'>判断条件</a-select-option>
                                                                </a-select>
                                                            </a-form-model-item>                                                             
                                                        </div>

                                                        <div class="rules-list-item-subject" >
                                                            <a-form-model-item ref="isUnlimited"  prop="isUnlimited">
                                                                <a-select   v-model="ele.isUnlimited" placeholder="是否必填" :disabled="!!ele.ruleId">
                                                                    <a-select-option  :value='1'>必填</a-select-option>
                                                                    <a-select-option  :value='0'>不必填</a-select-option>
                                                                </a-select>
                                                            </a-form-model-item>                                                             
                                                        </div> -->
                                                       
                                                        </template>
                                                        <div class="rules-list-item-delete" @click="deleteRulesListItem(index,ind)" v-if="ind!=0">
                                                            <a-icon type="delete" style="font-size:16px;position: relative;top: 4px;" />
                                                        </div>
                                                    </div>
                                                    
                                            </div>
                                               
                                            <div class="add-rule" @click="addCondition(item,index)" v-if="!!!item.ruleDetail[0].ruleId" v-show="item.ruleType=='group'||item.operation==1"> 添加条件</div>
                                        </div>
                                    </div>
                                    <div class="toolbox-automate-rules-create-content_rules-and-condition_rules">
                                        <div class="title">
                                            <span class="condition-title">则依次执行以下操作</span>
                                        </div>
                                        <div class="content"  v-if="item.operation==0">
                                                <div class="rules-list">                                        
                                                    <div class="rules-list-item">
                                                        <div class="rules-list-item-subject" >
                                                            <a-form-model-item ref="processMethod"  prop="processMethod">
                                                                <a-select   v-model="item.operate" :disabled="!!item.groupId">
                                                                    <a-select-option  value='SEND'>仅发送通知</a-select-option>
                                                                    <a-select-option  value='PAUSE' >关停并发送通知</a-select-option>
                                                                    
                                                                </a-select>
                                                            </a-form-model-item>
                                                        </div>
                                                        <div class="rules-list-item-subject" >
                                                            <a-form-model-item ref="processMethod"  prop="processMethod">
                                                                <a-select   v-model="item.sendType" :disabled="!!item.groupId">
                                                                    <!-- <a-select-option  value='message' >短信</a-select-option> -->
                                                                    <a-select-option  value='Wechat'>企业微信</a-select-option>
                                                                    <a-select-option  value='EMAIL'>邮箱</a-select-option>
                                                                    <!-- <a-select-option  value='phone'>电话</a-select-option> -->
                                                                </a-select>
                                                            </a-form-model-item>
                                                        </div>
                                                    </div>
                                                </div>
                                            
                                        </div>
                                        <div class="content" v-else>
                                                <div class="rules-list">                                        
                                                    <div class="rules-list-item">
                                                        <div class="rules-list-item-subject" >
                                                            <a-form-model-item ref="processMethod"  prop="processMethod">
                                                                <a-select   v-model="item.operate" :disabled="!!item.groupId">
                                                                    <a-select-option  value='BUDGET'>修改预算</a-select-option>
                                                                    <a-select-option  value='BID' >出价</a-select-option>
                                                                    <a-select-option  value='TIME' >投放时间</a-select-option>
                                                                    
                                                                </a-select>
                                                            </a-form-model-item>
                                                        </div>
                                                        <div class="rules-list-item-subject" v-if="item.operate!='TIME'">
                                                            <a-form-model-item ref="processMethod"  prop="processMethod">
                                                                <a-select   v-model="item.operationType" :disabled="!!item.groupId">
                                                                    <a-select-option  value='up'>提高</a-select-option>
                                                                    <a-select-option  value='down'>降低</a-select-option>
                                                                    <a-select-option  value='to'>调整至</a-select-option>
                                                                </a-select>
                                                            </a-form-model-item>
                                                        </div>
                                                        <div class="rules-list-item-subject" v-if="item.operate!='TIME'">
                                                            <a-form-model-item ref="processMethod"  prop="processMethod">
                                                                <a-select   v-model="item.operationValue" :disabled="!!item.groupId">
                                                                    <a-select-option  value='price'>金额</a-select-option>
                                                                    <a-select-option  value='percent'>百分比</a-select-option>
                                                                </a-select>
                                                            </a-form-model-item>
                                                        </div>
                                                    </div>
                                                </div>
                                            
                                        </div>
                                    </div>
                                </a-collapse-panel>
                                </template>
                               
                                
                            </a-collapse>
                            <div class="add-rule" @click="addRule"> 添加规则</div>
                        </div>
                    </div>
                  
                </div>
               
                <div class="moduler">
                    <!-- <div class="moduler-title">计划名称</div> -->
                    <div class="opt">
                        <a-button type="default" style="margin-right:15px" @click="goBack">取消</a-button>
                        <a-button type="primary"  style="margin-right:15px" @click="saveHandler" :loading="saveLoading">保存</a-button>
                    </div>
                </div>   
                </a-form-model>
            </div>
        </div>
    </a-spin>
    </div>
</template>

<script>
import moment from 'moment';
import { getAction, postAction, downFile, downFilePost,deleteAction,putAction } from '@/api/manage';
import { Switch } from 'ant-design-vue';
import Treeselect from '@/views/modules/Statistics/components/Treeselect.vue'
// import func from '../../../../vue-temp/vue-editor-bridge';

export default {
    components:{
        Treeselect,
    },
    data() {
        return {
            activeKey:'0',
            // tabActiveKey:[0],
            customStyle:'background: #f9f9fa;border-radius: 4px;margin-bottom:15px;overflow: hidden;border: 1px solid #d9d9d9;',
            conditionList:[],
            url:{
                fieldList:'/ruleIndicator/list',
                ruleCondition:'/rule/ruleCondition/list',
                creativeTemplate:'/ruleTemplate/createTemplate',
                ruleGroupDelete:'/ruleGroup/delete',
                createRuleGroup:'/ruleGroup/createRuleGroup',
                queryDetailById:'/ruleTemplate/queryDetailById',
            },
            
           
            currentRuleId:'',
            rulesFieldList:[],
       
         
            spinning:false,
           
            saveLoading:false,
            // 用到的参数数组
           
            form: {
                mediaType:3,
                templateName: `空白模板_${moment().format('YYYY_MM_DD_hh:mm:ss')}`,
                ruleList:[
                    {
                        groupName:'默认规则',
                        ruleRelationship:"and",
                        ruleType:'base',
                        operation:1,
                        remark:'',
                        isRequired:1,
                        isCopy:0,
                        rulesFieldList:[],
                        ruleDetail:[
                            {
                                ruleName:'',
                                baseIndex:[],
                                
                                indicatorCode:undefined,
                                ruleDimension:'',
                                dataRange:'CURRENT_DAY_DATA',
                                ruleCondition:undefined,                                
                                threshold:0,
                                variableType:1,  
                                dataUnit:'',
                                conditionList:[],
                                dataType:'',
                                judgeFormat:0,
                                isUnlimited:1,
                                cindicatorCode:'charge'
                            },
                        ],
                        operate:'BUDGET',//预警方式
                        sendType:'Wechat',//通知方式
                        operationType:'up',
                        operationValue:'price'
                    },
                   
                ],
            },
            rules: {
                templateName: [
                    { required: true, message: '请填写规则的具体名称', trigger: 'blur' },
                    { min: 2, message: '长度不得小于2', trigger: 'blur' },
                ],
                
                metricValueCode: [{ required: true, message: '请填写规则描述', trigger: 'change' }],
               
                // threshold: [
                //     { required: true, message: '请填写具体值', trigger: 'blur' },
                //     // { min: 2, message: '长度不得小于2', trigger: 'blur' },
                // ],
            },
            templateNameTrue:false,
            templateNameOld:''
        }
    },
    watch: {
        'form.templateName':function(n,o){
            if(n!=o){
                this.templateNameTrue = true
            }else{
                this.templateNameTrue = false
            }
        },
        // 'form.mediaType':function(n,o){

        //     getAction(this.url.fieldList,{   
        //         mediaType:n,
        //         pageNo:1,
        //         pageSize:500,
        //     }).then(res=>{
        //         console.log(res);
        //         this.rulesFieldList = []
        //         if(res.success){ 
        //             this.rulesFieldList=res.result.map(item=>{
        //                 return {
        //                     name:item.dimensionName,
        //                     code:item.dimension,
        //                     children:item.dimensionList
        //                 }
        //             }) 
        //             this.getTempletDetail()   
        //         }            
        //     })
            
        // }
    },
    methods: {
        blurTemplateName(){
            if(this.currentRuleId){
                if(this.templateNameTrue){
                    if(this.form.templateName!=''){
                        putAction('/ruleTemplate/edit',{id:this.form.templateId,templateName:this.form.templateName}).then(res=>{
                            if(res.success){

                            }else{
                            this.$message.error(res.message) 
                            }
                        })
                    }else{
                        this.$message.error('模板名称不可以为空！！！')
                    }
                }
            }
            
        },
        blurGroupName(item){
            if(this.currentRuleId&&item.groupId){
                if(item.groupName!=''&&item.remark!=''){
                    putAction('/ruleGroup/edit',{id:item.groupId,groupName:item.groupName,remark:item.remark}).then(res=>{
                        if(res.success){

                        }else{
                        this.$message.error(res.message)  
                        }
                    })
                }else{
                    this.$message.error('规则名称和规则描述不可以为空！！！')
                }
            }
            
        },
        ruleTypeChange(item){
            if(item.ruleType=='base'){
                item.isCopy=0;
                item.ruleDetail=item.ruleDetail.filter((item,index)=>{
                    return index==0
                })
            }
        },
        inputCheck(val){
        },


        isCost(val){
            if(val.indexOf('Cost') != -1){
                return true
            } else if(val.indexOf('depletion') != -1){
                return true
            }else{
                return false
            }
            
        },

        baseIndexChange(ele,item) {     
            ele.indicatorCode=ele.baseIndex[1];
            ele.ruleDimension=ele.baseIndex[0];

            item.rulesFieldList.forEach(element => {
                if(element.code==ele.baseIndex[0]){
                    element.children.forEach(item=>{
                        if(item.code==ele.baseIndex[1]){
                            ele.ruleName=item.name
                            ele.dataUnit=item.dataUnit
                            ele.dataType=item.dataType;

                            if(item.dataType!='number'){
                                ele.threshold=''
                            }
                            if(ele.baseIndex[1] == 'cost'||ele.baseIndex[1] == 'charge'){
                                ele.cindicatorCode = 'charge'
                            }else{
                                ele.cindicatorCode = 'bid'
                            }
                            getAction(this.url.ruleCondition,{
                                dataType:item.conditionType
                            }).then(res=>{
                                // console.log(res);
                                ele.conditionList=[];
                                if(res.success){
                                    ele.conditionList=res.result
                                }
                            })
                        }                        
                    })
                }               
            });
            ele.ruleCondition=undefined;
        },
        
        filterOption(input, option) {
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },

        // form-modal 自带方法
        onSubmit() {
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                } else {
                    return false;
                }
            });
        },
        resetForm() {
            this.$refs.ruleForm.resetFields();
        },
        addCondition(item,index){
            if(item.groupId){
                this.$message.warning('不可编辑当前规则组')
            }else{
                this.form.ruleList[index].ruleDetail.push({
                    ruleName:'',
                    baseIndex:[],
                    indicatorCode:undefined,
                    ruleDimension:'',
                    dataRange:'CURRENT_DAY_DATA',
                    ruleCondition:undefined,                                
                    threshold:0,
                    variableType:1,    
                    dataUnit:'',     
                    conditionList:[],     
                    dataType:'',  
                    judgeFormat:0,
                    isUnlimited:1,      
                    cindicatorCode:'charge'         
                })
            }
            
        },
        collapseChange(key){
        },
        addRule(){

            this.form.ruleList.push(
                {
                    groupName:'默认规则',
                    ruleRelationship:"and",
                    ruleType:'base',
                    remark:'',
                    operate:'BUDGET',//预警方式
                    sendType:'Wechat',//通知方式
                    operationType:'up',
                    operationValue:'price',
                    isRequired:1,
                    operation:1,
                    isCopy:0,
                    rulesFieldList:[],
                    ruleDetail:[
                        {
                            ruleName:'',
                            baseIndex:[],
                            indicatorCode:undefined,
                            ruleDimension:'',
                            dataRange:'CURRENT_DAY_DATA',
                            ruleCondition:undefined,                                
                            threshold:0,
                            variableType:1,   
                            dataUnit:'',   
                            conditionList:[],   
                            dataType:'', 
                            judgeFormat:0,
                            isUnlimited:1,   
                            cindicatorCode:'charge'                  
                        },
                    ]
                },
            )
            this.getMediaTypeRuleField(1,this.form.ruleList[this.form.ruleList.length-1])
            this.activeKey=(this.form.ruleList.length-1)+'';
           
            
        },
        deleteRulesListItem(index,ind){
            this.form.ruleList[index].ruleDetail=this.form.ruleList[index].ruleDetail.filter((ele,i)=>{
                return i!=ind
            })
            
        },
        deleteIcon(event){
            event.stopPropagation();
        },
        deleteRule(event,item,index){
            event.stopPropagation();
            if(item.groupId){
                deleteAction(this.url.ruleGroupDelete,{
                    id:item.groupId
                }).then(res=>{
                    if(res.success){
                        this.$message.success(res.message);
                        this.form.ruleList=this.form.ruleList.filter((ele,ind)=>{
                            return ind!=index
                        })
                        this.activeKey=(this.form.ruleList.length-1)+'';
                    }else{
                        this.$message.error(res.message)
                    }
                })
            }else{
                this.form.ruleList=this.form.ruleList.filter((ele,ind)=>{
                    return ind!=index
                })
                this.activeKey=(this.form.ruleList.length-1)+'';
            }
            
        },
        displayRender({ labels }) {
            return labels[labels.length - 1];
        },
        ruleConditionChange(item){
            if(item.metricValueName[1]=='COST'){
                item.judgeType='MONEY';
            }else{
                item.judgeType=undefined;
            } 
            item.specificMoney=undefined;
            item.specificMoneyMin=undefined;
            item.specificMoneyMax=undefined;
            item.threshold=undefined;
            item.maxNumber=undefined;
            item.campaignStatus=undefined;
            item.unitStatus=undefined;
        },

        
        saveHandler(){
             this.$refs.ruleForm.validate(valid=> {
                if (valid) {
                    // this.form.rulesList=this.rulesList;
                    
                    this.saveLoading=true;

                        if(this.currentRuleId){
                            if(this.form.ruleList.length){
                                let ruleList=this.form.ruleList.filter(item=>{
                                    return !item.groupId
                                })
                                if(ruleList.length>0){
                                    ruleList = ruleList.map(item=>{
                                        return {
                                            ...item,
                                            ruleType:item.ruleDetail.length>1?'group':'base'

                                        }
                                    })
                                    postAction(this.url.createRuleGroup,{
                                        templateId:this.currentRuleId,
                                        ruleList
                                    }).then(res=>{
                                        this.saveLoading=false;
                                        if(res.success){
                                            
                                            this.$router.push('/earlyWarningRules/index')
                                            this.$bus.$emit('remove', `/earlyWarningRules/configRules?id=${this.currentRuleId}`)
                                        }else{
                                            this.$message.error(res.message)
                                        }
                                        
                                    })
                                }else{
                                    this.$router.push('/earlyWarningRules/index')
                                    this.$bus.$emit('remove', `/earlyWarningRules/configRules?id=${this.currentRuleId}`)
                                }
                            }else{
                                this.saveLoading=false;
                                this.$message.error('模板内具体规则不能为空')
                            }
                            
                            
                        }else{
                            this.form.ruleList = this.form.ruleList.map(item=>{
                                return {
                                    ...item,
                                    ruleType:item.ruleDetail.length>1?'group':'base'
                                }
                            })
                            postAction(this.url.creativeTemplate,this.form).then(res=>{
                                this.saveLoading=false;
                                if(res.success){
                                    this.$router.push('/earlyWarningRules/index')
                                    this.$bus.$emit('remove', '/earlyWarningRules/configRules')
                                }else{
                                    this.$message.error(res.message)
                                }
                                    
                            
                            })
                        }
                    
                    
                    
                } else {
                    this.$message.error('请按提示填写必填项目！')
                    return false;
                }
            });
        },

        goBack() {
             this.$router.push('/earlyWarningRules/index')
            this.$bus.$emit('remove', '/earlyWarningRules/configRules')
           
        },


        // 获取条件运算符
        getRuleCondition(dataType){
           
        },


        // huixianzhi
        getTempletDetail(){           
            if(this.$route.query.id){
                this.spinning=true;
                getAction(this.url.queryDetailById,{
                    id:this.$route.query.id
                }).then(res=>{
                    // this.spinning=false;
                    if(res.success){
                       
                        // this.spinning=false;
                        new Promise((resolve,reject)=>{
                            // this.getMediaTypeRuleField(1,this.form.ruleList[0])
                            //  getAction(this.url.fieldList,{   
                            //     mediaType:res.result.mediaType,
                            //     pageNo:1,
                            //     pageSize:500,
                            // }).then(result=>{
                            //     console.log(result);
                            //     if(result.success){ 
                            //         this.rulesFieldList=result.result.map(item=>{
                            //             return {
                            //                 name:item.dimensionName,
                            //                 code:item.dimension,
                            //                 children:item.dimensionList
                            //             }
                            //         }) 
                            //         resolve('success')
                            //     }            
                            // })
                            this.form = res.result
                            this.form.ruleList=res.result.ruleList.map(b=>{
                                return {
                                    ...b,
                                    rulesFieldList: []
                                }
                                
                            });
                            resolve('success')
                        }).then(data=>{
                            if(this.form.ruleList){
                                this.form.ruleList.map((item,index)=>{
                                    this.getMediaTypeRuleField(item.operation,item)
                                    item.ruleDetail.forEach((ele,ind)=>{

                                       
                                        getAction(this.url.ruleCondition,{
                                            dataType:ele.conditionType
                                        }).then(result=>{
                                            if(result.success){
                                                ele.conditionList=result.result
                                                 this.$nextTick(()=>{
                                                    ele.baseIndex=[ele.ruleDimension,ele.indicatorCode];
                                                    this.form.ruleList=[...this.form.ruleList]
                                                })
                                               
                                            }
                                        })
                                    })
                                })
                                // this.$nextTick(()=>{
                                //     this.form.ruleList=[...this.form.ruleList]
                                // })
                                // this.form=res.result;
                                this.spinning=false
                            }else{
                                
                                this.form={
                                    ...res.result,
                                    ruleList:[]
                                }
                                // this.form.ruleList=[]
                                this.spinning=false
                            }
                             
                            // this.form=res.result;
                            
                        })
                       
                    }else{
                        this.$message.error(res.message);
                        this.spinning=false;
                    }
                })
            }else{
                this.spinning=false;
            }

        },
        mediaTypeAllChange(){
            for (let i = 0; i < this.form.ruleList.length; i++) {
                this.form.ruleList[i].operation = 1
                this.form.ruleList[i].ruleDetail = []
                this.form.ruleList[i].ruleDetail.push({
                        ruleName:'',
                        baseIndex:[],
                        
                        indicatorCode:undefined,
                        ruleDimension:'',
                        dataRange:'CURRENT_DAY_DATA',
                        ruleCondition:undefined,                                
                        threshold:0,
                        variableType:1,  
                        dataUnit:'',
                        conditionList:[],
                        dataType:'',
                        judgeFormat:0,
                        isUnlimited:1,
                        cindicatorCode:'charge',
                        ruleId:null
                    })
                this.$nextTick(()=>{
                    this.getMediaTypeRuleField(1,this.form.ruleList[i])
                })
                
            }
        },
        mediaTypeChange(e,item){
           
            if(e.target.value == 0){
                item.operate = 'SEND'
            }else if(e.target.value==1){
                item.operate = 'BUDGET'
            }
            item.ruleDetail = []
            item.ruleDetail.push({
                ruleName:'',
                baseIndex:[],
                
                indicatorCode:undefined,
                ruleDimension:'',
                dataRange:'CURRENT_DAY_DATA',
                ruleCondition:undefined,                                
                threshold:0,
                variableType:1,  
                dataUnit:'',
                conditionList:[],
                dataType:'',
                judgeFormat:0,
                isUnlimited:1,
                cindicatorCode:'charge',
                ruleId:null
            })
            this.$nextTick(()=>{
                this.getMediaTypeRuleField(e.target.value,item)
            })
            
        },

        getMediaTypeRuleField(data,itemDetail){
            this.rulesFieldList=[];
            // console.log(itemDetail.ruleDetail)
            getAction(this.url.fieldList,{   
                mediaType:this.form.mediaType,
                operation:data,
                pageNo:1,
                pageSize:500,
            }).then(res=>{
                if(res.success){ 
                    itemDetail.rulesFieldList=[];
                    this.$nextTick(()=>{
                        itemDetail.ruleDetail.map(c=>{
                            return {
                                ...c,
                                baseIndex:[],
                                conditionList:[],
                                ruleCondition:''

                            }
                        })
                    })
                    this.$nextTick(()=>{
                        itemDetail.rulesFieldList=res.result.map(item=>{
                            return {
                                name:item.dimensionName,
                                code:item.dimension,
                                children:item.dimensionList
                            }
                        }) 
                    })
                   
                   
                }            
            })
        },
    },

    filters:{
        handlerApplyObj(val){
            let showVal=''
            switch (val) {
                case 'CAMPAIGN':
                    showVal='计划'
                    break;
                case 'UNIT':
                    showVal='组'
                    break;
                case 'CREATE':
                    showVal='创意'
                    break;           
                default:
                    break;
            }
            return showVal
        },
        handlerDANWEI(val){
            // console.log(val.indexOf("RATE") != -1)

            let returnVal='';
            
            if(val.indexOf("Roi") != -1){
                returnVal='';
            }else if(val.indexOf("Cost") != -1|| val.indexOf("depletion") != -1){
                returnVal='元'                   
            }else{
                    returnVal=''                    
            }

            return returnVal
        },

        
    },

    mounted(){
        // this.spinning=true;
        this.currentRuleId=this.$route.query.id
        if(!this.$route.query.id){

            this.getMediaTypeRuleField(1,this.form.ruleList[0])
            // getAction(this.url.fieldList,{   
            //     mediaType:this.form.mediaType,
            //     pageNo:1,
            //     pageSize:500,
            // }).then(res=>{
            //     console.log(res);
            //     if(res.success){ 



            //         this.rulesFieldList=res.result.map(item=>{
            //             return {
            //                 name:item.dimensionName,
            //                 code:item.dimension,
            //                 children:item.dimensionList
            //             }
            //         }) 
            //         this.getTempletDetail()   
            //     }            
            // })
        }else{
            this.getTempletDetail()   
        }
        
        

        // console.log(this.$route.query);
        
        
    },
}
</script>

<style lang="scss" scoped>
.configRules{
    .add-rule:hover {
        color: #2F88FF;
        border-color: #2F88FF;
    }
     .add-rule {
                cursor: pointer;
               
                height: 40px;
                border-radius: 2px;
                border: 1px dashed #dadfe3;
                font-size: 12px;
                display: flex;
                flex-flow: row column;
                justify-content: center;
                align-items: center;
                color: #666;
                margin-top: 5px;
                -moz-user-select: none;
                -webkit-user-select: none;
                -ms-user-select: none;
                -khtml-user-select: none;
                user-select: none;
            }
    .toolbox-automate-rules-create-body {
        margin: 16px 12px 12px;
        padding: 32px 32px 16px;
        background-color: #fff;
        border-radius: 4px;
    }
    .toolbox-automate-rules-create-content_title {
        background-color: #fff;
        display: flex;
        flex-flow: row nowrap;
        justify-content: flex-start;
        align-items: center;
        margin-bottom: 28px;
        h3 {
            font-size: 22px;
            margin: 0;
            font-weight: 400;
            height: 30px;
            line-height: 30px;
        }
    }
    .toolbox-automate-rules-create-content {
        padding-left: 28px;
    }
    .moduler {
         .opt {
            text-align: right;
        }
        width: 100%;
        background: #fff;
        margin-bottom: 16px;
        position: relative;
        padding: 32px 24px 48px 32px;
        // border-radius: 4px;
        // box-shadow: 0px 1px 6px 0px rgba(0, 0, 0, 0.05);
        .moduler-title {
        display: flex;
        align-items: center;
        font-size: 22px;
        margin-bottom: 20px;
        }
        .extraClass{
            .row-item {
                margin-bottom: 20px;
            }
            
        }
        .row-item {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-bottom: 25px;
        }
        .row-item:last-of-type {
        margin-bottom: 0;
        }
        .row-item .hint-item {
        width: 24px;
        min-width: 24px;
        align-self: flex-start;
        line-height: 20px;
        height: 20px;
        margin-top: 9px;
        }
        .row-item .label-item {
        position: relative;
        align-items: flex-start;
        align-self: flex-start;
        line-height: 20px;
        height: 20px;
        margin-top: 10px;
        width: 80px;
        min-width: 80px;
        .text-item {
            font-size: 14px;
            width: 60px;
        }
        }
        .row-item .required-item {
        width: 4px;
        height: 4px;
        border-radius: 2px;
        background: #f45858;
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        }
        .row-item .input-item {
        min-width: 480px;
        position: relative;
        // height: 35px;
        .tip {
            font-size: 12px;
            color: tomato;
        }
        }
        .adName{
        display: flex;
        .nameList{
            width: 90%;
        }
        .item{
            display: inline-block;
            width: 30%;
            margin-left: 15px;
            margin-bottom: 10px;
        }
        }
    }

    .toolbox-automate-rules-create-content_rules-and-condition_rules {
        margin-bottom: 24px;  
    }
    .toolbox-automate-rules-create-content_rules-and-condition_rules, .toolbox-automate-rules-create-content_rules-and-condition_condition {
        width: 100%;
        background: #fff;
        border-radius: 4px;
        border: 1px solid #dadfe3;
    }
    .toolbox-automate-rules-create-content_rules-and-condition_rules, .toolbox-automate-rules-create-content_rules-and-condition_condition{
         .title{
            font-size: 14px;
            font-weight: 600;
            color: #333;
            
            border-bottom: 1px solid #E4E9ED;
            padding-left: 24px;
            padding: 12px;
            // display: flex;
            // justify-content: flex-start;
            align-items: center;
            .condition-title{
                padding-right: 17px;
            }
        }
         .title2{
            font-size: 14px;
            font-weight: 600;
            color: #333;
            height: 56px;
            border-bottom: 1px solid #E4E9ED;
            padding-left: 24px;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            .condition-title{
                padding-right: 17px;
            }
        }
        .content{
            padding: 15px;

            .add-rule {
                cursor: pointer;
               
                height: 40px;
                border-radius: 2px;
                border: 1px dashed #dadfe3;
                font-size: 12px;
                display: flex;
                flex-flow: row column;
                justify-content: center;
                align-items: center;
                color: #666;
                margin-top: 16px;
                -moz-user-select: none;
                -webkit-user-select: none;
                -ms-user-select: none;
                -khtml-user-select: none;
                user-select: none;
            }
            .add-rule:hover {
                color: #2F88FF;
                border-color: #2F88FF;
            }
            .rules-list-item {
                box-sizing: border-box;
                width: 100%;
                padding: 20px;
                background: #f8f9fa;
                border-radius: 4px;
                margin-bottom: 16px;
                display: flex;
                align-items: center;
                position: relative;
                .rules-list-item-delete {
                    position: absolute;
                    right: 24px;
                    height: 30px;
                    padding-left: 24px;
                    border-left: 1px solid #DADFE3;
                    cursor: pointer;
                }
                .rules-list-item-subject {
                    width: 120px;
                    margin-right: 16px;
                    display: flex;
                    .ruleName{
                        display: block;
                        width: 100%;
                        height: 32px;
                        line-height: 32px;
                        text-align: center;
                        background-color: #fff;
                        border: 1px solid #d9d9d9;
                        border-radius: 4px;
                    }
                }
            }
            .rules—list_item:last-of-type {
                margin-bottom: 0;
            }
        }
    }

    .selectedExist{
         width: 500px;
         padding-top: 5px;
         .inventory-tags-lists-header {
          background-color: #F8F9FA;
          border: 1px solid #E4E9ED;
          height: 36px;
          line-height: 33px;
          border-radius: 4px 4px 0 0;
          font-weight: bold;
          display: flex;
        }

        .inventory-tags-lists-container {
          border: 1px solid #E4E9ED;
          margin-top: -1px;
          height: 100%;
          padding: 4px 0px;
          border-radius: 0 0 4px 4px;
          height: 300px;
          overflow: auto;
          
        }

        .inventory-tags-lists-item {
          width: 100%;
          height: 37px;
          line-height: 37px;
          padding-left: 12px;
          padding-right: 12px;
          display: flex;
          font-size: 14px;
          color: #333;
        }
               
                .input{
                    margin-bottom:16px ;
                }
                .campaign-have-list{
                    font-family: PingFangSC-Regular;
                    font-size: 14px;
                    color: #333;
                    border: 1px solid #DADFE3;
                    border-radius: 4px;
                    margin-bottom: 16px;
                    height: 388px;
                    .campaign-have-header {
                        height: 38px;
                        width: 100%;
                        padding-left: 13px;
                        line-height: 38px;
                        background: #f8f9fa;
                        border-radius: 4px 4px 0px 0px;
                        border-bottom: 1px solid #DADFE3;
                    }
                    .campaign-have-list ul {
                        width: 100%;
                        height: 350px;
                        padding-top: 6px;
                        
                    }
                    li{
                        padding: 6px 10px;
                        cursor: pointer;
                    }
                    li:hover{
                        background: #EDF1F5;
                    }
                    .ad-d-flex-between {
                        justify-content: space-between !important;
                    }

                    .ad-d-flex, .ad-btn {
                        display: flex;
                        align-items: center;
                    }
                    .byted-loading-v {
                        position: absolute;
                        top: 0;
                        right: 0;
                        bottom: 0;
                        left: 0;
                        z-index: 996;
                        background-color: hsla(0,0%,96%,.9);
                    }
                    .info{
                        width: 60%;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }
                    .landing-type {
                        color: #999;
                        font-size: 12px;
                        white-space: nowrap;
                    }
                }
                .noAccountID{
                    font-size: 14px;
                    text-align: center;
                    color: #999;
                    line-height: 388px;
                }
                .fenye{
                    height: 60px;
                    padding-top: 12px;
                    text-align: right;
                }
            }
}
</style>
<style lang="scss">
.configRules{
    .ant-collapse > .ant-collapse-item > .ant-collapse-header {
        position: relative;
        padding: 12px 16px;
        padding-left: 40px;
        color: rgba(0, 0, 0, 0.85);
        line-height: 22px;
        cursor: pointer;
        -webkit-transition: all 0.3s;
        height: 46px;
        transition: all 0.3s;
    }
    .ant-form-item {
        margin-bottom: 0;
        
    }
    .content{
        .ant-form-item {
            margin-bottom: 0;
            width: 100%;
        } 
    }
    .ant-radio-button-wrapper {
        
        min-width: 70px;
        text-align: center;
    }
    .ant-checkbox-wrapper,
    .ant-checkbox-group-item {
      display: block;
      padding: 5px 15px;
    }

    .ant-checkbox-wrapper:first-child {
      padding: 0 15px 5px;
    }

    .ant-collapse{
       border: 1px solid #fff; 
       background-color: #fff;
    }
    // .rules-list-item{
    .ant-form-explain{
        clear: both;
        min-height: 22px;
        margin-top: -2px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 14px;
        line-height: 1.5;
        -webkit-transition: color 0.3s cubic-bezier(0.215, 0.61, 0.355, 1);
        transition: color 0.3s cubic-bezier(0.215, 0.61, 0.355, 1);
        position: absolute;
    }
    // }
    
    .has-error .ant-form-explain, .has-error .ant-form-split {
        color: #f5222d;
    }

    .has-error .ant-form-explain, .has-error .ant-form-split {
        color: #f5222d;
    }

    .has-error .ant-form-explain, .has-error .ant-form-split {
        color: #f5222d;
    }

    .has-error .ant-form-explain, .has-error .ant-form-split {
        color: #f5222d;
    }
}
</style>