<template>
  <div class="reliability-setting-content">
    <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="0px" label-position='right'
             class="demo-dynamic">
      <div class="setting-top">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="预警：" prop="rulesType" label-width="120px"
            >
              <el-radio-group
                  v-model="dynamicValidateForm.rulesType"
                  size="mini" @change='rulesTypeChange()'
              >
                <el-radio label="1">有</el-radio>
                <el-radio label="2">无</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <div class="naxtBox">
            <el-button v-if="dynamicValidateForm.rulesType === '1'"
                       size="mini" v-show="dynamicValidateForm.domains.length < config.riskLevelList.length"
                       class="addFactor" type="primary" @click="addDomain">新增预警
            </el-button>
            <el-button v-show="showPreviousBtn" type="primary" size="mini" @click="previousTab()">上一步</el-button>
            <el-button type="primary" size="mini" @click="submitForm('dynamicValidateForm')">下一步</el-button>
          </div>
        </el-row>
      </div>
      <div class="reliabilityBox">
        <div class="reliabilityItem" v-for="(domain, index) in dynamicValidateForm.domains" :key="domain.key">
          如果满足以下：
          <el-form-item
              class="lineBox"
              label=""
              :prop="'domains.' + index + '.condition'"
              :rules="{
                required: true, message: '请选择条件', trigger: 'change'
              }"
          >
            <el-select v-model="domain.condition" placeholder="请选择">
              <el-option
                  v-for="item in config.conditionList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          条件，风险等级设定为：
          <el-form-item
              class="lineBox"
              label=""
              :prop="'domains.' + index + '.riskLevel'"
              :rules="{
                required: true, message: '请选择', trigger: 'change'
              }"
          >
            <el-select v-model="domain.riskLevel" placeholder="请选择" @change='riskLevelChange(index, domain.riskLevel)'>
              <el-option
                  v-for="item in config.riskLevelList"
                  :key="item.value"
                  :disabled="item.disabled"
                  :label="item.name"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-row :gutter="20" v-for="(item1, index1) in domain.conditionitem" :key="item1.key">
            <el-col :span="5">
              <el-form-item
                  :prop="`domains.${index}.conditionitem.${index1}.factor`"
                  :rules="{
                required: true, message: '请选择条件', trigger: 'change'
              }"
              >
                <el-select v-if="showUid" v-model="item1.uid" placeholder="请选择因子" @change='uidChange(index, index1)'
                >
                  <el-option
                      v-for="item in factorListAll"
                      :key="item.uid"
                      :label="item.title"
                      :value="item.uid">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <!-- 得分 -->
              <el-form-item
                  label-width="0"
                  :prop="`domains.${index}.conditionitem.${index1}.scoreType`"
                  :rules="{
                    required: true, message: '请选择得分', trigger: 'change'
                  }">
                  <el-select v-model="item1.scoreType" placeholder="请选择得分">
                    <el-option key="ORIGINAL" label="原始分" value="ORIGINAL" />
                    <el-option
                        :disabled="item1.standardScoreType === '2'"
                        key="STANDARD" label="标准分" value="STANDARD" />
                    <el-option
                      :disabled="item1.averageScoreType === '2'"
                      key="AVERAGE" label="平均分" value="AVERAGE" />
                  </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item
                  :prop="`domains.${index}.conditionitem.${index1}.inequality`"
                  :rules="{
                required: true, message: '请选择条件', trigger: 'change'
              }"
              >
                <el-select v-model="item1.inequality" placeholder="请选择条件">
                  <el-option
                      v-for="item in config.inequalityList"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item
                  :prop="`domains.${index}.conditionitem.${index1}.value`"
                  :rules="{
                required: true, message: '不能为空', trigger: 'blur'
              }"
              >
                <el-input v-model="item1.value"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <!-- 删除因子 -->
              <div class="iconBox">

                <i class="el-icon-error deleteIcon"
                   v-if="dynamicValidateForm.domains[index].conditionitem.length != 1"
                   @click.prevent="removeConditionitem(index,index1)"></i>
              </div>
              <!-- 新增因子 -->
              <div class="iconBox">

                <i v-if="
              (dynamicValidateForm.domains[index].conditionitem.length - 1 === index1)
              "
                   class="el-icon-circle-plus-outline addIcon"
                   @click.prevent="addConditionitem(index)"></i>
              </div>
            </el-col>
          </el-row>
          <el-button v-if="dynamicValidateForm.domains.length > 1" type="primary" @click="removeDomain(domain)">删除
          </el-button>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import config from './config'

export default {
  name: 'warning',
  props: {
    factorList: [Array, Object],
  },
  data () {
    return {
      configName: 'warning', // 配置名称
      showPreviousBtn: false,

      config,
      score: '得分',
      totalScoreType: '', // ‘1’有总分，‘2’无
      totalAverageScoreType: '2', // 总均分计算‘1’有总分，‘2’无
      totalStandardType: '2', // 总标准分‘1’有总分，‘2’无
      dynamicValidateForm: {
        rulesType: '2',
        domains: [
          // {
          //   condition: '',
          //   riskLevel: '',
          //   conditionitem:[
          //     {
          //       scoreType: '',
          //       factor: '', //因子code
                // uid: '', // 因子uid
                // standardScoreType: '', // ‘1’有标准分，‘2’无
                // averageScoreType: '', // ‘1’有标准分，‘2’无
          //       inequality: '',
          //       value: '',
          //     }
          //   ]
          // }
        ],
      },
      factorListAll: [],
      showUid: false //显示因子

    }
  },
  watch: {
    factorList (newValue) {
    }
  },
  methods: {
    loadData () {
      this.totalType()
      // console.log('加载-预警配置',this.factorListAll)

      if (config.localGetConclusionList('updateData', this.configName)) {
        this.dynamicValidateForm = config.localGetConclusionList('updateData', this.configName)
      } else if (config.localGetConclusionList('requestData', this.configName)) {
        this.dynamicValidateForm = config.localGetConclusionList('requestData', this.configName)
      } else {
        this.dynamicValidateForm = {
          rulesType: '2',
          domains: []
        }
      }
      if(!this.dynamicValidateForm.rulesType){
      this.dynamicValidateForm = {
            rulesType: '2',
            domains: []
          }
      }
      // console.log('预警：this.dynamicValidateForm',this.dynamicValidateForm)
      this.showPreviousBtn = config.permissionIndex(this.configName)
		  this.factorListContrast()
    },
    //旧数据兼容，添加保存uid
    factorListContrast(){
      for(let i = 0; i<this.dynamicValidateForm.domains.length; i++){
        for(let j = 0; j<this.dynamicValidateForm.domains[i].conditionitem.length; j++){
          if(this.dynamicValidateForm.domains[i].conditionitem[j].factor != '$total'){
              // 非总分
            if(!this.dynamicValidateForm.domains[i].conditionitem[j].uid){
              // 无uid，其他添加uid
              console.log('无uid，其他添加uid',this.factorListAll,this.dynamicValidateForm)
              let index = this.factorListAll.findIndex(item=>{
                return item.code === this.dynamicValidateForm.domains[i].conditionitem[j].factor
              })
              if(index != -1){
                this.dynamicValidateForm.domains[i].conditionitem[j].uid = this.factorListAll[index].uid
              }else{
                this.dynamicValidateForm.domains[i].conditionitem[j].factor = null
                // console.log('无uid,找不到因子，至空',this.dynamicValidateForm.domains[i].conditionitem[j].factor)
              }
            }else{
              // 有uid，更新code
              let index = this.factorListAll.findIndex(item=>{
                return item.uid === this.dynamicValidateForm.domains[i].conditionitem[j].uid
              })
              if(index != -1){
                this.dynamicValidateForm.domains[i].conditionitem[j].factor = this.factorListAll[index].code
              }else{
                this.dynamicValidateForm.domains[i].conditionitem[j].factor = null
                // console.log('有uid,找不到因子，至空',this.dynamicValidateForm.domains[i].conditionitem[j].factor)
              }
              // console.log('有uid，更新code',this.factorListAll)
              this.typeChange(i, j, index)
            }
          }else{
            // 总分
            // console.log('总分有uid？',this.dynamicValidateForm.domains[i].conditionitem[j].uid)
            let index = this.factorListAll.findIndex(item=>{
              return item.code === this.dynamicValidateForm.domains[i].conditionitem[j].factor
            })
            if(index != -1){
              this.dynamicValidateForm.domains[i].conditionitem[j].uid = '$total'
            }else{
              this.dynamicValidateForm.domains[i].conditionitem[j].factor = null
              // console.log('无uid,找不到因子，至空',this.dynamicValidateForm.domains[i].conditionitem[j].factor)
            }
            // console.log('总分无uid',index,i,j,'this.dynamicValidateForm.domains[i].conditionitem[j]',this.dynamicValidateForm.domains[i].conditionitem[j])

            this.typeChange(i, j, index)
          }
        }
      }
      // console.log('旧数据兼容，添加保存uid',this.dynamicValidateForm,this.factorListAll)
      this.showUid = true
    },
    // 总分
    totalType(){
      let totalScoreType = config.localGetConclusionList('updateData', 'total').totalType

      this.totalAverageScoreType = config.localGetConclusionList('updateData', 'total').totalAverageScoreType
      this.totalStandardType = config.localGetConclusionList('updateData', 'total').totalStandardType
      if(totalScoreType === '1'){
        this.factorListAll = this.factorList.concat({
          code: '$total',
          uid: '$total',
          standardScoreType: this.totalStandardType,
          factorAverageScoreType: this.totalAverageScoreType,
          title: '总分',
        })
      }else{
        this.factorListAll = this.factorList
      }
      // console.log('总分:1有，2无',this.totalScoreType)
    },
    // 上一步
    previousTab () {
      this.showUid = false
      this.$emit('PreviousTab')
    },
    clear () {
      this.dynamicValidateForm.domains = []
      this.riskLevelChange()
    },
    // 风险等级有无 改变
    rulesTypeChange () {
      this.clear()
      this.dynamicValidateForm.domains = []
      if (this.dynamicValidateForm.rulesType === '1') {
        this.addDomain()
      }
    },
    // 风险等级改变
    riskLevelChange (index, Id) {
      this.config.riskLevelList.forEach(v => {
        v.disabled = false
        for (var i = 0; i < this.dynamicValidateForm.domains.length; i++) {
          if (this.dynamicValidateForm.domains[i].riskLevel === v.value) {
            // console.log('this.dynamicValidateForm.domains[i].riskLevel',this.dynamicValidateForm.domains[i].riskLevel,'v.Id',v.value)
            v.disabled = true
          }
        }
      })
      // console.log('this.riskLevelList',this.riskLevelList)

    },
    // 因子改变
    uidChange (id, id1) {
      let index = this.factorListAll.findIndex(item=>{
        return item.uid === this.dynamicValidateForm.domains[id].conditionitem[id1].uid
      })
      this.typeChange(id, id1, index)
    },
    // 标准分、平均分改变
    typeChange(id, id1, index){
      console.log('typeChange----index',index)
      // if(index){
        if(index != -1){
          this.dynamicValidateForm.domains[id].conditionitem[id1].factor = this.factorListAll[index].code
          // console.log('typeChange------,',index,this.factorListAll[index].code)
          // 标准分
          this.dynamicValidateForm.domains[id].conditionitem[id1].standardScoreType = this.factorListAll[index].standardScoreType
          if(this.factorListAll[index].standardScoreType === '2' && this.dynamicValidateForm.domains[id].conditionitem[id1].scoreType === 'STANDARD'){
            // 无标准分
            this.dynamicValidateForm.domains[id].conditionitem[id1].scoreType = ''
          }
          // 均分
          this.dynamicValidateForm.domains[id].conditionitem[id1].averageScoreType = this.factorListAll[index].factorAverageScoreType
          if(this.factorListAll[index].factorAverageScoreType === '2' && this.dynamicValidateForm.domains[id].conditionitem[id1].scoreType === 'AVERAGE'){
            // 无均分
            this.dynamicValidateForm.domains[id].conditionitem[id1].scoreType = ''
          }
        }
    },
    // 提交表单验证
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          config.localSetConclusionList('updateData', this.configName, this.dynamicValidateForm)
          this.showUid = false
          this.$emit('NextTab')
        } else {
          this.$message.error('请检查预警配置')
          console.log('error submit!!')
          return false
        }
      })
    },
    // 清空
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 删除因子
    removeConditionitem (index, index1) {
      // var index = this.dynamicValidateForm.domains.indexOf(item)
      // if (index !== -1) {
      this.dynamicValidateForm.domains[index].conditionitem.splice(index1, 1)
      // }
    },
    // 删除
    removeDomain (item) {
      var index = this.dynamicValidateForm.domains.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1)
      }
      this.config.riskLevelList.forEach(v => {
        if (v.value === item.riskLevel && v.disabled) {
          v.disabled = false
        }
      })
    },
    // 添加
    addConditionitem (index) {

      // if(this.dynamicValidateForm.domains[index].conditionitem.length < this.factorListAll.length){
      let item = {
        scoreType: '',
        factor: '',
        inequality: '',
        uid: '',
        standardScoreType: '',
        averageScoreType: '',
        value: '',
        key: Date.now() + 'n',
      }
      this.dynamicValidateForm.domains[index].conditionitem.push(item)
      // }
    },
    // 添加
    addDomain () {
      // for(let i = 0;i<this.factorListAll.length;i++){
      //   this.factorListAll[i].disabled = false
      // }
      if (this.dynamicValidateForm.domains.length < this.config.riskLevelList.length) {
        let item = {
          condition: '',
          riskLevel: '',
          key: Date.now() + 's',
          conditionitem: [
            {
              scoreType: '',
              factor: '',
              inequality: '',
              uid: '',
              standardScoreType: '',
              averageScoreType: '',
              value: '',
              key: Date.now() + 'n',
            }
          ]
        }
        this.dynamicValidateForm.domains.push(item)
      }
    }
  }
}
</script>

<style scoped>
.reliability-setting-content {
  padding: 0 20px;
  /* padding-top: 36px; */
  position: relative;
}

.setting-top {
  /* width: calc(100% - 40px) !important; */
  padding-top: 20px;
}

.deleteIcon {
  font-size: 24px;
  margin: 6px;
  color: #FF0000;
}

.addIcon {
  font-size: 24px;
  margin: 6px;
  color: #1989FA;
}

/* .addFactor{
  margin-left: 10px;
} */
.naxtBox {
  position: absolute;
  right: 50px;
}

.reliabilityBox {
  /* height: 600px; */
  overflow: auto;
}

.reliabilityItem {
  /* width: 860px; */
  /* height: 220px; */
  background: #F2F9FF;
  padding: 20px;
  margin-bottom: 10px;
}
::v-deep .el-select{
  width: 100%;
}
::v-deep .el-input__inner {
  background: #F2F9FF;
}
::v-deep .el-input--suffix {
  width: 100% !important;
}

.lineBox {
  display: inline-block;
}

.iconBox {
  width: 36px;
  display: inline;
}
</style>
