<template>
  <div>

    <div class="m-main">
      <div v-for="(ruleItem,ruleIndex) in smartRuleList"
           :key="ruleIndex">
        <div class="row-item">
          <el-select class="item_width_1"
                     v-model="ruleItem.selSmartType"
                     size="small"
                     placeholder="请选择">
            <el-option v-for="item in smartList"
                       @click.native="handleSelSmartType(ruleIndex,item)"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>

          <div v-if="ruleItem.selSmartType==='house'"
               class="row-item-one">

            <el-select class="item_width_1"
                       v-model="ruleItem.houseRule.colKey"
                       size="small"
                       placeholder="请选择">
              <el-option v-for="item in houseItemList"
                         @click.native="handleSelHouseItem(ruleIndex,item)"
                         :key="item.colKey"
                         :label="item.label"
                         :value="item.colKey">
              </el-option>
            </el-select>
            <el-select class="item_width_1"
                       v-model="ruleItem.houseRule.queryType"
                       size="small"
                       placeholder="请选择">
              <el-option v-for="item in queryList"
                         @click.native="handleSelHouseQuery(ruleIndex,item)"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
            <div v-if="ruleItem.houseRule.queryType!=='is_null'&&ruleItem.houseRule.queryType!=='is_not_null'">

              <el-select v-if="ruleItem.houseRule.colType==='select'||ruleItem.houseRule.colType==='radio'||ruleItem.houseRule.colType==='checkbox'"
                         class="item_width_2"
                         v-model="ruleItem.houseRule.colVal"
                         size="small"
                         placeholder="请选择">
                <el-option v-for="item in ruleItem.houseRule.colOption"
                           @click.native="handleSelHouseValue(ruleIndex,item)"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
              <el-input-number v-else-if="ruleItem.houseRule.colType==='inputNum'"
                               class="item_width_2"
                               v-model="ruleItem.houseRule.colVal"
                               :min="0"
                               size="small"
                               label="请输入"></el-input-number>
              <el-date-picker v-else-if="ruleItem.houseRule.colType==='datepicker'||ruleItem.houseRule.colType==='date'"
                              v-model="ruleItem.houseRule.colVal"
                              class="item_width_2"
                              type="datetime"
                              size="small"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              value="yyyy-MM-dd HH:mm:ss"
                              placeholder="开始时间">
              </el-date-picker>
              <el-input v-else
                        class="item_width_2"
                        size="small"
                        placeholder="请输入"
                        v-model="ruleItem.houseRule.colVal">
              </el-input>
            </div>

          </div>

          <div v-if="ruleItem.selSmartType==='person'"
               class="row-item-one">

            <el-select class="item_width_1"
                       v-model="ruleItem.personRule.itemGroupId"
                       size="small"
                       placeholder="请选择">
              <el-option v-for="item in groupList"
                         @click.native="handleSelGroup(ruleIndex,item)"
                         :key="item.id"
                         :label="item.label"
                         :value="item.id">
              </el-option>
            </el-select>
            <el-select class="item_width_1"
                       v-model="ruleItem.personRule.itemId"
                       size="small"
                       placeholder="请选择">
              <el-option v-for="item in ruleItem.personRule.itemList"
                         @click.native="handleSelGroupItem(ruleIndex,item)"
                         :key="item.itemId"
                         :label="item.label"
                         :value="item.itemId">
              </el-option>
            </el-select>
            <el-select class="item_width_1"
                       v-model="ruleItem.personRule.queryType"
                       size="small"
                       placeholder="请选择">
              <el-option v-for="item in queryList"
                         @click.native="handleSelPersonQuery(ruleIndex,item)"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
            <div v-if="ruleItem.personRule.queryType!=='is_null'&&ruleItem.personRule.queryType!=='is_not_null'">

              <el-select v-if="ruleItem.personRule.colType==='select'||ruleItem.personRule.colType==='radio'||ruleItem.personRule.colType==='checkbox'"
                         class="item_width_2"
                         v-model="ruleItem.personRule.colVal"
                         size="small"
                         placeholder="请选择">
                <el-option v-for="item in ruleItem.personRule.colOption"
                           @click.native="handleSelPersonValue(ruleIndex,item)"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
              <el-input-number v-else-if="ruleItem.personRule.colType==='inputNum'"
                               class="item_width_2"
                               v-model="ruleItem.personRule.colVal"
                               :min="0"
                               size="small"
                               label="请输入"></el-input-number>

              <el-date-picker v-else-if="ruleItem.personRule.colType==='datepicker'||ruleItem.personRule.colType==='date'"
                              v-model="ruleItem.personRule.colVal"
                              class="item_width_2"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              value="yyyy-MM-dd HH:mm:ss"
                              placeholder="开始时间">
              </el-date-picker>
              <el-input v-else
                        class="item_width_2"
                        size="small"
                        placeholder="请输入"
                        v-model="ruleItem.personRule.colVal">
              </el-input>

            </div>

          </div>

          <el-select v-if="ruleIndex<(smartRuleList.length-1)"
                     class="item_width_1"
                     v-model="ruleItem.nextLogicalRel"
                     size="small"
                     placeholder="请选择">
            <el-option v-for="item in logicalList"
                       @click.native="handleSelLogical(ruleIndex,item)"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>

          <img v-if=" ruleIndex<smartRuleList.length-1"
               class="img_del"
               src="@/assets/img/icon-del.png"
               @click="delRule(ruleIndex)">

          <div v-if=" ruleIndex==smartRuleList.length-1"
               class="d-icon">
            <img class="img_del"
                 src="@/assets/img/icon-add.png"
                 @click="addRule(ruleIndex)">
            <div class="d-save">保存为常用查询条件</div>
          </div>

        </div>

      </div>

    </div>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'


let loading // 加载动画
export default {
  data () {
    return {

      personChecked: false,
      houseChecked: false,

      smartList: [
        {
          value: 'house',
          label: '房屋信息'
        },
        {
          value: 'person',
          label: '居民信息'
        }
      ],
      groupList: [],
      queryList: [],
      logicalList: [
        {
          label: '并且',
          value: 'and'
        },
        {
          label: '或者',
          value: 'or'
        }
      ],
      houseItemList: [],//房屋信息第二列

      okflag: false,

      showPersonList: false,
      ruleList: {},

      smartRuleList: [
        {
          selSmartType: 'house',
          nextLogicalRel: '',//与上一条的关系；and、or	
          nextLogicalRelName: '',
          houseRule: {
            ruleDesc: '',
            queryType: '',
            colTable: '',
            colKey: '',
            colVal: '',

            titleName: '房屋信息',
            colType: '',//详细参数的组件类型
            colOption: [],
            itemGroupName: '房屋信息',
            itemLabel: '',
            queryTypeName: '',
            colValLabel: '',

          },
          personRule: {
            ruleDesc: '',//规则描述文字，例如：基础信息性别等于女	
            itemGroupId: '',
            itemId: '',
            queryType: '',
            colTable: '',
            colKey: '',
            colVal: '',

            itemList: [],
            colType: '',//详细参数的组件类型
            colOption: [],
            itemGroupName: '',
            itemLabel: '',
            queryTypeName: '',
            colValLabel: '',

          }
        },

      ],

    }
  },

  watch: {

  },
  components: {
    // personListItem
  },
  async created () {
    // this.startLoading()
    await this.loadPersonGroup()
    await this.loadHouseItem()
    await this.loadDicOption()

  },


  methods: {
    handleSelSmartType (ruleIndex, item) {
      let oneData = this.smartRuleList[ruleIndex]

      oneData.houseRule = {
        ruleDesc: '',
        queryType: '',
        colTable: '',
        colKey: '',
        colVal: '',

        titleName: '房屋信息',
        colType: '',//详细参数的组件类型
        colOption: [],
        itemGroupName: '房屋信息',
        itemLabel: '',
        queryTypeName: '',
        colValLabel: '',

      }
      oneData.personRule = {
        ruleDesc: '',//规则描述文字，例如：基础信息性别等于女	
        itemGroupId: '',
        itemId: '',
        queryType: '',
        colTable: '',
        colKey: '',
        colVal: '',

        itemList: [],
        colType: '',//详细参数的组件类型
        colOption: [],
        itemGroupName: '',
        itemLabel: '',
        queryTypeName: '',
        colValLabel: '',

      }

      this.$set(this.smartRuleList, ruleIndex, oneData)
      console.log(this.smartRuleList)
    },
    async setRule (ruleList) {

      if (this.groupList.length == 0 || this.houseItemList.length === 0) {
        setTimeout(() => {
          this.setRule(ruleList);
        }, 500);
        return false
      }

      this.startLoading()

      this.smartRuleList = ruleList
      if (this.smartRuleList && this.smartRuleList.length > 0) {

        for (let i = 0; i < this.smartRuleList.length; i++) {

          let element = this.smartRuleList[i]
          if (element.selSmartType === 'house') {

            let selHouseItem = this.houseItemList.filter((item) =>
              element.houseRule.colKey === item.colKey
            );

            if (selHouseItem.length > 0) {
              await this.handleSelHouseItem(i, selHouseItem[0], true)
            }
          }

          if (element.selSmartType === 'person') {

            let selGroup = this.groupList.filter((item) =>
              element.personRule.itemGroupId === item.id
            );
            console.log(selGroup)

            if (selGroup.length > 0) {
              await this.handleSelGroup(i, selGroup[0], true)

              let selItem = element.personRule.itemList.filter((item) =>
                element.personRule.itemId === item.itemId);
              if (selItem.length > 0) {
                await this.handleSelGroupItem(i, selItem[0], true)
              }

            }
          }

        }
      }
      this.endLoading()


    },

    getRule () {
      this.okflag = false
      let messageObj = this.validateRule()

      if (messageObj) {
        this.$message.error(messageObj)

      } else {

        if (this.smartRuleList.length > 0) {
          this.smartRuleList[this.smartRuleList.length - 1].nextLogicalRel = ''
        }
        console.log('smartRuleList', this.smartRuleList)

        this.okflag = true
      }

    },

    validateRule () {

      let message = ''

      this.smartRuleList.forEach((item, index) => {
        if (item.selSmartType === 'person') {

          if (item.personRule.itemGroupId === '' ||
            item.personRule.itemId === '' ||
            item.personRule.queryType === '' ||
            item.personRule.colKey === ''
          ) {
            message = '第' + (index + 1) + '行人员信息不完整，请填写完整！'
            return message
          }

          if ((item.personRule.queryType !== 'is_null' && item.personRule.queryType !== 'is_not_null') && item.personRule.colVal === '') {
            message = '第' + (index + 1) + '行人员信息不完整，请填写完整！'
            return message
          }
        }

        if (item.selSmartType === 'house') {


          if (item.houseRule.itemGroupId === '' ||
            item.houseRule.itemId === '' ||
            item.houseRule.queryType === '' ||
            item.houseRule.colKey === ''
          ) {
            message = '第' + (index + 1) + '行房屋信息不完整，请填写完整！'
            return message
          }


          if ((item.houseRule.queryType !== 'is_null' && item.houseRule.queryType !== 'is_not_null') && item.houseRule.colVal === '') {
            message = '第' + (index + 1) + '行房屋信息不完整，请填写完整！'
            return message
          }

        }

        if ((index != this.smartRuleList.length - 1) && item.nextLogicalRel === '') {
          message = '第' + (index + 1) + '行逻辑选项不能为空！'
          return message
        }
      });

      return message
    },

    handleClose () {
      this.showPersonList = false
    },

    addRule () {

      let obj = {
        selSmartType: 'house',
        nextLogicalRel: '',//与上一条的关系；and、or	
        nextLogicalRelName: '',
        houseRule: {
          ruleDesc: '',
          queryType: '',
          colTable: '',
          colKey: '',
          colVal: '',

          titleName: '房屋信息',
          colType: '',//详细参数的组件类型
          colOption: [],
          itemGroupName: '房屋信息',
          itemLabel: '',
          queryTypeName: '',
          colValLabel: '',

        },
        personRule: {
          ruleDesc: '',//规则描述文字，例如：基础信息性别等于女	
          itemGroupId: '',
          itemId: '',
          queryType: '',
          colTable: '',
          colKey: '',
          colVal: '',

          itemList: [],
          colType: '',//详细参数的组件类型
          colOption: [],
          itemGroupName: '',
          itemLabel: '',
          queryTypeName: '',
          colValLabel: '',
        }
      }

      this.smartRuleList.push(obj)
    },

    delRule (index) {
      this.smartRuleList.splice(index, 1);
    },



    //选择人员信息第一列下拉框
    async handleSelGroup (ruleIndex, item, isSet) {
      const url = '/oper/customize/icformitem/getItemListV2'
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/isServiceProject/service/serviceScopeTree'
      let params = {
        policyFlag: '1',
        groupId: item.id,

      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {

        let oneData = this.smartRuleList[ruleIndex]
        oneData.personRule.itemGroupName = item.label
        oneData.personRule.itemList = data
        oneData.personRule.colTable = item.tableName

        if (!isSet) {//如果是详情，赋值，不需要置空

          oneData.personRule.itemId = ''
          oneData.personRule.queryType = ''
          oneData.personRule.colKey = ''
          oneData.personRule.colVal = ''
        }

        this.$set(this.smartRuleList, ruleIndex, oneData)

      } else {
        this.$message.error(msg)
      }
    },

    //选择人员信息第二列下拉框
    async handleSelGroupItem (ruleIndex, item, isSet) {

      let oneData = this.smartRuleList[ruleIndex]

      oneData.personRule.colKey = item.columnName
      oneData.personRule.colType = item.itemType
      oneData.personRule.itemLabel = item.label

      if (!isSet) {//如果是详情，赋值，不需要置空

        oneData.personRule.queryType = ''
        oneData.personRule.colVal = ''
      }

      if (item.optionSourceType === 'remote') {
        const url = item.optionSourceValue

        let params = {}

        const { data, code, msg } = await requestPost(url, params)

        if (code === 0) {
          oneData.personRule.colOption = data
        } else {
          this.$message.error(msg)
        }
      } else {
        oneData.personRule.colOption = item.options
      }


      this.$set(this.smartRuleList, ruleIndex, oneData)

    },

    //选择人员信息第三列
    handleSelPersonQuery (ruleIndex, item) {
      let oneData = this.smartRuleList[ruleIndex]
      oneData.personRule.queryTypeName = item.label


      oneData.personRule.colVal = ''
      oneData.personRule.colValLabel = ''

      this.$set(this.smartRuleList, ruleIndex, oneData)
    },
    //选择人员信息第四列
    handleSelPersonValue (ruleIndex, item) {
      let oneData = this.smartRuleList[ruleIndex]

      oneData.personRule.colValLabel = item.label


      this.$set(this.smartRuleList, ruleIndex, oneData)
    },


    //选择房屋信息第二列下拉框
    async handleSelHouseItem (ruleIndex, item, isSet) {

      let oneData = this.smartRuleList[ruleIndex]

      oneData.houseRule.colTable = item.tableName
      oneData.houseRule.colType = item.itemType
      oneData.houseRule.itemLabel = item.label

      if (!isSet) {//如果是详情，赋值，不需要置空

        oneData.houseRule.queryType = ''
        oneData.houseRule.colVal = ''
      }

      if (item.optionSourceType === 'remote') {
        const url = item.optionSourceUrl
        let params = {}
        if (item.optionSourceParam) {
          params = JSON.parse(item.optionSourceParam)
        } else {
          params = {}
        }

        const { data, code, msg } = await requestPost(url, params)

        if (code === 0) {
          oneData.houseRule.colOption = data
        } else {
          this.$message.error(msg)
        }
      } else {
        oneData.houseRule.colOption = []
      }

      this.$set(this.smartRuleList, ruleIndex, oneData)

    },

    //选择房屋第三列
    handleSelHouseQuery (ruleIndex, item) {
      let oneData = this.smartRuleList[ruleIndex]
      oneData.houseRule.queryTypeName = item.label


      oneData.houseRule.colVal = ''
      oneData.houseRule.colValLabel = ''

      this.$set(this.smartRuleList, ruleIndex, oneData)
    },
    //选择房屋第四列
    handleSelHouseValue (ruleIndex, item) {
      let oneData = this.smartRuleList[ruleIndex]
      oneData.houseRule.colValLabel = item.label


      this.$set(this.smartRuleList, ruleIndex, oneData)
    },

    //选择第五列:逻辑
    handleSelLogical (ruleIndex, item) {
      let oneData = this.smartRuleList[ruleIndex]
      oneData.nextLogicalRelName = item.label

      this.$set(this.smartRuleList, ruleIndex, oneData)
    },


    // 获取人员信息---第一列
    async loadPersonGroup () {
      const url = '/oper/customize/icformitemgroup/list'
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/isServiceProject/service/serviceScopeTree'
      let params = {
        formCode: 'resi_base_info',
        policyFlag: '1'
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.groupList = data
      } else {
        this.$message.error(msg)
      }


    },
    // 获取房屋信息--第二列
    async loadHouseItem () {
      const url = '/heart/policy/item-list/' + 'house'

      let params = {}

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.houseItemList = data
      } else {
        this.$message.error(msg)
      }


    },

    async loadDicOption () {
      const url = '/sys/dict/data/dictlist'
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/isServiceProject/service/serviceScopeTree'
      let params = {
        dictType: "sql_query_type"
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.queryList = data
      } else {
        this.$message.error(msg)
      }

    },


    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
  },
  props: {

    formType: {
      type: String,
      required: 'true'
    },


  }
}
</script>


<style lang="scss" scoped >
.m-main {
  // display: flex;
  margin-top: 15px;
}

.tab-title {
  margin-right: 20px;
  cursor: pointer;
}

.tab-title-sel {
  color: #3e8ef7;
  text-decoration: underline;
}

.row-item {
  display: flex;
  margin-bottom: 10px;
}
.row-item-one {
  display: flex;
}
.item_width_1 {
  width: 200px;
  margin-right: 10px;
}
.item_width_2 {
  width: 200px;
  margin-right: 10px;
}

/deep/ .el-checkbox {
  margin-right: 10px;
}
/deep/.el-checkbox:last-of-type {
  margin-right: 10px;
}
.d-icon {
  display: flex;
}

.img_del {
  width: 25px;
  height: 25px;
  margin-top: 3px;
  cursor: pointer;
}
.d-save {
  position: relative;
  margin-top: 3px;
  margin-left: 10px;
  width: 138px;
  height: 25px;
  background: #dde8f3;
  text-align: center;
  border-radius: 3px;
  font-size: 12px;
  font-family: Source Han Serif CN;
  font-weight: 600;
  color: #0043c8;
  line-height: 26px;
  cursor: pointer;

  &::before {
    position: absolute;
    left: 0;
    top: 9px;
    width: 8px;
    height: 8px;
    background: #006ecd;
    border-radius: 50%;
  }
}
</style>
