<template>
  <el-row>
    <!-- 文本类型 -->
    <el-col :span="24" v-if="ruleType == 1">
      <el-form
        :model="form"
        ref="form1"
        class="sub-form"
        :validate-on-rule-change="false"
        :rules="rules"
      >
        <el-form-item label="条件明细" label-width="80px" prop="condition">
          <el-select
            style="width:100%;minWidth: 240px"
            v-model="form.name"
            filterable
            remote
            clearable
            :loading="showDrop"
            loading-text="加载中..."
            @change="changeWord"
            @visible-change="handleVisible"
            placeholder="搜索条件明细"
            :remote-method="searchCondition"
            reserve-keyword
            ref="conditionListName"
          >
            <el-option
              v-for="item in conditionList"
              :key="item.id + item.name"
              :label="item.name + '('+item.conditionLabel + ')'"
              :value="item.id"
              :title="item.name +  '('+item.conditionLabel + ')'"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-col>
    <el-col :span="24" v-if="ruleType == 2">
      <el-col :span="8">
        <el-form
          :model="form"
          ref="form"
          class="sub-form"
          :validate-on-rule-change="false"
          :rules="rules"
        >
          <el-row>
            <el-form-item label="条件明细" label-width="80px" prop="condition">
              <el-select
                style="width:100%"
                v-model="form.name"
                :title="form.name"
                filterable
                remote
                clearable
                :loading="showDrop"
                loading-text="加载中..."
                @change="changeWord"
                @visible-change="handleVisible"
                placeholder="搜索开单项目"
                :remote-method="searchCondition"
                reserve-keyword
                ref="conditionListName"
              >
                <el-option
                  v-for="item in conditionList"
                  :key="item.id + item.name"
                  :label="item.name + '('+item.conditionLabel + ')'"
                  :value="item.id"
                  :title="item.name + '('+item.conditionLabel + ')'"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label label-width="0px">
              <span class="font">1</span>
            </el-form-item>
          </el-row>
        </el-form>
      </el-col>
      <el-form :rules="rules1" ref="ruleForm" :model="ruleForm">
        <el-col :span="16" v-for="(item,index) in ruleForm.ruleForm" :key="index">
          <el-row>
            <el-col :span="8">
              <el-form-item label-width="0px" prop="compare">
                <el-select
                  v-model="item.compare"
                  placeholder="请输入比较"
                  style="width: 100%"
                  ref="compare"
                  clearable
                  @clear="handleClear(index)"
                  @change="handleChangeCom(index)"
                >
                  <!-- <el-option
                    label="大于"
                    value=">"
                    :disabled="index=== 0 ? isCompare1==='>' : isCompare2==='>'"
                  ></el-option>-->
                  <el-option
                    label="大于等于"
                    value=">="
                    :disabled="index=== 0 ? isCompare1==='>=' : isCompare2==='>='"
                  ></el-option>
                  <!-- <el-option
                    label="小于"
                    value="<"
                    :disabled="index=== 0 ? isCompare1==='<' : isCompare2==='<'"
                  ></el-option>-->
                  <el-option
                    label="小于等于"
                    value="<="
                    :disabled="index=== 0 ? isCompare1==='<=' : isCompare2==='<='"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="0px" :prop="index===0?'amount0':'amount1'">
                <el-input
                  clearable
                  v-model="item.value"
                  placeholder="填写数值"
                  @blur="handleValue('value',index)"
                  :disabled="item.compare ==''"
                  :ref="index===0?'amount0':'amount1'"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="0px" :prop="index===0?'unit0':'unit1'">
                <el-input
                  clearable
                  v-model="item.unit"
                  placeholder="填写单位"
                  @blur="handleValue('unit',index)"
                  :ref="index===0?'unit0':'unit1'"
                  :disabled="index==1"
                  @clear="handleUnitClear(index)"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1" class="operation">
              <div class="icon">
                <img src="../../../images/plus.png" v-if="!isOpen" @click="addForm()" />
                <img src="../../../images/cut.png" v-if="isOpen" @click="cutForm(index)" />
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import api from '@api/icss.js';
export default {
  name: 'ConditionForm',
  props: ['data', 'type', 'conceptName', 'ruleType'],
  data() {
    let checkFrequency = (rule, value, callback) => {
      let conditionListName = this.$refs.conditionListName.value;
      if (conditionListName === '') {
        callback('请输入条件明细');
      } else {
        callback();
      }
    };
    let checkFrequency1 = (rule, value, callback) => {
      let amount0 = this.$refs['amount0'][0].value;
      if (amount0 === '') {
        callback('请输入数值');
      } else {
        callback();
      }
    };
    let checkFrequency2 = (rule, value, callback) => {
      let amount1 = this.$refs['amount1'][0].value;
      if (amount1 === '') {
        callback('请输入数值');
      } else {
        callback();
      }
    };
    let checkFrequency3 = (rule, value, callback) => {
      let unit0 = this.$refs['unit0'][0].value;
      if (unit0 === '') {
        callback('请输入单位');
      } else {
        callback();
      }
    };
    let checkFrequency4 = (rule, value, callback) => {
      let unit1 = this.$refs['unit1'][0].value;
      if (unit1 === '') {
        callback('请输入单位');
      } else {
        callback();
      }
    };
    return {
      showDrop: false,
      conditionList: [],
      form: {
        conditionLabel: '',
        id: '',
        maxValue: '',
        minValue: '',
        name: '',
        range: '',
        status: '',
        unit: ''
      },
      ruleForm: {
        ruleForm: [
          {
            compare: '',
            value: '',
            unit: ''
          }
        ]
      },
      rules: {
        condition: [
          {
            required: true,
            validator: checkFrequency,
            trigger: ['blur', 'change']
          }
        ]
      },
      rules1: {
        amount0: [
          {
            required: true,
            validator: checkFrequency1,
            trigger: 'change'
          }
        ],
        amount1: [
          {
            required: true,
            validator: checkFrequency2,
            trigger: 'change'
          }
        ],
        unit0: [
          {
            required: true,
            validator: checkFrequency3,
            trigger: 'change'
          }
        ],
        unit1: [
          {
            required: true,
            validator: checkFrequency4,
            trigger: 'change'
          }
        ]
      }
    };
  },
  computed: {
    isOpen() {
      if (this.ruleForm.ruleForm.length === 2) {
        return true;
      } else {
        return false;
      }
    },
    isCompare1() {
      const { ruleForm } = this.ruleForm;
      if (ruleForm.length != 2) return false;
      if (ruleForm[1].compare == '') {
        return false;
      } else if (ruleForm[1].compare == '>=') {
        return '>=';
      } else if (ruleForm[1].compare == '<=') {
        return '<=';
      }
    },
    isCompare2() {
      const { ruleForm } = this.ruleForm;
      if (ruleForm.length != 2) return false;
      if (ruleForm[0].compare == '') {
        return false;
      } else if (ruleForm[0].compare == '>=') {
        return '>=';
      } else if (ruleForm[0].compare == '<=') {
        return '<=';
      }
    }
  },
  created() {
    this._initData();
  },
  mounted() {},
  methods: {
    _initData() {
      this.form = { ...this.data };
      const { maxValue, minValue, unit } = this.form;
      // console.log(this.form, 'this.form');
      this.form.name = this.form.conditionLabel
        ? `${this.form.name}(${this.form.conditionLabel})`
        : '';
      // console.log(maxValue, 'maxValue', minValue, 'minValue');
      if (minValue === null && maxValue === null) {
        this.ruleForm.ruleForm = [
          {
            compare: '',
            value: '',
            unit: ''
          }
        ];
      } else if (minValue === null && maxValue !== null) {
        this.ruleForm.ruleForm = [
          {
            compare: '<=',
            value: maxValue,
            unit: unit
          }
        ];
      } else if (minValue !== null && maxValue === null) {
        this.ruleForm.ruleForm = [
          {
            compare: '>=',
            value: minValue,
            unit: unit
          }
        ];
      } else if (minValue !== '' && maxValue !== '') {
        this.ruleForm.ruleForm = [
          {
            compare: '>=',
            value: minValue,
            unit: unit
          },
          {
            compare: '<=',
            value: maxValue,
            unit: unit
          }
        ];
      } else {
        this.ruleForm.ruleForm = [
          {
            compare: '',
            value: '',
            unit: ''
          }
        ];
      }
    },
    changeWord(val) {
      if (val === '') return;
      let condition = this.conditionList.find(item => item.id == val);
      // console.log(condition, 'condition');
      this.form.name = condition.conditionLabel
        ? `${condition.name}(${condition.conditionLabel})`
        : '';
      this.$emit('split', condition);
    },
    handleClear(index) {
      // this.ruleForm.ruleForm[index].value = '';
    },
    handleChangeCom(index) {
      let compare = this.ruleForm.ruleForm[index].compare;
      if (index === 0 && this.ruleForm.ruleForm.length == 1) {
        if (compare == '>=') {
          this.form.maxValue = '';
          this.$emit('handleInput', {
            type: 'maxValue',
            value: this.form.maxValue
          });
        } else if (compare == '<=') {
          this.form.minValue = '';
          this.$emit('handleInput', {
            type: 'minValue',
            value: this.form.minValue
          });
        }
      }
      // console.log(compare);
      this.ruleForm.ruleForm[index].value = '';
    },
    handleUnitClear(index) {
      // 两条规则
      if (index === 0 && this.ruleForm.ruleForm.length == 2) {
        this.ruleForm.ruleForm[1].unit = '';
      }
    },
    // handleSelectChange(val) {
    //   console.log(val, '===========');
    //   this.$refs.form.clearValidate();
    //   this.rules.compare = this.rules.compare.slice(0, 1);
    // },
    handleVisible(flag) {
      if (!flag) {
        this.conditionList = [];
      }
    },
    // 搜索列表
    searchCondition(query) {
      const { data, type, conceptName, ruleType } = this;
      if (!query) {
        this.conditionList = [];
        return;
      }
      this.showDrop = true;
      let params = {
        type,
        conceptName,
        ruleType,
        conditionName: query
      };
      api.conditionBillmanIndex(params).then(res => {
        this.showDrop = false;
        if (res.data.code == '0') {
          this.conditionList = res.data.data;
        }
      });
    },
    // 编辑规则
    handleValue(from, idx) {
      let item = this.ruleForm.ruleForm.find((item, index) => index == idx);
      if ((item.compare == '>' || item.compare == '>=') && from == 'value') {
        this.form.minValue = item.value;
        this.$emit('handleInput', {
          type: 'minValue',
          value: this.form.minValue
        });
      } else if (
        (item.compare == '<' || item.compare == '<=') &&
        from == 'value'
      ) {
        this.form.maxValue = item.value;
        this.$emit('handleInput', {
          type: 'maxValue',
          value: this.form.maxValue
        });
      } else if (from === 'unit') {
        console.log(item, 'unit');
        this.form.unit = item.unit;
        this.$emit('handleInput', {
          type: 'unit',
          value: this.form.unit
        });
        // 两条规则
        if (idx === 0 && this.ruleForm.ruleForm.length == 2) {
          this.ruleForm.ruleForm[1].unit = item.unit;
        }
      }
    },

    // 新增表单
    addForm() {
      if (this.ruleForm.ruleForm.length === 2) return;
      this.ruleForm.ruleForm.push({
        compare: '',
        value: '',
        unit: ''
      });
      // 两条规则
      if (this.ruleForm.ruleForm.length == 2) {
        this.ruleForm.ruleForm[1].unit = this.ruleForm.ruleForm[0].unit;
      }
    },
    // 减少表单
    cutForm(i) {
      let item = this.ruleForm.ruleForm.find((item, index) => index == i);
      // console.log(item, '==========');
      if (item.compare == '>' || item.compare == '>=') {
        this.form.minValue = '';
        this.$emit('handleInput', {
          type: 'minValue',
          value: this.form.minValue
        });
      } else if (item.compare == '<' || item.compare == '<=') {
        this.form.maxValue = '';
        this.$emit('handleInput', {
          type: 'maxValue',
          value: this.form.maxValue
        });
      }
      this.ruleForm.ruleForm.splice(i, 1);
    }
  }
};
</script>

<style lang="less">
.condition {
  /deep/ .el-form-item__label {
    margin-left: 12px !important;
  }
  /deep/ .el-col {
    padding-left: 0px !important;
    padding-right: 4px !important;
  }
  /deep/ .el-form-item__error {
    float: left;
    top: 40px;
    left: 12px;
  }
}

.conditionName {
  /deep/ .el-col {
    padding-left: 0px !important;
    padding-right: 0px !important;
  }
}
.operation {
  width: 0;
  height: 30px;
  position: relative;
  .icon:before {
    box-sizing: border-box;
    position: absolute;
    top: 20px;
    left: 20px;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    width: 30px;
    content: '';
    height: 30px;
  }
  img {
    position: relative;
    width: 30px;
    height: 30px;
    top: 5px;
    left: 10px;
  }
}
.font {
  color: #fff;
}
</style>