<template>
    <div class='newBlankRule'>
        <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.eventRuleLevel" @change="applyObjChange">
                                    <a-radio-button value="ACCOUNT">账户</a-radio-button>
                                    <a-radio-button value="CAMPAIGN">计划</a-radio-button>
                                    <a-radio-button value="UNIT">组</a-radio-button>
                                    <!-- <a-radio-button value="CREATE">创意</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="applyAccount" prop="applyAccount" >
                                <Treeselect :appId.sync="form.applyAccount" :multiple="false" request="2,4"  ref="treeSelect" />
                            </a-form-model-item>
                        </div>
                    </div>
                    <div class="row-item" v-if="form.eventRuleLevel=='UNIT'">
                        <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="campaignId" prop="campaignId" >
                                <a-select  style="width: 500px" v-model="form.campaignId" allowClear  placeholder="选择具体的计划">
                                    <a-select-option v-for="item in campaignList" :key='item.id' :value='item.campaignId'>
                                        {{item.campaignName}}
                                    </a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </div>
                    </div>
                    <div class="row-item" v-if="form.eventRuleLevel!='ACCOUNT'">
                        <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="applyRange" prop="applyRange" >
                                <a-radio-group v-model="form.applyRange" @change="applyRangeChange">
                                    <a-radio-button value="ACCORDINGTO_STATUS">按状态筛选</a-radio-button>
                                    <a-radio-button value="APPOINT">指定</a-radio-button>
                                </a-radio-group>
                            </a-form-model-item>
                        </div>
                    </div>
                   
                    <div class="row-item" v-if="form.applyRange=='ACCORDINGTO_STATUS'&&form.eventRuleLevel!='ACCOUNT'">
                        <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=" appStatus"  prop=" appStatus">
                                <a-select  style="width: 300px" v-model="form. appStatus" >
                                    <a-select-option v-for="item in statusList" :key="item.id" :value='item.value'>
                                        {{item.title}}
                                    </a-select-option>
                                </a-select>
                            </a-form-model-item>

                        </div>
                    </div>
                    <div class="row-item" v-if="form.applyRange=='APPOINT'&&form.eventRuleLevel!='ACCOUNT'">
                        <div class="hint-item"></div>
                        <div class="label-item">
                            <div class="text-item">具体{{form.eventRuleLevel | handlerApplyObj}}</div>
                            <div class="required-item"></div>
                        </div>
                        <div class="input-item" > 
                            <a-form-model-item ref="status"  prop="status">
                                <div class="selectedExist">
                                    <!-- <a-input v-model="selectedCampaignValue" class="input" placeholder='请输入名称' @change="selectedCampaign">
                                        <a-icon slot="addonAfter" type="search" />
                                    </a-input> -->
                                    <div style="width: 500px; margin-top: 4px;" >
                                        <div class="inventory-tags-lists-header">
                                            <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange">
                                            </a-checkbox>
                                            <div class="inventory-tags-lists-name"><strong>列表</strong></div>
                                        </div>
                                        <div class="inventory-tags-lists-container" v-if="form.applyAccount">
                                            <a-spin :spinning="spinning">
                                                <a-checkbox-group v-model="checkedList" :options="plainOptions" @change="onChange" v-show='plainOptions.length'></a-checkbox-group>
                                                <div style="text-align: center;padding-top:30px" v-show="!plainOptions.length">
                                                    暂无数据
                                                </div>
                                             </a-spin>
                                        </div>
                                        <div class="inventory-tags-lists-container" style="text-align: center;padding-top:30px" v-else>
                                            选择具体账户后，可查看
                                        </div>
                                    </div>
                                    <div class="fenye" v-if="totalPage">
                                        <a-pagination :current='currentPage' size='small' :total='totalPage' :pageSize='10' @change="pageNoChange" />
                                    </div>
                                </div>
                            </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="metricValueCode"  prop="metricValueCode">
                                 <a-select
                                    v-model="form.metricValueCode"
                                    show-search
                                    placeholder="选择规则字段"
                                    option-filter-prop="children"
                                    style="width: 200px"
                                    :filter-option="filterOption"
                                    @change="handleChange"
                                >
                                    <a-select-option  v-for="item in rulesFieldList" :key="item.id" :value='item.metricValueCode'>
                                        {{item.metricValueName}}
                                    </a-select-option>
                                   
                                </a-select>
                            </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" > 
                           <div class="toolbox-automate-rules-create-content_rules-and-condition_rules">
                               <div class="title">
                                   <span class="condition-title">如果</span>
                                   <a-form-model-item ref="causalCondition"  prop="causalCondition">
                                        <a-select  style="width: 300px" v-model="form.causalCondition">
                                            <a-select-option  value='MEET_ALL'>满足以下所有条件</a-select-option>
                                            <!-- <a-select-option  value='MEET_ANY'>满足以下任意条件</a-select-option> -->
                                        </a-select>
                                    </a-form-model-item>
                               </div>
                               <div class="content">
                                   <div class="rules-list" v-for="(item,index) in rulesList" :key='index'>
                                       
                                        <div class="rules-list-item">
                                            <div class="rules-list-item-subject" >
                                                <!-- <a-cascader
                                                    v-model="item.metricValueName"
                                                    :options="condition"
                                                    :display-render="displayRender"
                                                    expand-trigger="hover"
                                                    placeholder=""
                                                    @change="conditionChange(item)"
                                                /> -->
                                                <span class="ruleName">
                                                    {{item.metricValueName || '消耗'}}
                                                </span>
                                                
                                            </div>
                                            <template v-if="form.metricValueCode!='campaignStatus'&&form.metricValueCode!='unitStatus'">
                                            <div class="rules-list-item-subject" >
                                                <a-select  v-model="item.dataRange">
                                                    <a-select-option  value='CURRENT_DAY_DATA'>当天数据</a-select-option>
                                                </a-select>
                                            </div>
                                            <div class="rules-list-item-subject" >
                                                <a-select   v-model="item.judgeMethod">
                                                    <a-select-option  value='GT_EQ'>大于等于</a-select-option>
                                                    <a-select-option  value='LT_EQ'>小于等于</a-select-option>
                                                    <a-select-option  value='BETWEEN'>介于</a-select-option>
                                                </a-select>
                                            </div>
                                            <!--  -->
                                            <div class="rules-list-item-subject" v-if="isCost(item.metricValueCode)">
                                                <a-select   v-model="item.judgeType">
                                                    <a-select-option  value='MONEY'>金额</a-select-option>
                                                    <!-- <a-select-option  value='DAY_BUDGET'>日预算</a-select-option> -->
                                                </a-select>
                                            </div>
                                            <!-- <div class="rules-list-item-subject" v-if="item.judgeType=='MONEY'&&item.judgeMethod!='BETWEEN'">
                                                <a-input-number :min="0" style="width:100%" :max="9999999.99" :step="1" v-model="item.specificMoney" placeholder="请输入" />
                                                <span style="margin-left:8px;line-height:32px">元</span>
                                            </div> -->
                                            
                                            <div class="rules-list-item-subject" v-if="item.judgeMethod=='BETWEEN'" style="margin-right:5px">
                                                <a-input-number :min="0" style="width:100%" :max="9999999.99" :step="1" v-model="item.minThreshold" placeholder="请输入" @blur="inputCheck" />
                                                <!-- <span style="margin-left:8px;line-height:32px">{{item.metricValueCode | handlerDANWEI }}</span> -->
                                            </div>
                                            <span style="margin-right:5px" v-if="item.judgeMethod=='BETWEEN'">~</span>
                                            <div class="rules-list-item-subject" >
                                               <a-input-number :min="0" style="width:100%" :max="9999999.99" :step="1" v-model="item.threshold" placeholder="请输入" />
                                               <span style="margin-left:8px;line-height:32px">{{item.metricValueCode | handlerDANWEI }}</span>
                                            </div>
                                            </template>

                                            <!-- <div class="rules-list-item-subject" v-if="item.judgeType=='DAY_BUDGET'&&item.judgeMethod!='BETWEEN'">
                                                <a-select   v-model="item.budgetMultiple">
                                                    <a-select-option v-for="item in budgetMultipleArr" :key="item.value" :value='item.value' >{{item.label}}</a-select-option>
                                                </a-select>
                                            </div> -->
                                            <!-- <div class="rules-list-item-subject" v-if="item.judgeType=='DAY_BUDGET'&&item.judgeMethod!='LT_EQ'">
                                                <a-select   v-model="item.budgetMultipleMin">
                                                    <a-select-option v-for="item in budgetMultipleArr" :key="item.value" :value='item.value' >{{item.label}}</a-select-option>
                                                </a-select>
                                            </div>

                                            <span style="margin-right:20px" v-if="item.judgeType=='DAY_BUDGET'&&item.judgeMethod=='BETWEEN'">-</span>
                                            <div class="rules-list-item-subject" v-if="item.judgeType=='DAY_BUDGET'&&item.judgeMethod!='GT_EQ'">
                                                <a-select   v-model="item.budgetMultipleMax">
                                                    <a-select-option v-for="item in budgetMultipleArr" :key="item.value" :value='item.value' >{{item.label}}</a-select-option>
                                                </a-select>
                                            </div> -->


                                            <!-- 处理不是消耗的情况 -->
                                            <!-- <div class="rules-list-item-subject" v-if="item.metricValueName[1]!='COST'&&item.judgeMethod!='LT_EQ'">
                                                <a-input-number :min="0" style="width:100%" :max="9999999.99" :step="1" v-model="item.threshold" placeholder="请输入" />
                                                <span style="margin-left:8px;line-height:32px">{{item.metricValueCode | handlerDANWEI}}</span>
                                            </div>
                                            <span style="margin-right:20px" v-if="item.metricValueName[1]!='COST'&&item.judgeMethod=='BETWEEN'">-</span>
                                            <div class="rules-list-item-subject" v-if="item.metricValueName[1]!='COST'&&item.judgeMethod!='GT_EQ'">
                                               <a-input-number :min="0" style="width:100%" :max="9999999.99" :step="1" v-model="item.maxNumber" placeholder="请输入" />
                                               <span style="margin-left:8px;line-height:32px">{{item.metricValueCode | handlerDANWEI }}</span>
                                            </div> -->



                                            <!-- <div class="rules-list-item-delete" @click="deleteRulesListItem(item,index)">
                                                <a-icon type="delete" style="font-size:16px;position: relative;top: 4px;" />
                                            </div> -->
                                            <div class="rules-list-item-subject" v-if="form.metricValueCode=='campaignStatus'">
                                                <a-select   v-model="item.campaignStatus" placeholder="请输入具体状态">
                                                    <a-select-option  value='-1'>不限</a-select-option>
                                                    <a-select-option  value='1'>已暂停</a-select-option>
                                                    <a-select-option  value='3'>计划超预算</a-select-option>
                                                    <a-select-option  value='4'>有效</a-select-option>
                                                    <a-select-option  value='5'>已删除</a-select-option>
                                                    <a-select-option  value='6'>余额不足</a-select-option>
                                                </a-select>
                                            </div>
                                            <div class="rules-list-item-subject" v-if="form.metricValueCode=='unitStatus'">
                                                <a-select   v-model="item.unitStatus" placeholder="请输入具体状态">
                                                    <a-select-option  value='-1'>不限</a-select-option>
                                                    <a-select-option  value='1'>计划已暂停</a-select-option>
                                                    <a-select-option  value='3'>计划超预算</a-select-option>
                                                    <a-select-option  value='6'>余额不足</a-select-option>
                                                    <a-select-option  value='11'>审核中</a-select-option>
                                                    <a-select-option  value='12'>审核未通过</a-select-option>
                                                    <a-select-option  value='14'>已结束</a-select-option>
                                                    <a-select-option  value='15'>已暂停</a-select-option>
                                                    <a-select-option  value='17'>组超预算</a-select-option>
                                                    <a-select-option  value='19'>未达投放时间</a-select-option>
                                                    <a-select-option  value='20'>有效</a-select-option>
                                                </a-select>
                                            </div>

                                        </div>
                                        
                                    </div>
                                    
                                   <!-- <div class="add-rule" @click="addRule"> 添加条件</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">
                                    <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="form.processMethod">
                                                        <a-select-option  value='PAUSE' >关停组</a-select-option>
                                                        <a-select-option  value='SEND'>仅发送通知</a-select-option>
                                                    </a-select>
                                                </a-form-model-item>
                                            </div>
                                        </div>
                                    </div>
                                   
                               </div>
                           </div>
                        </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="checkFrequency"  prop="checkFrequency">
                                <a-radio-group v-model="form.checkFrequency">
                                    <!-- <a-radio-button value="DAY">每天</a-radio-button> -->
                                    <a-radio-button value="HOUR">每小时</a-radio-button>
                                    <a-radio-button value="HALF_AN_HOUR">每半小时</a-radio-button>
                                    <!-- <a-radio-button value="CUSTOM_TIME">自定义</a-radio-button> -->
                                </a-radio-group>
                            </a-form-model-item>
                        </div>
                    </div>
                     <div class="row-item" v-if="form.checkFrequency=='DAY'">
                        <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="specificMoment"  prop="specificMoment">
                               <a-select  style="width: 300px" placeholder="请选择具体时刻" v-model="form.specificMoment">
                                    <a-select-option v-for="(item,index) in 24" :key="item" :value='index'>
                                        {{index>10?`${index}:00`:`0${index}:00`}}
                                    </a-select-option>
                                </a-select>
                            </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="sendMessage"  prop="sendMessage">
                                <a-radio-group v-model="form.sendMessage">
                                    <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" >
                        <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="eventRuleName"  prop="eventRuleName">
                                <a-input
                                    v-model="form.eventRuleName"
                                    allowClear
                                />
                            </a-form-model-item>
                        </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>
    </div>
</template>

<script>
import moment from 'moment';
import { getAction, postAction, downFile, downFilePost } from '@/api/manage';
import { Switch } from 'ant-design-vue';
import Treeselect from '@/views/modules/Statistics/components/Treeselect.vue'
let statusList=[
    // {
    //     id:1,
    //     value:'STATUS_ALL',
    //     title:'所有',
    // },
    // STATUS_DELIVERY_OK
    {
        id:2,
        value:"1",
        title:'所有投放中',
    },
    // {
    //     id:3,
    //     value:'STATUS_CREATE',
    //     title:'所有新建',
    // },
    // {
    //     id:4,
    //     value:'STATUS_DISABLE',
    //     title:'所有已暂停',
    // },
    // {
    //     id:5,
    //     value:'STATUS_AUDIT',
    //     title:'所有新建审核',
    // },
    // {
    //     id:6,
    //     value:'STATUS_DONE',
    //     title:'所有已完成',
    // },
]


let condition=[
    {
        value:'0',
        label:'展示数据',
        children:[
            {
                value:'SHOW',
                label:'展示数',
            },
            {
                value:'CLICK',
                label:'点击数',
            },
            {
                value:'CLICK_RATE',
                label:'点击率',
            },
            {
                value:'COST',
                label:'消耗',
            },
            {
                value:'AD_CLICK_PRICE',
                label:'平均点击单价',
            },
        ]
    },
    {
        value:'1',
        label:'转化数据',
        children:[
            {
                value:'CONVERT',
                label:'转化数',
            },
            {
                value:'CONVERT_COST',
                label:'转化成本',
            },
            {
                value:'CONVERT_RATE',
                label:'转化率',
            },
            {
                value:'DEEP_CONVERT',
                label:'深度转化数',
            },
            {
                value:'DEEP_CONVERT_COST',
                label:'深度转化成本',
            },
            {
                value:'DEEP_CONVERT_RATE',
                label:'深度转化率',
            },
            
        ]
    }
]



let budgetMultipleArr=[
    {
        value:0.5,
        label:'0.5倍预算',
    },
    {
        value:0.8,
        label:'0.8倍预算',
    },
    {
        value:1,
        label:'1倍预算',
    },
    {
        value:1.5,
        label:'1.5倍预算',
    },
]


export default {
    components:{
        Treeselect,
    },
    data() {
        return {
            campaignList:[],
            currentRuleId:'',
            rulesFieldList:[],
            accountID:undefined,
            selectedCampaignValue:undefined,
            spinning:false,
            campaignHaveList:[],
            currentPage:1,
            totalPage:0,
            checkedList: [],
            indeterminate: false,
            checkAll: false,
            plainOptions:[],

            saveLoading:false,
            // 用到的参数数组
            condition,
            statusList,
            budgetMultipleArr,
            accountList:[],    
            form: {
                eventRuleName: `空白规则_${moment().format('YYYY_MM_DD_hh:mm:ss')}`,
                eventRuleLevel:'ACCOUNT',
                applyAccount:'',
                campaignId:undefined,
                applyRange:'ACCORDINGTO_STATUS',
                appStatus:'1',               
                sendMessage:1,                
                checkFrequency:'HOUR',
                causalCondition:'MEET_ALL', //因果条件 满足所有/满足任意
                processMethod:'SEND',
                metricValueCode:undefined,
            },
            rules: {
                eventRuleName: [
                    { required: true, message: '请填写规则的具体名称', trigger: 'blur' },
                    { min: 2, message: '长度不得小于2', trigger: 'blur' },
                ],
                metricValueCode: [{ required: true, message: '请选择规则字段', trigger: 'change' }],
                applyRange: [{ required: true, message: '请选择具体应用范围', trigger: 'change' }],
                applyAccount: [{required: true, message: '请选择具体应用范围', trigger: 'change' }],
                specificMoment: [{required: true, message: '请选择具体时刻', trigger: 'change' }],
                money: [
                    { required: true, message: '请填写具体金额', trigger: 'blur' },
                    // { min: 2, message: '长度不得小于2', trigger: 'blur' },
                ],
            },

            rulesList:[
                {
                    metricValueName:'',
                    metricValueCode:'',
                    dataRange:'CURRENT_DAY_DATA',
                    judgeMethod:'GT_EQ',
                    judgeType:'MONEY',
                    threshold:0,
                    minThreshold:0,
                    campaignStatus:undefined,
                    unitStatus:undefined,
                    // budgetMultiple:0.5,
                    // budgetMultipleMin:0.5,
                    // budgetMultipleMax:0.8,
                    // specificMoney:undefined,
                    // specificMoneyMin:undefined,
                    // specificMoneyMax:undefined,
                }
            ],

            accountFieldList:[],
            campaignFieldList:[],
            unitFieldList:[],
        }
    },
    watch:{
       'form.applyAccount'(n,o){
           this.campaignList=[];
           this.form.campaignId=''
           if(n){
               this.spinning=true;
               if(this.form.eventRuleLevel=='CAMPAIGN'){
                   this.getCampaignList()
               }else if(this.form.eventRuleLevel=='UNIT'){
                   this.getCampaignList()
                    this.getUnitList()
               }

               
           }else if(!n){
               this.plainOptions=[];
           }
       },
       'form.campaignId'(n,o){
           
                this.spinning=true;               
                this.getUnitList()

       }
    },
    methods: {
        // 应用方式改变
        applyRangeChange(e){
            console.log(e.target.value)
            this.checkedList=[];
            this.checkAll=false;
            this.indeterminate=false;
            if(e.target.value=='ACCORDINGTO_STATUS'){
                this.form.appStatus='1';
            }else{
                this.form.appStatus=null;
            }

        },
        // 获取计划列表
        getCampaignList(){
            getAction('/kuaishou/batch/getCampaignList',{
                accountId:this.form.applyAccount,
                putStatus:1,
                pageNo:1,
                pageSize:100000,
            }).then(res=>{
                console.log(res);
                this.plainOptions=[];
                this.spinning=false;
                if(res.success){
                    if(this.form.eventRuleLevel=='CAMPAIGN'){
                        this.plainOptions=res.result.records.map(item=>{
                            return {
                                ...item,
                                label:item.campaignName,
                                value:item.campaignId
                            }
                        })
                    }
                    
                    this.campaignList=res.result.records
                }
            })
        },
        // 获取计划列表
        getUnitList(){
            getAction('/kuaishou/batch/getUnitList',{
                accountId:this.form.applyAccount,
                campaignId:this.form.campaignId,
                pageNo:1,
                pageSize:100000,
            }).then(res=>{
                console.log(res);
                this.plainOptions=[];
                this.spinning=false;
                if(res.success){
                    this.plainOptions=res.result.records.map(item=>{
                        return {
                            ...item,
                            label:item.unitName+'_('+item.reviewDetail+')',
                            value:item.unitId
                        }
                    })
                }
            })
        },

        inputCheck(val){
            console.log(val)
        },


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

        handleChange(value) {
            console.log(value,this.metricValueCode);
            let rulesList={};
            rulesList=this.rulesFieldList.filter(item=>{
                return item.metricValueCode==value
            })[0]
            console.log(rulesList);
            this.rulesList=[]
            rulesList.childs.forEach((ele,index)=>{
                this.rulesList.push({
                    metricValueName:ele.metricValueName,
                    metricValueCode:ele.metricValueCode,
                    dataRange:'CURRENT_DAY_DATA',
                    judgeMethod:'GT_EQ',
                    judgeType:'MONEY',
                    threshold:undefined,
                    minThreshold:undefined,
                    campaignStatus:undefined,
                    unitStatus: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) {
                    console.log('submit!',valid);
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm() {
            this.$refs.ruleForm.resetFields();
        },
        addRule(){
            this.rulesList.push({
                metricValueName:['0','COST'],
                dataRange:'CURRENT_DAY_DATA',
                judgeMethod:'GT_EQ',
                judgeType:'MONEY',
                budgetMultiple:0.5,
                budgetMultipleMin:0.5,
                budgetMultipleMax:0.8,
                campaignStatus:undefined,
                unitStatus:undefined,
                threshold:0,
                maxNumber:0,
            })
        },
        deleteRulesListItem(item,index){
            console.log(item,index)
            this.rulesList=this.rulesList.filter((ele,ind)=>{
                return ind!=index
            })
        },
        displayRender({ labels }) {
            return labels[labels.length - 1];
        },
        conditionChange(item){
            console.log(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;
        },

        applyObjChange(e){
            // console.log(e.target.value)
            this.plainOptions=[]
            this.checkedList=[];
            this.checkAll=false;
            this.indeterminate=false;
            if(e.target.value=='ACCOUNT'){
                this.form.processMethod='SEND'
                this.rulesFieldList=this.accountFieldList
            }else if(e.target.value=='CAMPAIGN'){
                this.rulesFieldList=this.campaignFieldList
            }else if(e.target.value=='UNIT'){
                this.rulesFieldList=this.unitFieldList
            } 
            
            if(this.form.applyAccount){
                if(e.target.value=='CAMPAIGN'){
                    this.spinning=true;
                    this.getCampaignList()
                }else if(e.target.value=='UNIT'){
                    this.spinning=true;
                    this.getCampaignList()
                    this.getUnitList()
                }
            }
            
        },

        saveHandler(){
             this.$refs.ruleForm.validate(valid=> {
                if (valid) {
                    // this.form.rulesList=this.rulesList;
                    console.log(valid,this.form);
                    
                    this.saveLoading=true;
                    let rel=[]
                    if(this.form.eventRuleLevel=='CAMPAIGN'){
                       
                        rel=this.checkedList.map(item=>{
                            return {
                                campaignId:item,
                                unitId:'',
                            }
                        })
                        
                    }else if(this.form.eventRuleLevel=='UNIT'){
                        let checkedList=[];
                        this.checkedList.forEach(item=>{
                            this.plainOptions.forEach(ele=>{
                                if(ele.unitId==item){
                                    checkedList.push({
                                        campaignId:ele.campaignId|| '',
                                        unitId:item
                                    })
                                }
                            })
                        })
                        // console.log(checkedList)
                        rel=this.checkedList.map(item=>{
                            return {
                                campaignId:this.form.campaignId|| '',
                                unitId:item
                            }
                        })
                    }
                    // console.log(rel)
                    if(this.form.metricValueCode=='unitStatus'){
                        // console.log(1)
                        this.rulesList[0].threshold=this.rulesList[0].unitStatus;
                        this.rulesList[0].judgeMethod='EQ'
                    }else if(this.form.metricValueCode=='campaignStatus'){
                         this.rulesList[0].threshold=this.rulesList[0].campaignStatus
                         this.rulesList[0].judgeMethod='EQ'
                    }

                    let params ={
                        accountId:this.form.applyAccount,
                        alarmEventMetric:this.rulesList,
                        rel,
                        ...this.form
                    }
                    console.log(params)
                    if(params.appStatus||params.rel.length>0){
                        if(this.currentRuleId){
                            postAction('/alarm/alarmEventRule/edit',params).then(res=>{
                            console.log(res);
                            this.saveLoading=false;
                            if(res.success){
                                
                                this.$router.push('/autoRules')
                                this.$bus.$emit('remove', '/newBlankRule')
                            }else{
                                this.$message.error(res.message)
                            }
                                
                            
                            })
                        }else{
                            postAction('/alarm/alarmEventRule/add',params).then(res=>{
                            console.log(res);
                            this.saveLoading=false;
                            if(res.success){
                                
                                this.$router.push('/autoRules')
                                this.$bus.$emit('remove', '/newBlankRule')
                            }else{
                                this.$message.error(res.message)
                            }
                                
                            
                            })
                        }
                    }else{
                        this.saveLoading=false;
                        this.$message.error('指定情况下必须选择具体计划或者组')
                    }
                    
                    
                } else {
                    console.log('error submit!!');
                    this.$message.error('请按提示填写必填项目！')
                    return false;
                }
            });
        },

        goBack() {
            this.$router.push('/autoRules')
            this.$bus.$emit('remove', '/newBlankRule')
           
        },

        //分页页码改变
        pageNoChange(val){
            console.log(val);
            this.currentPage=val;
            this.selectedCampaign()
        },

        onChange(checkedList) {
            this.indeterminate = !!checkedList.length && checkedList.length < this.plainOptions.length;
            this.checkAll = checkedList.length === this.plainOptions.length;
        },
        onCheckAllChange(e) {
            let valueOption = [];
            this.plainOptions.forEach((item) => {
                valueOption.push(item.value)
            })
            Object.assign(this, {
                checkedList: e.target.checked ? valueOption : [],
                indeterminate: false,
                checkAll: e.target.checked,
            });
        },
        
        selectedCampaign(e){
            // console.log(e.target.value,this.selectedCampaignValue);
            if(this.accountID){
                this.getExsitGroupList();
            }else{
                this.$message.warning('请选择账户后重试！')
                this.selectedCampaignValue=undefined;
            }
        },

    },

    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(){
        // getAction('/alarm/alarmMetricValue/queryParentChildList',{
        // }).then(res=>{
        //     console.log(res);
        //     if(res.success){              
        //         this.rulesFieldList=res.result
        //     }            
        // })

        getAction(`/alarm/alarmMetricValue/queryParentChildList?metricValueLevel=${1}`,{          
        }).then(res=>{
            console.log(res);
            if(res.success){
                this.accountFieldList=res.result;
                if(this.form.eventRuleLevel=='ACCOUNT'){
                    this.rulesFieldList=this.accountFieldList
                }   
            }            
        })
        getAction(`/alarm/alarmMetricValue/queryParentChildList?metricValueLevel=${2}`,{
        }).then(res=>{
            console.log(res);
            if(res.success){
                this.campaignFieldList=res.result;
                if(this.form.eventRuleLevel=='CAMPAIGN'){
                    this.rulesFieldList=this.campaignFieldList
                }   
            }            
        })
        getAction(`/alarm/alarmMetricValue/queryParentChildList?metricValueLevel=${3}`,{           
        }).then(res=>{
            console.log(res);
            if(res.success){
                this.unitFieldList=res.result;
                if(this.form.eventRuleLevel=='UNIT'){
                    this.rulesFieldList=this.unitFieldList
                }   
            }            
        })

        // console.log(this.$route.query);
        this.currentRuleId=this.$route.query.id
        if(this.$route.query.id){
            getAction('/alarm/alarmEventRule/queryById',{
                id:this.$route.query.id
            }).then(res=>{
                console.log(res);
                if(res.success){
                    this.form={
                        causalCondition:'MEET_ALL', //因果条件 满足所有/满足任意
                        applyAccount:res.result.accountId,
                        ...res.result
                    }
                    this.rulesList=res.result.alarmEventMetrics.map(item=>{
                        if(item.metricValueCode=='unitStatus_value'){
                            return {
                                ...item,
                                unitStatus:item.threshold
                            }
                        }else if(item.metricValueCode=='campaignStatus_value'){
                            return {
                                ...item,
                                campaignStatus:item.threshold
                            }
                        }else {
                            return {
                                ...item,
                            }
                        }
                        
                    });
                    if(res.result.rel){
                        this.form.applyRange='APPOINT'
                        this.checkedList=res.result.rel.map(item=>{
                            if(item.eventRuleLevel=='CAMPAIGN'){
                                return item.campaignId
                            }else if (item.eventRuleLevel=='UNIT'){
                                return item.unitId
                            }
                            
                        })
                        this.onChange(this.checkedList)
                    }else{
                        this.form.applyRange='ACCORDINGTO_STATUS'
                    }
                    console.log(this.form)
                    if(this.form.eventRuleLevel=='ACCOUNT'){
                        this.rulesFieldList=this.accountFieldList
                    }else if(this.form.eventRuleLevel=='CAMPAIGN'){
                        this.rulesFieldList=this.campaignFieldList
                    }else if(this.form.eventRuleLevel=='UNIT'){
                        this.rulesFieldList=this.unitFieldList
                    }  
                }
                
            })
        }

    },
}
</script>

<style lang="scss" scoped>
.newBlankRule{
    
    .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;
        }
        .row-item {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-bottom: 32px;
        }
        .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: 1138px;
        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{
            height: 20px;
            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: 24px;

            .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;
            }

            .rules-list-item {
                box-sizing: border-box;
                width: 100%;
                padding: 24px;
                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">
.newBlankRule{
    .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;
    }
}
</style>