<template>
  <div class="routerWapper">
		<div>
      <!-- {{triggerType}} - {{labelId}} - {{finish}} - {{jsonData}} - {{initKey}} -->
      <a-row>
        <a-col :span='1' v-if="triggerType == 'create'">
          <a-button type='default' @click="backPage()">返回</a-button>
        </a-col>
        <a-col :span='1' v-else>
          <a-button type='default' @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' />
    <a-form :form='labelForm'>
      <a-form-item label='标签名' :label-col="{span:2}" :wrapper-col="{span:14}">
        <a-input v-decorator="['labelName',{validateTrigger:'blur', initialValue: jsonData.labelName?jsonData.labelName: '', rules: [{required: true, message: '请填写标签名！'}]}]"></a-input>
      </a-form-item>
      <a-form-item label='标签分组' :label-col="{span:2}" :wrapper-col="{span:14}">
        <a-select v-decorator="['parentId',{validateTrigger:'blur', initialValue: jsonData.parentId?jsonData.parentId: '0', rules: []}]">
          <a-select-option value='0'>无（将改标签设为一级标签）</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-form-item label='业务对象' :label-col="{span:2}" :wrapper-col="{span:14}">
        <a-select :disabled="triggerType == 'loadChildLabel'" @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>
    <a-row style="font-weight: bold">信息筛选配置</a-row>
    <a-form :form='infoSettingForm' layout='inline'>
      <div v-for="(item, index) in loopContent.data" :key='index'>
        <a-form-item v-if="!!item.relation">
          <a-select style="width: 120px" placeholder='请选择条件' v-decorator="['relation' + 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 v-else style="margin-left: 120px"></a-form-item>

        <a-form-item>
          <a-select style="width: 120px" placeholder='请选择业务属性' v-decorator="['key' + index,{initialValue: item.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' + index,{initialValue: item.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>

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

        <a-form-item>
          <a-select style="width: 120px" placeholder='查询方式' v-decorator="['selMet' + 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>
        <a-form-item>
          <a-icon v-if="index+1 == loopContent.data.length" theme='filled' style="color:lightgreen;" type="plus-circle" @click="addRow()" />
          <a-icon v-if="index+1 == loopContent.data.length" theme='filled' style="color:red; margin-left: 5px" type="minus-circle" @click="deleteRow(index)" />
        </a-form-item>
      </div>
    </a-form>
    <a-button type='link' v-if="loopContent.data.length == 0" @click="addInitRow()">新增配置</a-button>
    <a-modal :visible='deleteVisible' @ok='handleDeleteOk' @cancel='handleCancelOk'>
      确定删除该标签【{{labelId}}】吗?
    </a-modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      labelForm: this.$form.createForm(this),
      infoSettingForm: this.$form.createForm(this),
      loopContent: {
        data: [{
          key: '',
          codition: 'eq',
          val: '',
          selMet: ''
        }]
      },
      jsonData: {},
      deleteVisible: false,
      finish: false,
      parentLabelList: [],
      availableKeyList: [],
      initKey: ''
    }
  },
  mounted() {
    console.log('得到的' + this.labelId)
    this.getLabelDetail()
    this.getParentLabelList()
    // 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: {
    initKeyList() {
      // 获取当前的对象
      this.initKey = this.labelForm.getFieldValue('tableName')
      this.getKeyList(this.initKey)
    },
    handleObjChange(val) {
      this.getKeyList(val)
      // 重置key表项的值为空 或 业务对象干脆disable掉
    },
    getKeyList(val) {
      console.log('111')
      this.availableKeyList = []
      this.$ajax.get({
        url: this.$api.GET_AVAILABLE_KEY_LIST,
        params: {
          'tableName': val
        }
      }).then(res => {
        if (res.code == 200) {
          let list = res.data.content
          console.log(list)
          this.availableKeyList = []
          for(let i = 0; i < list.length; i++) {
            this.availableKeyList.push({
              'tblKey': list[i].tblKey,
              'tblKeyName': list[i].tblKeyName
            })
          }
        }
      })
    },
    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.loopContent.data = res.data.content.selParams
            console.log(res.data.content.selParams)
            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) {
      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)
    },
    addInitRow() {
      this.loopContent.data.push({
        key: '',
        codition: 'eq',
        val: '',
        selMet: ''
      })
    },
    addRow() {
      this.loopContent.data.push({
        key: '',
        codition: 'eq',
        val: '',
        relation: 'and',
        selMet: ''
      })
      console.log(this.loopContent)
    },
    deleteRow(index) {
      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) {
      // 查询该标签是否是一级标签，是一级标签直接删除。
      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 = []
      this.labelForm.resetFields()
    },
    save() {
      this.jsonData = {selParams: []}
      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 loopCounts = this.loopContent.data.length
              let formData = this.infoSettingForm.getFieldsValue()
              for(let i = 0; i < loopCounts; i++) {
                this.jsonData.selParams.push({
                  key: formData['key'+i],
                  val: !formData['inputTwo' + i] ? formData['inputOne' + i] : formData['inputOne' + i] + ',' + formData['inputTwo' + i],
                  codition: formData['codition'+i],
                  relation: formData['relation' + i],
                  selMet: formData['selMet' + i]
                })
              }
              this.$ajax.post({
                url: this.$api.GET_LABEL_BIND_FILTER_RESULT,
                params: this.jsonData
              }).then(res => {
                if (res.code == 200) {
                  console.log(res.data.content)
                  // this.$message.success('修改成功!')
                  // this.resetFormFields()
                  // this.finish = true
                  // this.$emit('finish', this.finish)
                } else {
                  this.$message.success('修改失败!')
                }
              })
              // 提交标签内容, 如果有labelId则调用put接口，反之调用post接口
              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.$message.success('修改失败!')
                  }
                })
              } 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('保存失败!')
                  }
                })
              }
            }
          })
        }
      })
    },
  },
}
</script>