<template>
  <div class="routerWapper">
		<div>
      <a-row>
        <!-- <a-col :span='1' v-if="triggerType == 'create'"> -->
        <a-col :span='1'>
          <div class="detailOperations">
            <a-button @click="backPage"> 返回 </a-button>
          </div>
        </a-col>
        <a-col :span='1' v-if="triggerType !== 'create' && triggerType !== 'loadParentLabel'" :offset='1'>
          <a-button type='danger' @click="deleteLabel(labelId)">删除</a-button>
        </a-col>
        <!-- <a-col :span='1' :offset='1'>
          <a-button type='default'>编辑</a-button>
        </a-col> -->
        <a-col :span='1' :offset='1'>
          <a-button type='primary' @click="save()">保存</a-button>
        </a-col>
        <a-col :span='19'></a-col>
      </a-row>
    </div>
    <a-divider type='horizontal' />
    <div style="height: 580px; overflow-y: scroll">
    <a-form :form='labelForm'>
      <a-form-item label='标签名' :label-col="{span:3}" :wrapper-col="{span:15}">
        <a-input placeholder='请输入标签名' v-decorator="['labelName',{validateTrigger:'blur', initialValue: jsonData.labelName?jsonData.labelName: '', rules: [{required: true, message: '请填写标签名！'}]}]"></a-input>
      </a-form-item>
      <a-row>
        <a-col :span='12'>
          <a-form-item label='标签分组' :label-col="{span:6}" :wrapper-col="{span:16}">
            <a-select v-decorator="['parentId',{validateTrigger:'blur', initialValue: jsonData.parentId?jsonData.parentId: '', rules: [{required: verifySelect, message: '请选择标签分组！'}]}] " placeholder='请选择分组'>
              <a-select-option value=''>其他</a-select-option>
              <a-select-option v-for="(item, index) in parentLabelList" :key='index' :value='item.id'>
                {{item.labelName}}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='12'>
          <a-form-item :label-col="{span:1}" :wrapper-col="{span:12}" v-if="labelForm.getFieldValue('parentId') == ''">
            <a-input placeholder='请输入分组名称' v-decorator="['parentName',{validateTrigger:'blur', initialValue: jsonData.parentName?jsonData.parentName: '', rules: [{required: verifyInput, message: '请填写标签分组名！'}]}]"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <!-- <a-form-item label='标记对象' :label-col="{span:3}" :wrapper-col="{span:15}">
        <a-select placeholder='请选择业务对象' @change='handleObjChange' v-decorator="['tableName',{validateTrigger:'blur', initialValue: jsonData.tableName?jsonData.tableName: '', rules: [{required: true, message: '请选择业务对象！'}]}]">
          <a-select-option value='tbl_community'>小区</a-select-option>
          <a-select-option value='tbl_building'>门牌幢</a-select-option>
        </a-select>
      </a-form-item> -->
      <a-form-item label='标记对象' :label-col="{span:3}" :wrapper-col="{span:15}">
        <a-radio-group @change='handleObjChange' v-decorator="['tableName',{validateTrigger:'blur', initialValue: jsonData.tableName?jsonData.tableName: '', rules: [{required: true, message: '请选择业务对象！'}]}]">
          <a-radio value="tbl_community">
            小区
          </a-radio>
          <a-radio value="tbl_building">
            门牌幢
          </a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
    <!-- <div style="background-color: #F0F2F5; height: 10px; "></div> -->
    <!-- {{loopContent}} -->
      <a-form :form='infoSettingForm' layout='inline'>
        <!-- {{loopContent.data}} -->
        <div v-for="(item66, index66) in loopContent" :key="index66" style="margin-top: 20px; padding: 20px; border: 1px solid lightgrey">
          <a-row type='flex' style="font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid lightgrey" align='middle'>
            <a-col :span='21'>
              <span style="font-weight: bold">条件分组{{index66.length == '4'? `1`: index66.split('data')[1]}}</span>
            </a-col>
            <a-col :span='3'>
              <a-button style="color: darkred" type="link" @click="delGroup(index66)"><a-icon type="delete" /> {{index66}}删除分组 </a-button>
            </a-col>
          </a-row>
          {{item66}}
          <div v-if="JSON.stringify(loopContent[index66]) !== '[]'" style="width: 90%; padding: 20px; margin-bottom: 20px">
            <!-- <span v-if="index66 !== 'data'">与</span> -->
            <!-- {{item66}} -->
            <div v-for="(item, index) in item66" :key='index' style="margin-bottom: 20px">
              <!-- <a-form-item v-if="!!item.relation">
                <a-select style="width: 120px" placeholder='请选择条件' v-decorator="['relation-' + index66 +'-' + index,{initialValue: item.relation, validateTrigger:'blur',rules: []}]">
                  <a-select-option value='and'>与</a-select-option>
                  <a-select-option value='or'>或</a-select-option>
                  <a-select-option value='ne'>非</a-select-option>
                </a-select>
              </a-form-item> -->
              <!-- {{item}} -->
              {{item}}
              <a-form-item>
                <a-select style="width: 120px" placeholder='请选择条件' v-decorator="['relation-' + index66 +'-' + index,{initialValue: item.relation, validateTrigger:'blur',rules: []}]">
                  <a-select-option value='and'>与</a-select-option>
                  <a-select-option value='or'>或</a-select-option>
                  <a-select-option value='ne'>非</a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item>
                <a-select style="width: 120px" placeholder='请选择业务属性' v-decorator="['key-' + index66 +'-' + index,{initialValue: item.labelSelConditionList[0].key, validateTrigger:'blur',rules: [{required: true, message: '请至少选择一项！'}]}]">
                  <a-select-option v-for="(item1, index1) in availableKeyList" :key='index1' :value='item1.tblKey'>{{item1.tblKeyName}}</a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item>
                <a-select style="width: 120px" placeholder='区间' v-decorator="['codition-' + index66 +'-' + index,{initialValue: item.labelSelConditionList[0].codition, validateTrigger:'blur',rules: [{required: true, message: '请至少选择一项！'}]}]">
                  <a-select-option value='eq'>等于</a-select-option>
                  <a-select-option value='gt'>大于</a-select-option>
                  <a-select-option value='gte'>大于等于</a-select-option>
                  <a-select-option value='lt'>小于</a-select-option>
                  <a-select-option value='lte'>小于等于</a-select-option>
                  <a-select-option value='btw'>区间</a-select-option>
                </a-select>
              </a-form-item>
              <!-- {{item}} -->
              <a-form-item>
                <a-input style="width: 120px" placeholder='请输入' v-decorator="['inputOne-' + index66 +'-' + index,{initialValue: getInitialValueOne(item.labelSelConditionList[0].val), validateTrigger:'blur',rules: [],}]"></a-input>
              </a-form-item>
              <a-form-item v-if="infoSettingForm.getFieldValue('codition-'+index66 +'-' + index) == 'btw'">
                <a-input style="width: 120px" placeholder='请输入' v-decorator="['inputTwo-' + index66 +'-' + index,{initialValue: getInitialValueTwo(item.labelSelConditionList[0].val), validateTrigger:'blur',rules: []}]"></a-input>
              </a-form-item>

              <a-form-item>
                <a-select style="width: 120px" placeholder='查询方式' v-decorator="['selMet-' + index66 +'-' + index,{initialValue: item.labelSelConditionList[0].selMet, validateTrigger:'blur',rules: [{required: true, message: '请至少选择一项！'}]}]">
                  <a-select-option value='equels'>精确</a-select-option>
                  <a-select-option value='like'>模糊</a-select-option>
                </a-select>
              </a-form-item>
              <!-- <a-form-item>
                <a-icon v-if="index+1 == loopContent.data.length" theme='filled' style="color:lightgreen;" type="plus-circle" @click="addRow(index66)" />
                <a-icon v-if="index+1 == loopContent.data.length" theme='filled' style="color:red; margin-left: 5px" type="minus-circle" @click="deleteRow(index66, index)" />
              </a-form-item> -->
              <a-form-item>
                <a-icon v-if="index+1 == loopContent.data.length" theme='filled' style="color:lightgreen;" type="plus-circle" @click="addRow(index66)" />
                <a-icon v-if="index+1 == loopContent.data.length" theme='filled' style="color:red; margin-left: 5px" type="minus-circle" @click="deleteRow(index66, index)" />
              </a-form-item>
            </div>
          </div>
        </div>
      </a-form>

      <a-row style="text-align: center; margin-top: 10px; border: 2px dashed lightblue; padding: 10px 0px">
          <a-button type="link" @click="addGroup"> <a-icon type="plus" />添加分组 </a-button>
      </a-row>

      <!-- <a-button type='link' v-if="loopContent.data.length == 0" @click="addInitRow()"><a-icon type="plus" />新增配置</a-button> -->
      <a-row v-if="Object.keys(this.loopContent).length == 0" style="border: 1px solid pink; padding: 20px">
        <a-icon type="info-circle" />
        <span>请选择业务对象后填写筛选配置</span>
      </a-row>
    </div>
    <!-- <div v-if="resultList.length > 0">
      <a-divider type='horizontal' />
      <a-row style="font-weight: bold">筛选结果</a-row>
      <a-table class="portalTable" size="small" row-key="id" :columns="columns" :dataSource="resultList"></a-table>
    </div> -->
    <a-modal :visible='deleteVisible' @ok='handleDeleteOk' @cancel='handleCancelOk'>
      确定删除标签【{{labelNameForDel}}】吗?
    </a-modal>
    <a-modal width='400px' :bordered='true' title='提示' :visible='confirmVisible' @ok='handleConfirmVisible' @cancel='handleConfirmCancel'>
      确定保存吗？
      <!-- <a-table class="portalTable" size="small" row-key="id" :columns="columns" :dataSource="resultList"></a-table> -->
    </a-modal>
  </div>
</template>

<script>
import Vue from 'vue'
export default {
  data() {
    return {
      labelForm: this.$form.createForm(this),
      infoSettingForm: this.$form.createForm(this),
      loopContent: {
        data: [{
          key: '',
          codition: 'eq',
          val: '',
          selMet: ''
        }],
      },
      verifySelect: false,
      verifyInput: false,
      jsonData: {},
      deleteVisible: false,
      confirmVisible: false,
      finish: false,
      parentLabelList: [],
      availableKeyList: [],
      initKey: '',
      resultList: [],
      labelNameForDel: '',
      columns: [
        {
          title: '小区名称',
          // width: 240,
          dataIndex: 'stNameFrst',
          key: 'stNameFrst',
          align: 'center',
        },
        {
          title: '小区地址',
          // width: 240,
          dataIndex: 'addrFrst',
          key: 'addrFrst',
          align: 'center',
        },
        {
          title: '房管办',
          // width: 240,
          dataIndex: 'hoName',
          key: 'hoName',
          align: 'center',
        },
        {
          title: '小区性质',
          // width: 240,
          dataIndex: 'stKindName',
          key: 'stKindName',
          align: 'center',
        },
        {
          title: '小区类型',
          // width: 240,
          dataIndex: 'sectTypeName',
          key: 'sectTypeName',
          align: 'center',
        },
      ]
    }
  },
  mounted() {
    console.log('得到的' + this.labelId)
    this.getLabelDetail()
    this.getParentLabelList()
    // this.getKeyList()
    // this.initKeyList()
  },
  props: [
    'triggerType',
    'labelId'
  ],
  watch: {
    triggerType: {
      handler: function(newV, oldV) {
        this.resetFormFields()
        this.getLabelDetail()
      },
      immediate: true
    },
    labelId: {
      handler: function(newV, oldV) {
        this.resetFormFields()
        this.getLabelDetail()
      },
      immediate: true
    },
  },
  methods: {
    addGroup() {
      // 添加分组前，先查询当前有几个分组
      const groupTotal = Object.keys(this.loopContent).length
      
      Vue.set(this.loopContent, 'data'+(groupTotal+1), [
        { "serial": "1", "relation": "and", "labelSelConditionList": [ { "key": "", "val": "", "codition": "eq", "selMet": "", "relation": "" } ] }
      ])

      console.log(JSON.stringify(this.loopContent))
    },
    delGroup(key) {
      console.log(key)
      Vue.delete(this.loopContent, key)
    },
    initKeyList() {
      // 获取当前的对象
      this.initKey = this.labelForm.getFieldValue('tableName')
      this.getKeyList(this.initKey)
    },
    handleObjChange(val) {
      let needValue = this.labelForm.getFieldValue('tableName')
      this.getKeyList(needValue)

      this.loopContent = {data: [{
        key: '',
        codition: 'eq',
        val: '',
        selMet: ''
      }]}

      this.infoSettingForm.resetFields()
      // 重置key表项的值为空 或 业务对象干脆disable掉
    },
    getKeyList(val) {
      this.availableKeyList = []
      this.$ajax.get({
        url: this.$api.GET_AVAILABLE_KEY_LIST,
        params: {
          pageNo: 1,
          pageSize: 999
        }
      }).then(res => {
        if (res.code == 200) {
          this.availableKeyList = res.data.content
        }
      })
    },
    getLabelDetail() {
      if(!!this.labelId && this.labelId !== 'undefined') {
        this.$ajax.get({
          url: this.$api.DELETE_SINGLE_LABEL.replace('{id}', this.labelId),
        }).then(res => {
          if (res.code == 200) {
            this.labelForm.setFieldsValue({
              labelName: res.data.content.labelName,
              parentId: res.data.content.parentId,
              tableName: res.data.content.tableName
            })
            this.labelNameForDel = res.data.content.labelName
            this.loopContent.data = res.data.content.selParams

            console.log(this.loopContent.data)
            this.initKeyList()
          }
        })
      } else {
        this.resetFormFields()
      }
    },
    getParentLabelList() {
      this.$ajax.get({
        url: this.$api.GET_LABEL_LIST,
      }).then(res => {
        let list = this.$com.confirm(res, 'data.content', [])
        for(let i = 0; i < list.length; i++) {
          this.parentLabelList.push({
            'labelName': list[i].labelName,
            'id': list[i].id
          })
        }
      })
    },
    getInitialValueOne(val) {
      // return ''
      if(val.indexOf(',') > -1) {
        return val.split(',')[0]
      } else {
        return val
      }
    },
    getInitialValueTwo(val) {
      // return ''
      if(val.indexOf(',') > -1) {
        return val.split(',')[1]
      } else {
        return ''
      }
    },
    backPage(){ // 返回按钮
      this.finish = true
      this.$emit('finish', this.finish)
    },
    // addInitRow() {
    //   this.loopContent.data.push({
    //     key: '',
    //     codition: 'eq',
    //     val: '',
    //     selMet: ''
    //   })
    // },
    addRow(whichGroup) {
      console.log(whichGroup)
      this.loopContent[whichGroup].push({
        key: '',
        codition: 'eq',
        val: '',
        relation: 'and',
        selMet: ''
      })
      console.log(this.loopContent)
    },
    deleteRow(whichGroup, whichRow) {
      console.log(whichGroup, whichRow)
      this.loopContent[whichGroup].splice(whichRow, 1)
      // console.log(JSON.stringify(this.loopContent.data))
      // console.log(index)
      // this.loopContent.data.splice(index, 1)
      // console.log(JSON.stringify(this.loopContent.data))
    },
    deleteLabel(id) {
      console.log(id)
      // 查询该标签是否是一级标签，是一级标签直接删除。
      this.deleteVisible = !this.deleteVisible
    },
    handleDeleteOk() {
      this.$ajax.delete({
        url: this.$api.DELETE_SINGLE_LABEL.replace('{id}', this.labelId),
      }).then(res => {
        if (res.code == 200) {
          this.$message.success('删除标签成功!')
          this.finish = true
          this.$emit('finish', this.finish)
        }
      })
      this.deleteVisible = !this.deleteVisible
    },
    handleCancelOk() {
      this.deleteVisible = !this.deleteVisible
    },
    resetFormFields() {
      this.loopContent = { "data": [ { "serial": "1", "relation": "and", "labelSelConditionList": [ { "key": "", "val": "", "codition": "eq", "selMet": "", "relation": "" } ] } ] }
      this.resultList = []
      this.labelForm.resetFields()
      this.jsonData = {selParams: []}
    },
    handleConfirmVisible() {
      console.log(this.jsonData)
      if(!!this.labelId) {
        this.$ajax.put({
          url: this.$api.PUT_LABEL_INFO.replace('{id}', this.labelId),
          params: Object.assign(this.jsonData, {id: this.labelId})
        }).then(res => {
          if (res.code == 200) {
            this.$message.success('修改成功!')
            this.resetFormFields()
            this.finish = true
            this.$emit('finish', this.finish)
          }
        })
      } else {
        this.$ajax.post({
          url: this.$api.POST_SINGLE_LABEL,
          params: Object.assign(this.jsonData)
        }).then(res => {
          if (res.code == 200) {
            this.$message.success('保存成功!')
            this.resetFormFields()
            this.finish = true
            this.$emit('finish', this.finish)
          } else {
            this.$message.success('保存失败!')
          }
        })
      }
    },
    handleConfirmCancel() {
      this.confirmVisible = !this.confirmVisible
    },
    save() {
      // if(this.loopContent.data.length == 0) {
      if(Object.keys(this.loopContent).length == 0) {
        this.$message.error('请至少添加一组配置！')
      } else {
        // 判断是否选择分组或填写分组
        console.log(!!this.labelForm.getFieldValue('parentId'))
        if(!!this.labelForm.getFieldValue('parentId')) {
          this.verifyInput = false
          this.verifySelect = true
        } else {
          this.verifyInput = true
          this.verifySelect = false
        }

        this.labelForm.validateFields((err, values) => {
          if(!err) {
            const labelFormData = this.labelForm.getFieldsValue()
            
            this.jsonData = Object.assign(this.jsonData, labelFormData)
            console.log(
              this.jsonData
            )
            this.infoSettingForm.validateFields((err1, values) => {
              if(!err1) {
                let loopGroup = this.loopContent // 有多少组

                // console.log(values, 'form表单的数据')
                let innerResult = []
                
                let formData = this.infoSettingForm.getFieldsValue()

                // console.log(loopGroup, 'loopGroup')
                console.log(formData, 'formData')

                for (let k in loopGroup) {
                  let rowList = []
                  loopGroup[k].forEach((item, index) => {
                    rowList.push({
                      key: formData['key-' + k + '-'+index ],
                      val: !formData['inputTwo-' + k+'-'+index] ? formData['inputOne-' + k+'-'+index] : formData['inputOne-' + k+'-'+index] + ',' + formData['inputTwo-' + k+'-'+index],
                      codition: formData['codition-' + k + '-' +index],
                      relation: formData['relation-' + k + '-' + index],
                      selMet: formData['selMet-' + k + '-' + index]
                    })
                  })
                  // console.log(k)
                  // console.log(loopGroup[k])
                  innerResult.push({
                    'serial': 1,
                    'relation': formData['relation-' + k + '-0'],
                    'labelSelConditionList': rowList
                  })
                  
                }

                console.log(innerResult)

                this.jsonData.selParams = innerResult
                console.log(
                  this.jsonData
                )

                // console.log(innerResult)

                // 先循环得到有多少个form

                // this.$ajax.post({
                //   url: this.$api.GET_LABEL_BIND_FILTER_RESULT,
                //   params: this.jsonData
                // }).then(res => {
                //   if (res.code == 200) {
                //     if(res.data == null) {
                //       console.log(1)
                //       this.$message.error('该标签无搜索结果，标签添加失败！')
                //     } else if(!!res.data.content) {
                //       if(res.data.content.length > 0) {
                //         this.resultList = res.data.content
                //         this.confirmVisible = !this.confirmVisible
                //       } else {
                //         console.log(2)
                //         this.$message.error('该标签无搜索结果，标签添加失败！')
                //       }
                //     } else {
                //     }
                //   } else {
                //     this.$message.error('接口报错，报错码 ' + res.code + ', 请稍后重试！')
                //   }
                // })
                // this.resultList = res.data.content
                this.confirmVisible = !this.confirmVisible
              }
            })
          }
        })
      }
    },
  },
}
</script>