<script>
import _ from 'lodash'
import util from '../common/util.js'
import DimensionCatalogSelector from '../pages/contentadvance/dimensionCatalogSeletor.vue'
var getEmptyCondition = function () {
  return [{
    joinOperator: null,
    conditions: [{
      column: 'Attribute',
      operator: '',
      value: [],
      joinOperator: null
    }]
  }]
}

var getEmptySortfield = function () {
  return [{
    column: '',
    type: ''
  }]
}
export default {
  components: {
    DimensionCatalogSelector
  },
  props: {
    // 条件数据
    conditions: {
      type: Array,
      default: null
    },
    // 排序数据
    sortFields: {
      type: Array,
      default: null
    },
    // 是否包含排序方式
    hasOrder: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      initdata: {},
      conditionData: _.extend([], this.conditions),
      sortFieldData: _.extend([], this.sortFields),
      dimensionCatalogDlg: {
        isShowModal: false,
        dimensionID: null,
        names: '',
        ids: [],
        currentConditionItem: null
      }
    }
  },
  computed: {
    /*
      // TODO:增加数据合法性校验
      isValid(){
        let result = true
        for(let i = 0,leng = this.conditionData.length;i<leng;i++) {
          let groupItem = this.conditionData[i]
          // 判断连接符
          if(i === 0) {
            if(groupItem.joinOperator !== null) {
              console.warn('条件格式不对，第一个条件组合的joinOperator值必须为null')
              return false
            }
          } else {
            if (groupItem.joinOperator !== 'and' && groupItem.joinOperator !== 'or') {
              console.warn('条件格式不对，条件组合的joinOperator值为and或or')
              return false
            }
          }

          // 判断conditions
        }
      } */
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      if (this.conditions === null) {
        this.conditionData = getEmptyCondition()
      }
      if (this.sortFields === null) {
        this.sortFieldData = getEmptySortfield()
      }
      // 组件相关数据初始化
      let initdata = await axios.get('/ui/conditionfilter/initData')
      this.initdata = initdata.data.data
      this.$emit('data-loaded')
    },
    columnChange(conditionItem) {
      conditionItem.operator = ''
      if (conditionItem.column === 'Attribute') {
        conditionItem.value = []
      } else if (conditionItem.column === 'TopFlag') {
        conditionItem.value = this.initdata.columnOptions.TopFlag.valueOptions[1].key
      } else {
        conditionItem.value = ''
      }
    },
    sortColumnChange(sortItem) {
      const curColumn = sortItem.column
      var data = this.sortFieldData.filter((sort) => {
        return sort.column === curColumn
      })
      if (data.length > 1) {
        util.showErrorNotification('已经存在相同的排序字段')
        sortItem.column = ''
      }
    },
    addConditionBlock() {
      this.conditionData.push({
        joinOperator: 'and',
        conditions: [{
          column: 'Attribute',
          operator: '',
          value: [],
          joinOperator: null
        }]
      })
    },
    minusConditionBlock(idx) {
      this.conditionData.splice(idx, 1)
    },
    addConditionItem(idx) {
      this.conditionData[idx].conditions.push({
        column: '',
        operator: '',
        value: [],
        joinOperator: 'and'
      })
    },
    minusConditionItem(i, j) {
      this.conditionData[i].conditions.splice(j, 1)
    },
    choiceDimensionCatalog(conditionItem) {
      this.dimensionCatalogDlg.dimensionID = this.initdata.columnOptions[conditionItem.column].valueOptions.ID
      this.dimensionCatalogDlg.currentConditionItem = conditionItem
      this.dimensionCatalogDlg.ids = []
      const val = conditionItem.value
      if (val && val.indexOf('&&') > 0) {
        val.split('&&')[0].split(',').forEach(id => {
          this.dimensionCatalogDlg.ids.push(parseInt(id, 10))
        })
      }
      this.dimensionCatalogDlg.isShowModal = true
    },
    getCheckeDimenstionCatalogs(catalog) {
      this.dimensionCatalogDlg.currentConditionItem.value = catalog
    },
    addSortItem() {
      this.sortFieldData.push({
        column: '',
        type: ''
      })
    },
    minusSortItem(idx) {
      this.sortFieldData.splice(idx, 1)
    }
  },
  filters: {
    showDimensionData: function (val) {
      return val.indexOf('&&') > 0 ? val.split('&&')[1] : val
    }
  },
  watch: {
    conditionData: {
      handler: function (val, oldVal) {
        this.$emit('update:conditions', val)
        this.$emit('conditionsChanged', {
          val,
          oldVal
        })
      },
      deep: true
    },
    sortFieldData: {
      handler: function (val, oldVal) {
        this.$emit('update:sortFields', val)
        this.$emit('sortFieldsChanged', {
          val,
          oldVal
        })
      },
      deep: true
    }
  }
}

</script>
<template>
  <div class="component-condition-filter">
    <div class="condition-filter-wrap">
      <fieldset v-if="initdata.columns" v-for="(conditionBlock,i) in conditionData" :key="i" class='condition-filter-block'>
        <legend>筛选条件{{i + 1}}</legend>
        <div class="condition-filter-block-join" v-if="i>0">
          <el-radio-group v-model="conditionBlock.joinOperator">
            <el-radio :label="item.key" v-for="item in initdata.groupOprators" :key="item.key">{{item.value}}</el-radio>
          </el-radio-group>
        </div>
        <div class="condition-oprate">
          <el-button @click="addConditionBlock" v-show="i === conditionData.length-1 && conditionData[i].conditions[0].value.length > 0"
            title="新增分组条件">
            <i class="fa fa-plus"></i>
          </el-button>
          <el-button @click="minusConditionBlock(i)" v-show="i !== 0" title="删除分组条件">
            <i class="fa fa-minus"></i>
          </el-button>
        </div>
        <el-row :gutter="4" class="condition-item" v-for="(conditionItem,j) in conditionBlock.conditions" :key="j">
          <el-col :span="3">
            <el-select style="width:100%" v-model="conditionItem.joinOperator" v-if="conditionItem.joinOperator !== null">
              <el-option v-for="item in initdata.groupOprators" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
            <span v-else>&nbsp;</span>
          </el-col>
          <el-col :span="4">
            <el-select v-model="conditionItem.column" style="width:100%" @change="columnChange(conditionItem)">
              <el-option v-for="item in initdata.columns" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="conditionItem.operator" v-if="conditionItem.column !== ''" style="width:100%">
              <el-option v-for="item in initdata.columnOptions[conditionItem.column].oprator" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="10">
            <el-checkbox-group style="margin-top:5px;" v-model="conditionItem.value" v-if="conditionItem.column === 'Attribute' && conditionItem.operator !== ''">
              <el-checkbox v-for="item in initdata.columnOptions[conditionItem.column].valueOptions" :key="item.key" :label="item.key">{{item.value}}&nbsp;&nbsp;</el-checkbox>
            </el-checkbox-group>
            <el-input v-model="conditionItem.value" style="width:100%" v-if="['Author','Keyword','Source','tag','Title'].includes(conditionItem.column) && conditionItem.operator !== ''"></el-input>
            <el-date-picker v-model="conditionItem.value" type="datetime" style="width:100%" v-if="conditionItem.column === 'PublishDate' && conditionItem.operator !== ''">
            </el-date-picker>

            <el-radio-group v-model="conditionItem.value" v-if="conditionItem.column === 'TopFlag' && conditionItem.operator !== ''">
              <el-radio v-for="item in initdata.columnOptions[conditionItem.column].valueOptions.filter((item) => item.key!='')" :label="item.key"
                :key="item.key">{{item.value}}</el-radio>
            </el-radio-group>

            <el-select v-model="conditionItem.value" style="width:100%" v-if="conditionItem.column === 'BranchInnerCode' && conditionItem.operator !== ''">
              <el-option v-for="item in initdata.columnOptions[conditionItem.column].valueOptions" :key="item.key" :label="item.value"
                :value="item.key">
              </el-option>
            </el-select>

            <el-input disabled :value="conditionItem.value | showDimensionData" style="width:100%" v-if="conditionItem.column.indexOf('DimensionCatalog') === 0 && conditionItem.operator !== ''"
              placeholder="">
              <el-button slot="append" @click="choiceDimensionCatalog(conditionItem)">选择</el-button>
            </el-input>
          </el-col>
          <el-col :span="3">
            <el-button v-show="(conditionItem.value !== '' ||conditionItem.value.length > 0) && j === conditionBlock.conditions.length - 1"
              @click="addConditionItem(i)">
              <i class="fa fa-plus"></i>
            </el-button>
            <el-button @click="minusConditionItem(i,j)" v-if="j !== 0">
              <i class="fa fa-minus"></i>
            </el-button>
          </el-col>
        </el-row>
      </fieldset>
    </div>
    <div class="condition-order-wrap" v-if="hasOrder">
      <fieldset v-if="initdata.orderConditionColumns" class='condition-order-block'>
        <legend>排序方式</legend>
        <el-row :gutter="4" v-for="(sortItem,i) in sortFieldData" :key="i" class="sort-item">
          <el-col :offset="3" :span="4">
            <el-select v-model="sortItem.column" @change="sortColumnChange(sortItem)" style="width:100%">
              <el-option v-for="item in initdata.orderConditionColumns" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-show="sortItem.column !== ''" v-model="sortItem.type" style="width:100%">
              <el-option v-for="item in initdata.orderTypes" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button v-show="i === sortFieldData.length - 1 && sortFieldData.length < initdata.orderConditionColumns.length && sortItem.column.length > 0 && sortItem.type.length > 0"
              @click="addSortItem()">
              <i class="fa fa-plus"></i>
            </el-button>
            <el-button @click="minusSortItem(i)" v-if="i !== 0">
              <i class="fa fa-minus"></i>
            </el-button>
          </el-col>
        </el-row>
      </fieldset>
    </div>
    <dimension-catalog-selector :show.sync="dimensionCatalogDlg.isShowModal" class="condition-dimension-selector" :ID="dimensionCatalogDlg.dimensionID"
      :checked-ids="dimensionCatalogDlg.ids" @callback="getCheckeDimenstionCatalogs">
    </dimension-catalog-selector>
  </div>
</template>
<style>
  .component-condition-filter fieldset {
    border: none;
    margin: 0;
    padding: 0;
  }

  .component-condition-filter legend {
    width: 100%;
    border: none;
    border-bottom: 1px solid #e5e5e5;
    color: #333;
    font-size: 14px;
    position: relative;
    line-height: 32px;
    padding: 3px 0px;
    margin-bottom: 7px;
  }

  .component-condition-filter .el-checkbox {
    margin-left: 0;
  }

  .component-condition-filter .el-checkbox__label {
    margin-left: 3px;
  }

  .component-condition-filter button>span>i {
    padding-right: 0;
  }

  .condition-filter-block {
    position: relative
  }

  .component-condition-filter .condition-oprate {
    position: absolute;
    right: 10px;
    top: -5px;
  }

  .condition-filter-block+.condition-filter-block {
    margin-top: 40px;
  }

  .condition-filter-block .condition-filter-block-join {
    position: absolute;
    top: -24px;
    left: 45%;
  }

  .condition-filter-block .condition-item,
  .condition-order-block .sort-item {
    margin-bottom: 7px;
  }

  .condition-filter-block .el-checkbox__label {
    padding-left: 2px;
  }

  .condition-filter-block .condition-item .el-radio-group {
    padding-top: 8PX;
  }

  /**隐藏维度分类选择窗口中树节点上的站点复选框**/

  .dim-catalog-selector .el-tree>.el-tree-node>.el-tree-node__content .el-checkbox__inner {
    display: none;
  }

</style>
