
<style>
.display-none-selset {
  display: none !important;
}
.ruleModule .ant-form-item-label > label::after {
  content: '';
  position: relative;
  top: -0.5px;
  margin: 0 8px 0 2px;
}
</style>
<template>
  <div class="ruleModule">
    <div class="toolbox-automate-rules-create-body">
      <!-- <a-steps :current="current" size="default" style="width: 50%; margin: 0 auto" v-if="editShow">
        <a-step title="预警值填写" />
        <a-step title="开关设置" />
      </a-steps> -->

      <!-- {{ ceshi }}{{ time }}
      <br />
      <selectGroup v-model="ceshi2" style="width: 300px;margin-right:5px" code="37f678d06fc45b494a924894355d6f76" :multiple="true" />

      <timeRange v-model="time" :allowClear="true" :disabledDate="disabledDate" /> -->
      <!-- {{ ceshi }}
      <checkBoxGroup
        v-model="ceshi"
        style="width: 400px"
        code="95224d306285ea267eb6b5a31b5d84b6"
        :allValue="true"
        :radioStyle="true"
      />
      {{ form }} -->

      <div class="toolbox-automate-rules-create-content_title">
        <h3>预警值{{ editShow ? '填写' : '表单预览' }}</h3>
      </div>
      <a-spin :spinning="spinLoading">
        <div class="toolbox-automate-rules-create-content">
          <a-form-model ref="ruleForm" :model="form" layout="horizontal" :hideRequiredMark="true">
            <div class="moduler">
              <template v-for="(item, index) of form.ruleList">
                <div v-if="item.operation==1" style="border:1px solid #f2f2f2;padding:15px 25px;margin-bottom:15px">
                  <div class="row-item" :key="index">
                    <div class="hint-item">
                      <a-tooltip>
                        <template slot="title">
                          {{ item.remark }}
                        </template>
                        <a-icon type="question-circle" />
                      </a-tooltip>
                    </div>
                    <div class="label-item">
                      <div class="text-item">{{ item.groupName }}</div>
                      <div class="required-item" v-if="item.isRequired == 1"></div>
                    </div>
                     <div class="input-item" style="width:70%;min-width:none">
                    
                      <div class="toolbox-automate-rules-create-content_rules-and-condition_rules" style="margin-bottom:10px">
                        <div class="content">
                          <div class="rules-list">
                            <div class="rules-list-item">
                              <template   v-for="(value, valueIndex) of item.ruleDetail">
                                <div class="input-item"   style="width:100%;min-width:none">
                                    <a-form-model-item
                                      :label-col="{ span: 4 }"
                                      :wrapper-col="{ span: 20 }"
                                      :label="value.name"
                                      :prop="'ruleList.' + index + '.ruleDetail.' + valueIndex + '.threshold'"
                                      :rules="{
                                        required: item.isRequired == 1 ? true : false,
                                        message: `${value.name}必填`,
                                        trigger: 'blur',
                                      }"
                                    >
                                    <!-- <div style="margin-left:20px"> -->
                                      当天数据
                                      <span
                                        style="color: red; font-size: 16px; font-weight: 500;margin:0 10px"
                                        v-if="value.modelType == 'numberText'"
                                      >
                                        {{ value.ruleCondition | conditionName }}
                                      </span>
                                      {{ value.cindicatorCode | cindicatorName }}
                                      <a-input-number
                                        v-if="value.cindicatorCode=='charge'||value.cindicatorCode=='cost'"
                                        :disabled="!editShow"
                                        style="width: 100px; margin-right: 5px"
                                        v-model="value.threshold"
                                        :min="0.01"
                                        :max="999999.99"
                                        :step="0.01"
                                      />
                                      
                                      <a-select 
                                        allowClear
                                        v-else-if="value.cindicatorCode=='dayBudget'" 
                                        v-model="value.threshold" 
                                        style="width: 100px; margin-right: 5px"
                                        :disabled="!editShow"
                                      >
                                        <a-select-option value="0.5">
                                          0.5倍预算
                                        </a-select-option>
                                        <a-select-option value="0.8">
                                          0.8倍预算
                                        </a-select-option>
                                        <a-select-option value="1">
                                          1倍预算
                                        </a-select-option>
                                        <a-select-option value="1.2">
                                          1.2倍预算
                                        </a-select-option>
                                      </a-select>
                                      <a-select 
                                        allowClear
                                        v-else-if="value.cindicatorCode=='bid'" 
                                        v-model="value.threshold" 
                                        style="width: 100px; margin-right: 5px"
                                        :disabled="!editShow"
                                      >
                                        <a-select-option value="1.2">
                                          1.2倍出价
                                        </a-select-option>
                                         <a-select-option value="1.5">
                                          1.5倍出价
                                        </a-select-option>
                                      </a-select>
                                      {{ value.cindicatorCode=='charge'||value.cindicatorCode=='cost'?value.dataUnit:'' }}
                                      <span v-if=" value.ruleCondition == 'between'" style="margin:0 15px">
                                        ~
                                      </span>
                                      <a-input-number
                                        v-if=" value.ruleCondition == 'between'&&(value.cindicatorCode=='charge'||value.cindicatorCode=='cost')"
                                        :disabled="!editShow"
                                        style="width: 100px; margin-right: 5px"
                                        v-model="value.thresholdTwo"
                                        :min="0.01"
                                        :max="999999.99"
                                        :step="0.01"
                                      />
                                       <a-select 
                                        allowClear
                                        v-else-if="value.ruleCondition == 'between'&&value.cindicatorCode=='dayBudget'" 
                                        v-model="value.thresholdTwo" 
                                        style="width: 100px; margin-right: 5px"
                                        :disabled="!editShow"
                                      >
                                        <a-select-option value="0.5">
                                          0.5倍预算
                                        </a-select-option>
                                        <a-select-option value="0.8">
                                          0.8倍预算
                                        </a-select-option>
                                        <a-select-option value="1">
                                          1倍预算
                                        </a-select-option>
                                        <a-select-option value="1.2">
                                          1.2倍预算
                                        </a-select-option>
                                      </a-select>
                                      <a-select 
                                        allowClear
                                        v-else-if="value.ruleCondition == 'between'&&value.cindicatorCode=='bid'" 
                                        v-model="value.thresholdTwo" 
                                        style="width: 100px; margin-right: 5px"
                                        :disabled="!editShow"
                                      >
                                        <a-select-option value="1.2">
                                          1.2倍出价
                                        </a-select-option>
                                         <a-select-option value="1.5">
                                          1.5倍出价
                                        </a-select-option>
                                      </a-select>
                                      
                                      
                                      

                                    <!-- </div> -->
                                      
                                    </a-form-model-item>
                                </div>
                              </template>

                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="toolbox-automate-rules-create-content_rules-and-condition_rules" style="margin-bottom:10px">
                        <div class="content">
                          <div class="rules-list">
                            <div class="rules-list-item">
                              <template>
                              <div class="input-item"  style="width:100%!important;min-width:none">
                                  <a-form-model-item
                                    :label-col="{ span: 4 }"
                                    :wrapper-col="{ span: 20 }"
                                    :label="item.operate=='BUDGET'?'修改预算':item.operate=='BID'?'出价':'投放时间'"
                                    :prop="'ruleList.' + index  +'.operationThreshold'"
                                    :rules="{
                                      required: item.isRequired == 1 ? true : false,
                                      message: `${item.operate=='BUDGET'?'修改预算':item.operate=='BID'?'出价':'投放时间'}必填`,
                                      trigger: 'blur',
                                    }"
                                  >
                                  <!-- <div style="margin-left:20px"> -->
                                  <div v-if="item.operate!='TIME'">
                                    <span style="margin:0 15px 0 0">{{item.operationType|operationType}}</span>
                                    <a-input-number
                                      :disabled="!editShow"
                                      style="width: 100px; margin-right: 5px"
                                      v-model="item.operationThreshold"
                                      :min="0.01"
                                      :max="item.operationValue=='price'?999999.99:99.99"
                                      :step="0.01"
                                    />
                                    {{item.operationValue=='price'?'元':'%'}}
                                    <div v-if="item.operationType != 'to'" style="display:inline-block">
                                      <span style="margin:0 15px">|</span>
                                      <span style="margin:0 15px 0 0">{{item.operationType == 'up'?'最高调整至':'最低调整至'}}</span>
                                      <a-input-number
                                        v-if="item.operationType == 'up'"
                                        :disabled="!editShow"
                                        style="width: 100px; margin-right: 5px"
                                        v-model="item.maxValue"
                                        :min="0.01"
                                        :max="9999.99"
                                        :step="0.01"
                                      />
                                      <a-input-number
                                        v-else-if="item.operationType == 'down'"
                                        :disabled="!editShow"
                                        style="width: 100px; margin-right: 5px"
                                        v-model="item.minValue"
                                        :min="0.01"
                                        :max="9999.99"
                                        :step="0.01"
                                      />
                                      <span>
                                        元
                                      </span>
                                    </div>
                                  </div>
                                  <a-select 
                                    allowClear
                                    v-else
                                    v-model="item.operationThreshold" 
                                    style="width: 100px; margin-right: 5px"
                                    :disabled="!editShow"
                                  >
                                    <a-select-option value="1">
                                      1
                                    </a-select-option>
                                    <a-select-option value="2">
                                      2
                                    </a-select-option>
                                    <a-select-option value="3">
                                      3
                                    </a-select-option>
                                    <a-select-option value="4">
                                      4
                                    </a-select-option>
                                  </a-select>
                                  <span v-if="item.operate == 'TIME'">
                                    小时
                                  </span>
                                    
                                    


                                    
                                    

                                  <!-- </div> -->
                                    
                                  </a-form-model-item>
                              </div>
                              </template>
                            </div>
                          </div>
                        </div>
                      </div>
                     </div>
                  </div>
                </div>
                <div v-else>
                  <div class="row-item" v-if="item.ruleType == 'base' && item.isCopy == 0" :key="index">
                    <div class="hint-item">
                      <a-tooltip>
                        <template slot="title">
                          {{ item.remark }}
                        </template>
                        <a-icon type="question-circle" />
                      </a-tooltip>
                    </div>
                    <div class="label-item">
                      <div class="text-item">{{ item.groupName }}</div>
                      <div class="required-item" v-if="item.isRequired == 1"></div>
                    </div>
                    <div class="input-item">
                      <a-form-model-item
                        v-for="(value, valueIndex) of item.ruleDetail"
                        :key="valueIndex"
                        :ref="value.indicatorCode + valueIndex"
                        :prop="'ruleList.' + index + '.ruleDetail.' + valueIndex + '.threshold'"
                        :rules="{
                          required: item.isRequired == 1 ? true : false,
                          message: `${item.groupName}必填`,
                          trigger: value.dataType == 'array' ? 'change' : 'blur',
                        }"
                      >
                        <span
                          style="color: red; font-size: 16px; font-weight: 500"
                          v-if="value.modelType == 'numberText'"
                        >
                          {{ value.ruleCondition | conditionName }}
                        </span>
                        <a-input-number
                          :disabled="!editShow"
                          v-model="value.threshold"
                          :min="0"
                          style="width: 100px; margin-right: 5px"
                          v-if="value.modelType == 'numberText'"
                        />
                        <a-input
                          :disabled="!editShow"
                          v-model="value.threshold"
                          style="width: 300px; margin-right: 5px"
                          v-else-if="value.modelType == 'text'"
                          @change="inputChange(value)"
                        />
                        <selectGroup
                          :disabled="!editShow"
                          v-model="value.threshold"
                          style="width: 300px; margin-right: 5px"
                          :code="value.dictId"
                          :requestUrl="value.requestUrl"
                          :multiple="
                            value.dataType == 'string' ||
                            value.dataType == 'number' ||
                            value.indicatorCode == 'presentedVideo' ||
                            value.indicatorCode == 'hideIfExists'
                              ? false
                              : true
                          "
                          v-else-if="value.modelType == 'select'"
                        />
                        <!-- <selectGroup
                        v-model="value.threshold"
                        style="width: 300px;margin-right:5px"
                        :code="value.dictId"
                        :multiple="value.dataType == 'string' ? false : true"
                      /> -->
                        <checkBoxGroup
                          :disabled="!editShow"
                          v-model="value.threshold"
                          style="width: 100%; margin-right: 5px"
                          :code="value.dictId"
                          :allValue="true"
                          :radioStyle="
                            value.dataType == 'string' ||
                            value.dataType == 'number' ||
                            value.indicatorCode == 'presentedVideo' ||
                            value.indicatorCode == 'hideIfExists'
                              ? true
                              : false
                          "
                          v-else-if="value.modelType == 'checkBox'"
                        />
                        <a-select
                          :disabled="!editShow"
                          mode="tags"
                          style="width: 100%"
                          placeholder="按回车生成"
                          v-model="value.threshold"
                          dropdownClassName="display-none-selset"
                          :token-separators="[',', ' ', '，']"
                          v-else-if="value.modelType == 'tagBox'"
                        >
                        </a-select>

                        <!-- <p v-else-if="value.modelType == 'timeRange'">{{value.threshold}}</p> -->

                        <scheduleTime
                          style="width: 100%"
                          :scheduleTime.sync="value.threshold"
                          ref="selectCheck"
                          v-else-if="value.modelType == 'scheduleTime'"
                        >
                        </scheduleTime>
                        <!--  v-model="value.threshold" -->
                        <!-- :cascaderValue.sync="value.threshold" -->
                        <region
                          :disabled="!editShow"
                          :checkData.sync="value.threshold"
                          :dataValue="value.threshold"
                          style="width: 100%"
                          :isLazy="true"
                          v-else-if="value.modelType == 'region'"
                        >
                        </region>
                        <!-- {{value.threshold}} -->
                        {{ value.dataUnit }}
                      </a-form-model-item>
                    </div>
                  </div>

                  <div class="row-item" v-else-if="item.ruleType == 'group' && item.isCopy == 0" :key="index">
                    <div class="hint-item">
                      <a-tooltip>
                        <template slot="title">
                          {{ item.remark }}
                        </template>
                        <a-icon type="question-circle" />
                      </a-tooltip>
                    </div>
                    <div class="label-item">
                      <div class="text-item">{{ item.groupName }}</div>
                      <div class="required-item" v-if="item.isRequired == 1"></div>
                    </div>
                    <div class="input-item">
                      <div class="toolbox-automate-rules-create-content_rules-and-condition_rules">
                        <div class="content">
                          <div class="rules-list">
                            <div class="rules-list-item">
                              <template v-for="(value, valueIndex) of item.ruleDetail">
                                <div class="row-item row-group" v-if="value.variableType == 1" :key="valueIndex">
                                  <!-- <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
                                      :label-col="{ span: 6 }"
                                      :wrapper-col="{ span: 18 }"
                                      :label="value.name"
                                      :ref="value.indicatorCode + valueIndex"
                                      :prop="'ruleList.' + index + '.ruleDetail.' + valueIndex + '.threshold'"
                                      :rules="{
                                        required: item.isRequired == 1 ? true : false,
                                        message: `${value.name}必填`,
                                        trigger: 'blur',
                                      }"
                                      v-if="value.modelType == 'numberText'"
                                    >
                                      <span style="color: red; font-size: 16px; font-weight: 500">
                                        {{ value.ruleCondition | conditionName }}
                                      </span>

                                      <a-input-number
                                        :disabled="!editShow"
                                        style="width: 100px; margin-right: 5px"
                                        v-model="value.threshold"
                                        :min="0"
                                      />{{ value.dataUnit }}
                                    </a-form-model-item>
                                    <a-form-model-item
                                      :label-col="{ span: 6 }"
                                      :wrapper-col="{ span: 18 }"
                                      :label="value.name"
                                      :ref="value.indicatorCode + valueIndex"
                                      :prop="'ruleList.' + index + '.ruleDetail.' + valueIndex + '.threshold'"
                                      :rules="{
                                        required: item.isRequired == 1 ? true : false,
                                        message: `${value.name}必填`,
                                        trigger: 'blur',
                                      }"
                                      v-else-if="value.modelType == 'text'"
                                    >
                                      <a-input v-model="value.threshold" style="width: 95%" :disabled="!editShow" />
                                    </a-form-model-item>
                                    <a-form-model-item
                                      :label-col="{ span: 6 }"
                                      :wrapper-col="{ span: 18 }"
                                      :label="value.name"
                                      :ref="value.indicatorCode + valueIndex"
                                      :prop="'ruleList.' + index + '.ruleDetail.' + valueIndex + '.threshold'"
                                      :rules="{
                                        required: item.isRequired == 1 ? true : false,
                                        message: `${value.name}必选`,
                                        trigger: 'change',
                                      }"
                                      v-else-if="value.modelType == 'select' || value.modelType == 'checkBox'"
                                    >
                                      <!--  -->
                                      <selectGroup
                                        :disabled="!editShow"
                                        v-model="value.threshold"
                                        :code="value.dictId"
                                        :requestUrl="value.requestUrl"
                                        :multiple="
                                          value.dataType == 'string' ||
                                          value.dataType == 'number' ||
                                          value.indicatorCode == 'presentedVideo' ||
                                          value.indicatorCode == 'hideIfExists'
                                            ? false
                                            : true
                                        "
                                        style="width: 95%"
                                        @clearValidate="clearAll"
                                      />
                                    </a-form-model-item>
                                    <a-form-model-item
                                      :label-col="{ span: 6 }"
                                      :wrapper-col="{ span: 18 }"
                                      :label="value.name"
                                      :ref="value.indicatorCode + valueIndex"
                                      :prop="'ruleList.' + index + '.ruleDetail.' + valueIndex + '.threshold'"
                                      :rules="{
                                        required: item.isRequired == 1 ? true : false,
                                        message: `${value.name}必选`,
                                        trigger: 'change',
                                      }"
                                      v-else-if="value.modelType == 'tagBox'"
                                    >
                                      <a-select
                                        :disabled="!editShow"
                                        mode="tags"
                                        style="width: 95%"
                                        placeholder="按回车生成"
                                        v-model="value.threshold"
                                        dropdownClassName="display-none-selset"
                                        :token-separators="[',', ' ', '，']"
                                        :maxTagCount="3"
                                      >
                                      </a-select>
                                    </a-form-model-item>
                                  </div>
                                </div>
                              </template>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="row-item" v-else-if="item.ruleType == 'group' && item.isCopy == 1" :key="index">
                    <div class="hint-item">
                      <a-tooltip>
                        <template slot="title">
                          {{ item.remark }}
                        </template>
                        <a-icon type="question-circle" />
                      </a-tooltip>
                    </div>
                    <div class="label-item">
                      <div class="text-item">{{ item.groupName }}</div>
                      <div class="required-item" v-if="item.isRequired == 1"></div>
                    </div>
                    <div class="input-item">
                      <div class="toolbox-automate-rules-create-content_rules-and-condition_rules">
                        <div class="content">
                          <div
                            class="rules-list"
                            v-for="(valueElse, valueIndex) of item.ruleDetail"
                            :key="valueIndex + 'ruleDetail'"
                          >
                            <div class="rules-list-item">
                              <template v-for="(value, valueElseIndex) of valueElse">
                                <div
                                  class="row-item row-group"
                                  v-if="value.variableType == 1"
                                  :key="valueElseIndex + 'valueElse'"
                                >
                                  <!-- <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
                                      :label-col="{ span: 6 }"
                                      :wrapper-col="{ span: 18 }"
                                      :label="value.name"
                                      :ref="value.indicatorCode + valueIndex"
                                      :prop="
                                        'ruleList.' +
                                        index +
                                        '.ruleDetail.' +
                                        valueIndex +
                                        '.' +
                                        valueElseIndex +
                                        '.threshold'
                                      "
                                      :rules="{
                                        required: item.isRequired == 1 ? true : false,
                                        message: `${value.name}必填`,
                                        trigger: 'blur',
                                      }"
                                      v-if="value.modelType == 'numberText'"
                                    >
                                      <span style="color: red; font-size: 16px; font-weight: 500">
                                        {{ value.ruleCondition | conditionName }}
                                      </span>
                                      <a-input-number
                                        :disabled="!editShow"
                                        style="width: 100px; margin-right: 5px"
                                        v-model="value.threshold"
                                        :min="0"
                                      />{{ value.dataUnit }}
                                    </a-form-model-item>
                                    <a-form-model-item
                                      :label-col="{ span: 6 }"
                                      :wrapper-col="{ span: 18 }"
                                      :label="value.name"
                                      :ref="value.indicatorCode + valueIndex"
                                      :prop="
                                        'ruleList.' +
                                        index +
                                        '.ruleDetail.' +
                                        valueIndex +
                                        '.' +
                                        valueElseIndex +
                                        '.threshold'
                                      "
                                      :rules="{
                                        required: item.isRequired == 1 ? true : false,
                                        message: `${value.name}必填`,
                                        trigger: 'blur',
                                      }"
                                      v-else-if="value.modelType == 'text'"
                                    >
                                      <a-input
                                        :disabled="!editShow"
                                        v-model="value.threshold"
                                        style="width: 95%"
                                        @change="inputChange"
                                      />
                                    </a-form-model-item>
                                    <a-form-model-item
                                      :label-col="{ span: 6 }"
                                      :wrapper-col="{ span: 18 }"
                                      :label="value.name"
                                      :ref="value.indicatorCode + valueIndex"
                                      :prop="
                                        'ruleList.' +
                                        index +
                                        '.ruleDetail.' +
                                        valueIndex +
                                        '.' +
                                        valueElseIndex +
                                        '.threshold'
                                      "
                                      :rules="{
                                        required: item.isRequired == 1 ? true : false,
                                        message: `${value.name}必选`,
                                        trigger: 'change',
                                      }"
                                      v-else-if="value.modelType == 'select' || value.modelType == 'checkBox'"
                                    >
                                      <selectGroup
                                        :disabled="!editShow"
                                        v-model="value.threshold"
                                        :code="value.dictId"
                                        :requestUrl="value.requestUrl"
                                        :multiple="
                                          value.dataType == 'string' ||
                                          value.dataType == 'number' ||
                                          value.indicatorCode == 'presentedVideo' ||
                                          value.indicatorCode == 'hideIfExists'
                                            ? false
                                            : true
                                        "
                                        style="width: 95%"
                                        @clearValidate="clearAll"
                                      />
                                    </a-form-model-item>
                                    <a-form-model-item
                                      :label-col="{ span: 6 }"
                                      :wrapper-col="{ span: 18 }"
                                      :label="value.name"
                                      :ref="value.indicatorCode + valueIndex"
                                      :prop="
                                        'ruleList.' +
                                        index +
                                        '.ruleDetail.' +
                                        valueIndex +
                                        '.' +
                                        valueElseIndex +
                                        '.threshold'
                                      "
                                      :rules="{
                                        required: item.isRequired == 1 ? true : false,
                                        message: `${value.name}必选`,
                                        trigger: 'change',
                                      }"
                                      v-else-if="value.modelType == 'tagBox'"
                                    >
                                      <a-select
                                        :disabled="!editShow"
                                        mode="tags"
                                        style="width: 95%"
                                        placeholder="按回车生成"
                                        v-model="value.threshold"
                                        dropdownClassName="display-none-selset"
                                        :token-separators="[',', ' ', '，']"
                                        :maxTagCount="3"
                                      >
                                      </a-select>
                                    </a-form-model-item>
                                  </div>
                                </div>
                                <div
                                  class="rules-list-item-delete"
                                  v-if="item.isCopy == 1"
                                  @click="addData(item, valueElse, valueIndex)"
                                  :key="valueElseIndex"
                                >
                                  {{ valueIndex == 0 ? '复建' : '删除' }}
                                </div>
                              </template>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              
              </template>
            </div>
          </a-form-model>
        </div>
      </a-spin>
    </div>
    <switchConfig :disabled="!editShow" v-if="form.mediaType == 1 || form.mediaType == 3" />
    <div class="toolbox-automate-rules-create-body" v-if="editShow">
      <div class="moduler">
        <div class="opt">
          <a-button type="default" style="margin-right: 15px" @click="goBack">{{
            editShow ? '取消' : '返回'
          }}</a-button>
          <a-button
            type="primary"
            style="margin-right: 15px"
            @click="saveHandler"
            :loading="saveLoading"
            v-if="editShow"
            >确定</a-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { isArray } from '@/utils/Tools'
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'
import selectGroup from '@/components/formComponents/selectGroup'
import checkBoxGroup from '@/components/formComponents/checkBoxGroup'
import timeRange from '@/components/formComponents/timeRange'
import scheduleTime from '@/components/formComponents/toutiaoTime'
import region from '@/components/formComponents/selectRegion'
import switchConfig from './switchConfig'
let str = '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
function changeString (str, num){
  let strArr = str.split('')
  for (let i = num; i < strArr.length; i+=(num+1)) {
    strArr[i] = 1
  }
  return strArr.join('')
}
let statusList = [
  {
    id: 2,
    value: '1',
    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,
    selectGroup,
    checkBoxGroup,
    timeRange,
    switchConfig,
    scheduleTime,
    region,
  },
  data() {
    return {
      editShow: false,
      current: 0,
      spinLoading: false,
      // allCol: {
      //   labelCol: { span: 6 },
      //   wrapperCol: { span: 18 },
      // },
      wrapperCol: { span: 14 },
      ceshi: [],
      ceshi2: [],
      time: [moment('2020/11/16', 'YYYY-MM-DD'), moment('2020/11/17', 'YYYY-MM-DD')],
      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: {},
      rules: {},

      rulesList: [
        {
          metricValueName: '',
          metricValueCode: '',
          dataRange: 'CURRENT_DAY_DATA',
          judgeMethod: 'GT_EQ',
          judgeType: 'MONEY',
          threshold: 0,
          minThreshold: 0,
          campaignStatus: undefined,
          unitStatus: undefined,
        },
      ],

      accountFieldList: [],
      campaignFieldList: [],
      unitFieldList: [],
      textData: {
        success: true,
        message: '操作成功！',
        code: 0,
        result: {
          templateName: '测试模板',
          applyAccount: '',
          ruleList: [
            {
              groupName: '成本限额',
              operate: '',
              ruleDetail: [
                {
                  variableType: 1,
                  ruleCondition: 'greater_equal',
                  ruleDimension: 'account',
                  dataType: 'number',
                  indicatorCode: 'convert_cost',
                  name: '转化成本',
                  ruleName: '转化成本',
                  threshold: '0',
                  dictId: '',
                  ruleId: 9,
                  dataUnit: '元',
                },
              ],
              groupId: 4,
              ruleType: 'base',
              sendType: '',
              ruleRelationship: 'and',
              remark: '转化成本大于等于设置值X，报警',
            },
            {
              groupName: '消耗限额',
              operate: '',
              ruleDetail: [
                {
                  variableType: 1,
                  ruleCondition: 'greater_equal',
                  ruleDimension: 'plan',
                  dataType: 'number',
                  indicatorCode: 'cost',
                  name: '消耗',
                  ruleName: '消耗',
                  threshold: '0',
                  dictId: '',
                  ruleId: 10,
                  dataUnit: '元',
                },
              ],
              groupId: 5,
              ruleType: 'base',
              sendType: '',
              ruleRelationship: 'and',
              remark: '消耗大于等于设置值X，触发报警',
            },
            {
              groupName: '账户余额限额',
              operate: '',
              ruleDetail: [
                {
                  variableType: 1,
                  ruleCondition: 'less_equal',
                  ruleDimension: 'account',
                  dataType: 'number',
                  indicatorCode: 'validBalance',
                  name: '账户余额',
                  ruleName: '账户余额',
                  threshold: '0',
                  dictId: '',
                  ruleId: 11,
                  dataUnit: '元',
                },
              ],
              groupId: 6,
              ruleType: 'base',
              sendType: '',
              ruleRelationship: 'and',
              remark: '账户余额小于等于设置值X，报警',
            },
            {
              groupName: '广告位付费',
              operate: '',
              ruleDetail: [
                {
                  variableType: 1,
                  ruleCondition: 'equal',
                  ruleDimension: 'plan',
                  dataType: 'string',
                  indicatorCode: 'pricing',
                  name: '付费方式',
                  ruleName: '付费方式',
                  threshold: '',
                  dictId: 'ba22a2f2777f7156a7bd814dafc36637',
                  ruleId: 12,
                  dataUnit: '',
                },
                {
                  variableType: 1,
                  ruleCondition: 'contain',
                  ruleDimension: 'target',
                  dataType: 'array',
                  indicatorCode: 'inventoryType',
                  name: '媒体广告位',
                  ruleName: '媒体广告位',
                  threshold: '0',
                  dictId: 'eb595236fd3891c7d283986464eb40e5',
                  ruleId: 13,
                  dataUnit: '',
                },
              ],
              groupId: 7,
              ruleType: 'group',
              sendType: '',
              ruleRelationship: 'and',
              remark: '预警系统设置付费方式X，且媒体广告位为Y，触发报警',
            },
          ],
          mediaType: 1,
          templateId: 3,
        },
        timestamp: 1605605725236,
      },
    }
  },
  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: {
    inputChange(value) {
      value.threshold = value.threshold.trim()
    },
    addData(valueElse, value, index) {
      // alert(1)
      if (index == 0) {
        var data = JSON.parse(JSON.stringify(value))
        data = data.map((item) => {
          return {
            ...item,
            threshold: undefined,
          }
        })
        valueElse.ruleDetail.push(data)
      } else {
        valueElse.ruleDetail.splice(index, 1)
      }
    },
    disabledDate(current) {
      return current && current < moment().subtract(1, 'days')
    },

    // 获取计划列表
    getCampaignList() {
      getAction('/kuaishou/batch/getCampaignList', {
        accountId: this.form.applyAccount,
        putStatus: 1,
        pageNo: 1,
        pageSize: 100000,
      }).then((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) => {
        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) {
    },

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

    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()
    },

    displayRender({ labels }) {
      return labels[labels.length - 1]
    },

    saveHandler() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // this.form.rulesList=this.rulesList;
          var str = ''
          for (let i = 0; i < 7 * 24; i++) {
            str += '0'
          }
          var datas = []
          datas = this.form.ruleList.map((item) => {
            return {
              ...item,
              operationThreshold:item.operationValue=='price'?item.operationThreshold:item.operationThreshold/100,
              ruleDetail: item.ruleDetail.map((end) => {
                if (isArray(item.ruleDetail[0])) {
                  var data = end.map((c) => {
                    return {
                      ...c,
                      threshold: isArray(c.threshold)
                        ? c.dataType != 'array'
                          ? c.threshold[0]
                          : JSON.stringify(c.threshold)
                        : c.threshold,
                    }
                  })
                  return data
                } else {
                  return {
                    ...end,
                    threshold: isArray(end.threshold)
                      ? end.dataType == 'array'
                        ? end.modelType == 'region'
                          ? JSON.stringify(
                              end.threshold.map((c) => {
                                return c.value
                              })
                            )
                          : JSON.stringify(end.threshold)
                        : end.threshold[0]
                      : end.modelType == 'scheduleTime'
                      ? end.threshold == str
                        ? ''
                        : end.threshold
                      : end.ruleCondition == 'between'?end.threshold+'~'+end.thresholdTwo:end.threshold,
                  }
                }
              }),
            }
          })
          var params = {
            ...this.form,
            ruleList: datas,
            accountId: JSON.parse(localStorage.getItem('getRuleDetail')).accountId,
          }
          this.saveLoading = true
          postAction('/ruleAccountThreshold/fillThreshold', params).then((res) => {
            if (res.success) {
              this.saveLoading = false
              // this.goBack()
              this.$router.replace('/earlyWarningRules/useRuleList')
              this.$bus.$emit('remove', '/earlyWarningRules/ruleModule')
            }
          })
        } else {
          this.$message.error('请按提示填写必填项！')
          return false
        }
      })
    },

    goBack() {
      this.$router.replace('/earlyWarningRules/useRuleList')
      this.$bus.$emit('remove', '/earlyWarningRules/ruleModule')
    },

    //分页页码改变
    pageNoChange(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) {
      if (this.accountID) {
        this.getExsitGroupList()
      } else {
        this.$message.warning('请选择账户后重试！')
        this.selectedCampaignValue = undefined
      }
    },
    clearAll(data) {
      this.$nextTick(() => {
        // if (data.length == 0) {
        setTimeout(() => {
          this.$refs.ruleForm.clearValidate()
        }, 100)
        // }
      })
    },
  },

  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) {

      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
    //     }
    // })
    



    var data = JSON.parse(localStorage.getItem('getRuleDetail'))
    this.editShow = data.edit
    if (data.edit) {
      this.spinLoading = true

      getAction('/ruleTemplate/queryDetailByAccountIdAndTemplateId', {
        templateId: data.id,
        accountId: data.accountId,
      }).then((res) => {
        if (res.success) {
          this.form = res.result

          var data = this.form.ruleList.map((item) => {
            return {
              ...item,
              operationThreshold:!!item.operationThreshold?item.operationValue=='price'?item.operationThreshold:item.operationThreshold*100:undefined,
              ruleDetail: item.ruleDetail.map((end) => {
                if (isArray(end)) {
                  var data = end.map((c) => {
                    return {
                      ...c,
                      thresholdTwo:undefined,
                      threshold:
                        c.modelType == 'tagBox'
                          ? c.threshold == null
                            ? undefined
                            : c.threshold
                          : c.modelType == 'checkBox'
                          ? c.dataType == 'array'
                            ? c.threshold
                            : [c.threshold]
                          : c.threshold,
                    }
                  })
                  return [...data]
                } else {
                  return {
                    ...end,
                    thresholdTwo:end.threshold&&end.ruleCondition == 'between'?end.threshold.split('~')[1]:undefined,
                    threshold:
                      end.modelType == 'tagBox'
                        ? end.threshold == null
                          ? undefined
                          : end.threshold
                        : end.modelType == 'checkBox'
                        ? end.dataType == 'array'
                          ? end.threshold
                          : [end.threshold]
                        : end.threshold&&end.ruleCondition == 'between'?end.threshold.split('~')[0]:end.threshold
                  }
                }
              }),
            }
          })
          this.form.ruleList = data
          this.spinLoading = false
        } else {
          this.spinLoading = false
        }
      })
    } else {
      this.spinLoading = true
      getAction('/ruleTemplate/previewTemplate', { id: data.id }).then((res) => {
        if (res.success) {
          this.form = res.result
          var str = ''
          for (let i = 0; i < 7 * 24; i++) {
            str += '0'
          }
          var data = this.form.ruleList.map((item) => {
            return {
              ...item,
              ruleDetail: item.ruleDetail.map((end) => {
                if (isArray(end)) {
                  var data = end.map((c) => {
                    return {
                      ...c,
                      threshold:
                        c.modelType == 'tagBox' ? undefined : c.modelType == 'scheduleTime' ? str : end.threshold,
                    }
                  })
                  return [...data]
                } else {
                  return {
                    ...end,
                    threshold:
                      end.modelType == 'tagBox' ? undefined : end.modelType == 'scheduleTime' ? str : end.threshold,
                  }
                }
              }),
            }
          })
          this.form.ruleList = data
          this.spinLoading = false
        } else {
          this.spinLoading = false
        }
      })
    }
  },
}
</script>

<style lang="scss" scoped>
.ruleModule {
  .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-group {
      margin-bottom: 0 !important;
    }
    .row-item {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-bottom: 20px;
    }
    .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: 140px;
      min-width: 140px;
      .text-item {
        font-size: 14px;
        width: 120px;
      }
    }
    .row-item .required-item::after {
      content: '*';
      // width: 4px;
      // height: 4px;
      // border-radius: 2px;
      // background: #f45858;
      color: #f5222d;
      font-size: 14px;
      position: absolute;
      left: -40px;
      top: -1px;
      font-family: SimSun, sans-serif;

      // 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 {
      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 {
      .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: 10px;
        background: #f8f9fa;
        border-radius: 4px;
        display: flex;
        align-items: center;
        position: relative;
        flex-wrap: wrap;
        .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%, 0.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">
.ruleModule {
  .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;
  }
}
</style>