<template>
  <div class="routerWapper">
		<div>
      <a-row>
        <!-- <a-col :span='1' v-if="triggerType == 'create'"> -->
          <!-- <a-col :span='16'>
            <a-row>
              <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 v-if="triggerType !== 'create' && triggerType !== 'loadParentLabel'" :offset='1' type='danger' @click="deleteLabel(labelId)">删除</a-button>
              <!-- </a-col>
              <a-col :span='1' :offset='1'> -->
                <a-button type='primary' @click="preview()">预览</a-button>
              <!-- </a-col>
              <a-col :span='1' :offset='1'> -->
                <a-button type='primary' @click="save()">保存</a-button>
              <!-- </a-col>
              <a-col :span='18'></a-col>
            </a-row> -->
          <!-- </a-col> -->
      </a-row>
    </div>
    <a-divider type='horizontal' />
    <div style="height: 580px; overflow-y: scroll">
    <a-form :form='labelForm'>
      <!-- {{loopContent.data}} -->
      <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 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>
    <!-- {{loopContent}} -->
      <a-form :form='infoSettingForm' layout='inline'>

        <div v-for="(item66, index66) in loopContent.data" :key="index66" style="padding: 20px;border-left: 5px solid #F0F2F5; border-right: 5px solid #F0F2F5; border-bottom: 5px solid #F0F2F5;">
          <!-- {{index66}} -->
          <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">{{item66.serial}}</span>
            </a-col>
            <a-col :span='3' v-if="index66 !== 0">
              <a-button style="color: darkred" type="link" @click="delGroup(index66)"><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-row>
                <a-form-item v-if="index == 0 && 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-option value='ne'>非</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item v-if="index == 0">
                  <a-input style="width: 80px" placeholder='分组名' v-decorator="['groupName-' + index66,{initialValue: item66.serial, validateTrigger:'blur',rules: []}]"></a-input>
                </a-form-item>
              </a-row>

              <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-option value='ne'>非</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: 80px" 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>

              <!-- 可以是输入框或者选择框 -->
              <!-- {{availableKeyList}}
              {{infoSettingForm.getFieldValue('tableName-' + index66 +'-' + index)}}
              {{infoSettingForm.getFieldValue('key-' + index66 +'-' + index)}} -->

              <a-form-item v-if="checkIfSelectOptionAppears(availableKeyList, infoSettingForm.getFieldValue('tableName-' + index66 +'-' + index), infoSettingForm.getFieldValue('key-' + index66 +'-' + index))">
              <!-- {{checkIfSelectOptionAppears(availableKeyList, infoSettingForm.getFieldValue('tableName-' + index66 +'-' + index), infoSettingForm.getFieldValue('key-' + index66 +'-' + index))}} -->
               <!-- {{availableKeyList.find(item=>item.tblKey == 'stKind')}} -->
               <!-- {{availableKeyList.find(item=>item.tblKey == "stKind").selVals}} -->
                <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-option v-for="(item1) in 
                  JSON.parse((availableKeyList.find(item=>item.tblKey == infoSettingForm.getFieldValue('val-' + index66 +'-' + index))).selVals)
                  " :key='item1' :value="item1.value">{{item1.name}}</a-select-option> -->
                </a-select>
              </a-form-item>

              <a-form-item v-else>
                <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-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-select v-if="infoSettingForm.getFieldValue('codition-'+index66 +'-' + index) == 'eq' || infoSettingForm.getFieldValue('codition-'+index66 +'-' + index) == 'regex' || infoSettingForm.getFieldValue('codition-'+index66 +'-' + index) == undefined" style="width: 80px" placeholder='查询方式' v-decorator="['selMet-' + index66 +'-' + index,{initialValue: item.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>
              <!-- {{index + `,` + loopContent.data[index66].labelSelConditionList.length}} -->
              <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 v-if="index !== 0 && index+1 == loopContent.data[index66].labelSelConditionList.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>
    <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>
    <!-- <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 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-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),
      resultModalVisible: false,
      loopContent: {
        // data: [{
        //   key: '',
        //   tableName: '',
        //   codition: 'eq',
        //   val: '',
        //   selMet: ''
        // }],
      },
      objSelectOptions: [
        {
          name: '小区',
          value: 'tbl_community'
        },
        {
          name: '门牌',
          value: 'tbl_building'
        },
        {
          name: '物业',
          value: 'tbl_prop_company'
        },
        {
          name: '业委会',
          value: 'tbl_industry_council'
        }
      ],
      verifySelect: false,
      verifyInput: false,
      jsonData: {},
      deleteVisible: false,
      confirmVisible: false,
      finish: false,
      parentLabelList: [],
      availableKeyList: [],
      initKey: '',
      resultList: [],
      labelNameForDel: '',
      columns: [
        {
          tbl_community: [
            {
              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',
            },
          ],
          tbl_building: [
            {
              title: '门牌地址',
              // width: 240,
              dataIndex: 'unitAddr',
              key: 'unitAddr',
              align: 'center',
            },
            {
              title: '门牌类型',
              // width: 240,
              dataIndex: 'unitKindName',
              key: 'unitKindName',
              align: 'center',
            },
            {
              title: '门牌所在路',
              // width: 240,
              dataIndex: 'uLoad',
              key: 'uLoad',
              align: 'center',
            },
            {
              title: '门牌所在弄',
              // width: 240,
              dataIndex: 'uLong',
              key: 'uLong',
              align: 'center',
            },
          ],
          tbl_prop_company: [
            {
              title: '物业名称',
              // width: 240,
              dataIndex: 'cspName',
              key: 'cspName',
              align: 'center',
            },
            {
              title: '物业联系人',
              // width: 240,
              dataIndex: 'cspContacter',
              key: 'cspContacter',
              align: 'center',
            },
            {
              title: '物业地址',
              // width: 240,
              dataIndex: 'cspAddr',
              key: 'cspAddr',
              align: 'center',
            },
            {
              title: '注册地址',
              // width: 240,
              dataIndex: 'registerAddress',
              key: 'registerAddress',
              align: 'center',
            },
          ],
          tbl_industry_council: [
            {
              title: '业委会名称',
              // width: 240,
              dataIndex: 'hocName',
              key: 'hocName',
              align: 'center',
            },
            {
              title: '业委会地址',
              // width: 240,
              dataIndex: 'hocAddr',
              key: 'hocAddr',
              align: 'center',
            },
            {
              title: '竞选时间',
              // width: 240,
              dataIndex: 'electionDate',
              key: 'electionDate',
              align: 'center',
            },
            {
              title: '开始时间',
              // width: 240,
              dataIndex: 'conStartDate',
              key: 'conStartDate',
              align: 'center',
            },
            {
              title: '结束时间',
              // width: 240,
              dataIndex: 'conEndDate',
              key: 'conEndDate',
              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.initKeyList()
        this.resetFormFields()
        this.getLabelDetail()
      },
      immediate: true
    },
  },
  methods: {
    clearForm(formToClear) {
      console.log(formToClear)
      this.infoSettingForm.resetFields(formToClear)
    },
    getSelectedProperty(val) {
      console.log(val)
    },
    handleResultCancel() {
      this.resultModalVisible = !this.resultModalVisible
    },
    clearNextKey(col) {
      console.log(col)
      // console.log(this.infoSettingForm.resetFields());
    },
    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))
      
      if (!findKey || !findKey.selVals) return false

      return true

      let resultList = []
      let obj = JSON.parse(findKey.selVals)
      for (const key in obj) {
        resultList.push({
          name: key,
          value: obj[key]
        })
      }
      console.log(resultList)
      return resultList
      // for(let i = 0; i < options.length; i++) {
      //   if(options[i].tblKey == key) {
      //     if(options[i].tblKey == null) {
      //       console.log(JSON.parse(options[i].selVals));

      //       let resultList = []
      //       let obj = JSON.parse(options[i].selVals)
      //       for (const key in obj) {
      //         resultList.push({
      //           name: key,
      //           value: obj[key]
      //         })
      //       }

      //       return resultList
      //       // return JSON.parse(options[i].selVals)
      //     } else {
      //       return null
      //     }
      //   }
      // }
    },
    cnonvertObjSecond() {},
    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',
                      selMet: formData['selMet-' + i + '-' + index]
                    })
                  })

                  innerResult.push({
                    '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, { serial: '新分组', relation: 'and', labelSelConditionList: [ { key: '', val: '', tableName: '', codition: 'eq', selMet: '', relation: '' } ] }
      ])

      this.$forceUpdate()

      console.log(JSON.stringify(this.loopContent))
    },
    delGroup(key) {
      console.log(key)
      Vue.delete(this.loopContent.data, key)
      this.$forceUpdate()
    },
    initKeyList() {
      // 获取当前的对象
      this.initKey = this.labelForm.getFieldValue('tableName')
      this.getKeyList(this.initKey)
    },
    handleObjChange(val) {
      // 确定插入到哪一行
      console.log(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

          }
        })
      } 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.data[whichGroup].labelSelConditionList.push({
        key: '',
        tableName: '',
        codition: 'eq',
        val: '',
        relation: 'and',
        selMet: ''
      })
      this.$forceUpdate()
      console.log(this.loopContent)
    },
    deleteRow(whichGroup, whichRow) {
      console.log(whichGroup, whichRow)
      this.loopContent.data[whichGroup].labelSelConditionList.splice(whichRow, 1)
      this.$forceUpdate()
      // 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 = !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: '新分组', relation: 'and', labelSelConditionList: [ { key: '', val: '', tableName: '', codition: 'eq', selMet: '', relation: '' } ] } ]

      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',
                selMet: formData['selMet-' + i + '-' + index]
              })
            })

            // console.log(!!formData['relationWithGroup-' + i + '-0']? formData['relationWithGroup-' + i + '-0']: 'and');
            
            // relationWithGroup-0-0
            innerResult.push({
              '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', [])
          
          // this.resetFormFields()
          // this.finish = true
          // this.$emit('finish', this.finish)
        } 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',
                      selMet: formData['selMet-' + i + '-' + index]
                    })
                  })

                  innerResult.push({
                    '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>