<template>
  <div class="routerWapper">
		<div>
      <a-row>
        <a-button @click="backPage"> 返回 </a-button>
        <a-button v-if="triggerType !== 'create' && triggerType !== 'loadParentLabel'" :offset='1' type='danger' @click="deleteLabel(labelId)">删除</a-button>
        <a-button type='primary' @click="preview()">预览</a-button>
        <a-button type='primary' @click="save()">保存</a-button>
      </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-radio-group 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 value="tbl_prop_company">
            物业
          </a-radio>
          <a-radio value="tbl_industry_council">
            业委会
          </a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
    <div style="background-color: #F0F2F5; height: 5px; "></div>
      <a-form :form='infoSettingForm' layout='inline'>
        <div v-for="(item66, index66) in loopContent.data" :key="item66.randomNum" style="padding: 20px;border-left: 5px solid #F0F2F5; border-right: 5px solid #F0F2F5; border-bottom: 5px solid #F0F2F5;">
          <a-row type='flex' style="font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid lightgrey" align='middle'>
            <!-- {{item66}} -->
            <a-col :span='21'>
              <a-row>
                <a-form-item>
                  <a-input style="width: 80px" placeholder='分组名' v-decorator="['groupName-' + index66,{initialValue: item66.serial, validateTrigger:'blur',rules: []}]"></a-input>
                </a-form-item>
                
                <a-form-item v-if="index66 !== 0" style="margin-bottom: 20px">
                  <a-select style="width: 80px" placeholder='与上组关系' v-decorator="['relationWithGroup-' + index66 + '-0',{initialValue: item66.relation, validateTrigger:'blur',rules: [{required: true, message: '请至少选择一项！'}]}]">
                    <a-select-option value='and'>且</a-select-option>
                    <a-select-option value='or'>或</a-select-option>
                  </a-select>
                </a-form-item>

                <a-form-item v-show="false">
                  <a-input style="width: 80px" placeholder='randomId' v-decorator="['randomNum-' + index66,{initialValue: item66.randomNum, validateTrigger:'blur',rules: []}]"></a-input>
                </a-form-item>
              </a-row>
            </a-col>
            <a-col :span='3' v-if="index66 !== 0">
              <a-button style="color: darkred" type="link" @click="delGroup(index66, item66.randomNum)"><a-icon type="delete" />删除分组 </a-button>
            </a-col>
          </a-row>
          <div style="width: 90%; padding: 20px; margin-bottom: 20px">
            <div v-for="(item, index) in item66.labelSelConditionList" :key='index' style="margin-bottom: 20px">

              <a-form-item v-if="index !== 0">
                <a-select style="width: 80px" placeholder='请选择条件' v-decorator="['relation-' + index66 +'-' + index,{initialValue: item.relation, validateTrigger:'blur',rules: [{required: true, message: '请至少选择一项！'}]}]">
                  <a-select-option value='and'>且</a-select-option>
                  <a-select-option value='or'>或</a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item v-else style="width: 80px">
              </a-form-item>
              
              <a-form-item>
                <a-select style="width: 80px" placeholder='请选择标记对象' v-decorator="['tableName-' + index66 +'-' + index,{initialValue: item.tableName, validateTrigger:'blur',rules: [{required: true, message: '请至少选择一项！'}]}]">
                  <a-select-option v-for="(item, index) in objSelectOptions" :key='index' :value='item.value'>{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>

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

              <a-form-item>
                <a-select style="width: 150px" placeholder='区间' v-decorator="['codition-' + index66 +'-' + index,{initialValue: item.codition, validateTrigger:'blur',rules: [{required: true, message: '请至少选择一项！'}]}]">
                  <a-select-option value='eq'>等于</a-select-option>
                  <a-select-option value='regex'>包含</a-select-option>
                  <a-select-option value='ne'>不等于</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>

              <a-form-item v-if="checkIfSelectOptionAppears(availableKeyList, infoSettingForm.getFieldValue('tableName-' + index66 +'-' + index), infoSettingForm.getFieldValue('key-' + index66 +'-' + index)).dataType == 'select' && checkIfSelectOptionAppears(availableKeyList, infoSettingForm.getFieldValue('tableName-' + index66 +'-' + index), infoSettingForm.getFieldValue('key-' + index66 +'-' + index)).isfromUrl == false">
                <a-select style="width: 100px" placeholder='请选择' v-decorator="['inputOne-' + index66 +'-' + index,{initialValue: item.val, validateTrigger:'blur',rules: [{required: true, message: '请至少选择一项！'}]}]">
                  <a-select-option v-for="(item1, index) in JSON.parse(availableKeyList.find(item=>item.tblKey == infoSettingForm.getFieldValue('key-' + index66 +'-' + index)).selVals)" :key='item1' :value="item1">{{index}}</a-select-option>
                </a-select>
              </a-form-item>
              
              <a-form-item v-else-if="checkIfSelectOptionAppears(availableKeyList, infoSettingForm.getFieldValue('tableName-' + index66 +'-' + index), infoSettingForm.getFieldValue('key-' + index66 +'-' + index)).dataType == 'select' && checkIfSelectOptionAppears(availableKeyList, infoSettingForm.getFieldValue('tableName-' + index66 +'-' + index), infoSettingForm.getFieldValue('key-' + index66 +'-' + index)).isfromUrl == true">
                <a-select style="width: 100px" placeholder='请选择' v-decorator="['inputOne-' + index66 +'-' + index,{initialValue: item.val, validateTrigger:'blur',rules: [{required: true, message: '请至少选择一项！'}]}]">
                  <a-select-option v-for="(item1, index) in sectOptions" :key='index' :value="item1.streetId">{{item1.name}}</a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item v-else-if="checkIfSelectOptionAppears(availableKeyList, infoSettingForm.getFieldValue('tableName-' + index66 +'-' + index), infoSettingForm.getFieldValue('key-' + index66 +'-' + index)).dataType == 'str'">
                <a-input style="width: 100px" placeholder='请输入' v-decorator="['inputOne-' + index66 +'-' + index,{initialValue: getInitialValueOne(item.val), validateTrigger:'blur',rules: [],}]"></a-input>
              </a-form-item>

              <a-form-item v-else-if="checkIfSelectOptionAppears(availableKeyList, infoSettingForm.getFieldValue('tableName-' + index66 +'-' + index), infoSettingForm.getFieldValue('key-' + index66 +'-' + index)).dataType == 'num'">
                <a-input-number style="width: 100px" placeholder='请输入' v-decorator="['inputOne-' + index66 +'-' + index,{initialValue: getInitialValueOne(item.val), validateTrigger:'blur',rules: [],}]"></a-input-number>
              </a-form-item>

              <a-form-item v-else-if="checkIfSelectOptionAppears(availableKeyList, infoSettingForm.getFieldValue('tableName-' + index66 +'-' + index), infoSettingForm.getFieldValue('key-' + index66 +'-' + index)).dataType == 'date'">
                <a-date-picker style="width: 100px" placeholder='请选择' v-decorator="['inputOne-' + index66 +'-' + index,{initialValue: getInitialValueOne(item.val), validateTrigger:'blur',rules: [],}]"></a-date-picker>
              </a-form-item>

              <a-form-item v-if="infoSettingForm.getFieldValue('codition-'+index66 +'-' + index) == 'btw'">
                <a-input style="width: 100px" placeholder='请输入' v-decorator="['inputTwo-' + index66 +'-' + index,{initialValue: getInitialValueTwo(item.val), validateTrigger:'blur',rules: []}]"></a-input>
              </a-form-item>

              <a-form-item>
                <a-icon v-if="index+1 == loopContent.data[index66].labelSelConditionList.length" theme='filled' style="color:lightgreen;" type="plus-circle" @click="addRow(index66)" />
                <a-icon 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-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>

    <a-modal title='以下是预览结果，确定保存吗？' width='55%' v-model='resultModalVisible'>
      <template slot="footer">
        <a-button key="cancel" @click="handleResultCancel">
          返回
        </a-button>
        <a-button key="ok" type="primary" @click='handleResultOk'>
          确认并保存
        </a-button>
      </template>
      <a-table class="portalTable" size="small" row-key="id" :columns="columns[0][labelForm.getFieldValue('tableName')]" :dataSource="resultList"></a-table>
    </a-modal>
    <a-modal v-model='deleteVisible' @ok='handleDeleteOk' @cancel='handleCancelOk'>
      确定删除标签【{{labelNameForDel}}】吗?
    </a-modal>
    <a-modal width='400px' :bordered='true' title='提示' v-model='confirmVisible' @ok='handleConfirmVisible' @cancel='handleConfirmCancel'>
      确定保存吗？
    </a-modal>
  </div>
</template>

<script>
import Vue from 'vue'
export default {
  data() {
    return {
      num: 0,
      numRow: 0,
      labelForm: this.$form.createForm(this),
      infoSettingForm: this.$form.createForm(this),
      resultModalVisible: false,
      loopContent: {},
      objSelectOptions: [
        {
          name: '小区',
          value: 'tbl_community'
        },
        {
          name: '门牌',
          value: 'tbl_building'
        },
        {
          name: '物业',
          value: 'tbl_prop_company'
        },
        {
          name: '业委会',
          value: 'tbl_industry_council'
        }
      ],
      sectOptions: [],
      verifySelect: false,
      verifyInput: false,
      jsonData: {},
      deleteVisible: false,
      confirmVisible: false,
      finish: false,
      parentLabelList: [],
      availableKeyList: [],
      initKey: '',
      resultList: [],
      labelNameForDel: '',
      columns: [
        {
          tbl_community: [
            {
              title: '小区名称',
              dataIndex: 'stNameFrst',
              key: 'stNameFrst',
              align: 'center',
            },
            {
              title: '小区地址',
              dataIndex: 'addrFrst',
              key: 'addrFrst',
              align: 'center',
            },
            {
              title: '房管办',
              dataIndex: 'hoName',
              key: 'hoName',
              align: 'center',
            },
            {
              title: '小区性质',
              dataIndex: 'stKindName',
              key: 'stKindName',
              align: 'center',
            },
            {
              title: '小区类型',
              dataIndex: 'sectTypeName',
              key: 'sectTypeName',
              align: 'center',
            },
          ],
          tbl_building: [
            {
              title: '门牌地址',
              dataIndex: 'unitAddr',
              key: 'unitAddr',
              align: 'center',
            },
            {
              title: '门牌类型',
              dataIndex: 'unitKindName',
              key: 'unitKindName',
              align: 'center',
            },
            {
              title: '门牌所在路',
              dataIndex: 'uLoad',
              key: 'uLoad',
              align: 'center',
            },
            {
              title: '门牌所在弄',
              dataIndex: 'uLong',
              key: 'uLong',
              align: 'center',
            },
          ],
          tbl_prop_company: [
            {
              title: '物业名称',
              dataIndex: 'cspName',
              key: 'cspName',
              align: 'center',
            },
            {
              title: '物业联系人',
              dataIndex: 'cspContacter',
              key: 'cspContacter',
              align: 'center',
            },
            {
              title: '物业地址',
              dataIndex: 'cspAddr',
              key: 'cspAddr',
              align: 'center',
            },
            {
              title: '注册地址',
              dataIndex: 'registerAddress',
              key: 'registerAddress',
              align: 'center',
            },
          ],
          tbl_industry_council: [
            {
              title: '业委会名称',
              dataIndex: 'hocName',
              key: 'hocName',
              align: 'center',
            },
            {
              title: '业委会地址',
              dataIndex: 'hocAddr',
              key: 'hocAddr',
              align: 'center',
            },
            {
              title: '竞选时间',
              dataIndex: 'electionDate',
              key: 'electionDate',
              align: 'center',
            },
            {
              title: '开始时间',
              dataIndex: 'conStartDate',
              key: 'conStartDate',
              align: 'center',
            },
            {
              title: '结束时间',
              dataIndex: 'conEndDate',
              key: 'conEndDate',
              align: 'center',
            },
          ]
        }
      ]
    }
  },
  mounted() {
    console.log('得到的' + this.labelId)
    this.getLabelDetail()
    this.getParentLabelList()
    this.initKeyList()
    this.getSectOptions()
  },
  props: [
    'triggerType',
    'labelId'
  ],
  watch: {
    triggerType: {
      handler: function(newV, oldV) {
        this.resetFormFields()
        this.getLabelDetail()
      },
      immediate: true
    },
    labelId: {
      handler: function(newV, oldV) {
        this.initKeyList()
        this.resetFormFields()
        this.getLabelDetail()
      },
      immediate: true
    },
  },
  methods: {
    getSectOptions() {
      this.sectOptions = []
      this.$ajax.get({
        url: this.$api.BASE_URL + '/service-basicdatasync-ddd/streets',
      }).then(res => {
        if (res.code == '200') {
          let resultList = res.data.content

          // resultList.forEach(element => {
          //   this.sectOptions[element.strName] = element.streetId
          // })

          resultList.forEach(element => {
            this.sectOptions.push({
              name: element.strName,
              streetId: element.streetId
            })
          });
          
        } else {
          alert('接口发生错误！')
        }
      })
    },
    handleResultCancel() {
      this.resultModalVisible = !this.resultModalVisible
    },
    cnonvertObj(options, tableName) {
      let tbRealName = ''
      switch (tableName) {
      case 'tbl_community':
        tbRealName = '小区'
        break

      case 'tbl_building':
        tbRealName = '自然幢'
        break

      case 'tbl_prop_company':
        tbRealName = '物业公司'
        break

      case 'tbl_industry_council':
        tbRealName = '业委会'
        break
      
      default:
        break
      }

      let optionsPush = []
      for (let i = 0; i < options.length; i++) {
        if(options[i].tableName == tbRealName) {
          optionsPush.push(options[i])
        }
      }

      return optionsPush
    },
    /**
     * options => 所有可选择项目
     * formValue => 业务属性
     * key => 业务属性二级可选值
     */
    checkIfSelectOptionAppears(options, formValue, key) {
      console.log(options, formValue, key);
      let findKey = options.find(item => (item.tblKey == key))
      let pushSels = []
      // 如果没找到
      if (!findKey) return false

      // str / date / select/ num
      // return findKey.dataType
      if(findKey.pathUrl == '/service-basicdatasync-ddd/streets') {
        return { dataType: findKey.dataType, isfromUrl: true, selVals: this.sectOptions }
      } else {
        return { dataType: findKey.dataType, isfromUrl: false, selVals: findKey.selVals }
      }
    },
    handleResultOk() {
      this.resultModalVisible = !this.resultModalVisible
      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)
            this.infoSettingForm.validateFields((err1, values) => {
              if(!err1) {
                let loopGroup = this.loopContent // 有多少组
                console.log(loopGroup)
                let innerResult = []
                
                let formData = this.infoSettingForm.getFieldsValue()

                loopGroup.data.forEach((item, i) => {
                  let rowList = []
                  item.labelSelConditionList.forEach((ele, index) => {

                    // console.log(formData)
                    rowList.push({
                      key: formData['key-' + i + '-'+index ],
                      tableName: formData['tableName-' + i + '-'+index ],
                      val: !formData['inputTwo-' + i+'-'+index] ? formData['inputOne-' + i+'-'+index] : formData['inputOne-' + i+'-'+index] + ',' + formData['inputTwo-' + i+'-'+index],
                      codition: formData['codition-' + i + '-' +index],
                      relation: !!formData['relation-' + i + '-' + index]? formData['relation-' + i + '-' + index]: 'and',
                      randomNum: formData['randomNumInner-' + i + '-' +index],
                    })
                  })

                  innerResult.push({
                    'randomNum': formData['randomNum-' + i],
                    'serial': formData['groupName-' + i],
                    'relation': !!formData['relationWithGroup-' + i + '-0']? formData['relationWithGroup-' + i + '-0']: 'and',
                    'labelSelConditionList': rowList
                  })
                })

                this.jsonData.selParams = innerResult

                this.$ajax.post({
                  url: this.$api.POST_LABEL_CREATE_CONFIRM,
                  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.$message.error('保存失败！')
                  }
                })
              }
            })
          }
        })
      }
    },
    addGroup() {
      // 添加分组前，先查询当前有几个分组
      const groupTotal = Object.keys(this.loopContent.data).length
      console.log(groupTotal)
      console.log(this.loopContent)

      Vue.set(this.loopContent, 'data', [
        ...this.loopContent.data, {randomNum: Math.random().toString(), serial: '新分组', relation: 'and', labelSelConditionList: [ { key: '', val: '', tableName: '', codition: 'eq', relation: '', randomNum: Math.random() } ] }
      ])

      this.$forceUpdate()

      console.log(JSON.stringify(this.loopContent))
    },
    delGroup(index1, key) {
      let loopGroup = this.loopContent // 有多少组
      let innerResult = []
                
      let formData = this.infoSettingForm.getFieldsValue()

      loopGroup.data.forEach((item, i) => {
        let rowList = []
        item.labelSelConditionList.forEach((ele, index) => {

          // console.log(formData)
          rowList.push({
            key: formData['key-' + i + '-'+index ],
            tableName: formData['tableName-' + i + '-'+index ],
            val: !formData['inputTwo-' + i+'-'+index] ? formData['inputOne-' + i+'-'+index] : formData['inputOne-' + i+'-'+index] + ',' + formData['inputTwo-' + i+'-'+index],
            codition: formData['codition-' + i + '-' +index],
            relation: !!formData['relation-' + i + '-' + index]? formData['relation-' + i + '-' + index]: 'and',
            randomNum: formData['randomNumInner-' + i + '-' +index],
          })
        })

        innerResult.push({
          'randomNum': formData['randomNum-' + i],
          'serial': formData['groupName-' + i],
          'relation': !!formData['relationWithGroup-' + i + '-0']? formData['relationWithGroup-' + i + '-0']: 'and',
          'labelSelConditionList': rowList
        })
      })

      this.loopContent.data = innerResult

      this.loopContent.data = this.loopContent.data.filter(i => i.randomNum !== key)
      this.$forceUpdate()
    },
    initKeyList() {
      // 获取当前的对象
      this.initKey = this.labelForm.getFieldValue('tableName')
      this.getKeyList(this.initKey)
    },
    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

          }
        })
      } 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) {
      if(val.indexOf(',') > -1) {
        return val.split(',')[0]
      } else {
        return val
      }
    },
    getInitialValueTwo(val) {
      if(val.indexOf(',') > -1) {
        return val.split(',')[1]
      } else {
        return ''
      }
    },
    backPage(){ // 返回按钮
      this.finish = true
      this.$emit('finish', this.finish)
    },
    addRow(whichGroup) {
      this.numRow ++
      this.loopContent.data[whichGroup].labelSelConditionList.push({
        numRow: this.numRow,
        key: '',
        tableName: '',
        codition: 'eq',
        val: '',
        relation: 'and',
      })
      this.$forceUpdate()
    },
    deleteRow(whichGroup, whichRow) {
      if(this.loopContent.data[whichGroup].labelSelConditionList.length == 1) {
        this.$message.error('请至少保留一个筛选条件，或删除分组！')
      } else {
        this.loopContent.data[whichGroup].labelSelConditionList.splice(whichRow, 1)
        // this.loopContent.data[whichGroup].labelSelConditionList = this.loopContent.data[whichGroup].labelSelConditionList.filter(i => i.num !== whichRow)
        this.$forceUpdate()
      }
    },
    deleteLabel(id) {
      console.log(id, this.deleteVisible)
      // 查询该标签是否是一级标签，是一级标签直接删除。
      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 = [ { randomNum: Math.random(), serial: '新分组', relation: 'and', labelSelConditionList: [ {key: '', val: '', tableName: '', codition: 'eq', relation: '', randomNum: Math.random()} ] } ]
      this.resultList = []
      this.labelForm.resetFields()
      this.infoSettingForm.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
    },
    preview() {
      this.infoSettingForm.validateFields((err1, values) => {
        if(!err1) {
          let loopGroup = this.loopContent // 有多少组
          console.log(loopGroup)
          let innerResult = []
                
          let formData = this.infoSettingForm.getFieldsValue()

          loopGroup.data.forEach((item, i) => {
            let rowList = []
            item.labelSelConditionList.forEach((ele, index) => {

              // console.log(formData)
              rowList.push({
                key: formData['key-' + i + '-'+index ],
                tableName: formData['tableName-' + i + '-'+index ],
                val: !formData['inputTwo-' + i+'-'+index] ? formData['inputOne-' + i+'-'+index] : formData['inputOne-' + i+'-'+index] + ',' + formData['inputTwo-' + i+'-'+index],
                codition: formData['codition-' + i + '-' +index],
                relation: !!formData['relation-' + i + '-' + index]? formData['relation-' + i + '-' + index]: 'and',
                randomNum: formData['randomNumInner-' + i + '-' +index],
              })
            })
            innerResult.push({
              'randomNum': Math.random(),
              'serial': formData['groupName-' + i],
              'relation': !!formData['relationWithGroup-' + i + '-0']? formData['relationWithGroup-' + i + '-0']: 'and',
              'labelSelConditionList': rowList
            })
          })
          // 调用预览接口
          const tableName = this.labelForm.getFieldValue('tableName')
          this.sendToPreview(innerResult, tableName)
        }
      })
    },
    sendToPreview(body, tableName) {
      this.$ajax.post({
        url: this.$api.POST_LABEL_RESULT_PREVIEW+'?pageNo=0&pageSize=999&tableName=' + tableName,
        params: body
      }).then(res => {
        if (res.code == 200) {

          this.resultModalVisible = !this.resultModalVisible

          this.resultList = this.$com.confirm(res, 'data.content', [])
        } else {
          this.$message.success('发生错误!')
        }
      })
    },
    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)
            this.infoSettingForm.validateFields((err1, values) => {
              if(!err1) {
                let loopGroup = this.loopContent // 有多少组
                console.log(loopGroup)
                let innerResult = []
                
                let formData = this.infoSettingForm.getFieldsValue()

                loopGroup.data.forEach((item, i) => {
                  let rowList = []
                  item.labelSelConditionList.forEach((ele, index) => {

                    // console.log(formData)
                    rowList.push({
                      key: formData['key-' + i + '-'+index ],
                      tableName: formData['tableName-' + i + '-'+index ],
                      val: !formData['inputTwo-' + i+'-'+index] ? formData['inputOne-' + i+'-'+index] : formData['inputOne-' + i+'-'+index] + ',' + formData['inputTwo-' + i+'-'+index],
                      codition: formData['codition-' + i + '-' +index],
                      relation: !!formData['relation-' + i + '-' + index]? formData['relation-' + i + '-' + index]: 'and',
                      randomNum: formData['randomNumInner-' + i + '-' +index],
                    })
                  })

                  innerResult.push({
                    'randomNum': formData['randomNum-' + i],
                    'serial': formData['groupName-' + i],
                    'relation': !!formData['relationWithGroup-' + i + '-0']? formData['relationWithGroup-' + i + '-0']: 'and',
                    'labelSelConditionList': rowList
                  })
                })

                this.jsonData.selParams = innerResult
                this.confirmVisible = !this.confirmVisible
              }
            })
          }
        })
      }
    },
  },
}
</script>