<template>
  <div class="filter-user">
    <div class="filter-option">
      <el-select
        v-model="filterType"
        class="filter-item"
        :placeholder="$t('common.selectType')"
        @change="handleFilterTypeChange"
      >
        <el-option v-for="(item,key) in allFilterTypes" :key="key" :label="item.name" :value="key" />
      </el-select>
      <el-select
        v-model="filterSymbol"
        class="filter-item"
        :placeholder="$t('common.selectFunction')"
      >
        <el-option v-for="(item,key) in filterSymbols" :key="key" :label="item" :value="key" />
      </el-select>
      <template
        v-if="filterType !== '' && allFilterTypes[filterType].hasOwnProperty('other') && allFilterTypes[filterType].other === 'date'"
      >
        <el-date-picker
          v-model="filterValue"
          class="filter-item"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          :placeholder="$t('common.selectDate')"
        />
      </template>
      <template
        v-else-if="filterType !== '' && allFilterTypes[filterType].hasOwnProperty('other') && allFilterTypes[filterType].other === 'month'"
      >
        <el-date-picker
          v-model="filterValue"
          class="filter-item"
          value-format="yyyyMM"
          type="month"
          :placeholder="$t('common.selectMonth')"
        />
      </template>
      <template
        v-else-if="filterType !== '' && allFilterTypes[filterType].hasOwnProperty('other') && allFilterTypes[filterType].other === 'area'"
      >
        <el-cascader
          v-model="filterAreaValue"
          class="filter-item"
          :options="regionData"
          :props="{ checkStrictly: true }"
        />
      </template>
      <template
        v-else-if="filterType !== '' && allFilterTypes[filterType].hasOwnProperty('other') && allFilterTypes[filterType].other === 'select'"
      >
        <el-select
          v-model="filterValue"
          class="filter-item"
          :placeholder="`请选择${allFilterTypes[filterType].name}`"
        >
          <el-option
            v-for="(item,key) in allFilterTypes[filterType].selectData"
            :key="key"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </template>
      <template
        v-else-if="filterType !== '' && allFilterTypes[filterType].hasOwnProperty('other') && filterCustomType.hasOwnProperty(allFilterTypes[filterType].other)"
      >
        <el-select v-model="filterValue" class="filter-item" :placeholder="`${filterCustomType[allFilterTypes[filterType].other].placeholder}`">
          <el-option v-for="(item,key) in filterCustomType[allFilterTypes[filterType].other].values" :key="key" :label="item[filterCustomType[allFilterTypes[filterType].other].labelField]" :value="item[filterCustomType[allFilterTypes[filterType].other].valueField]" />
        </el-select>
      </template>
      <template v-else>
        <el-input v-model="filterValue" class="filter-item filter-value" :placeholder="$t('common.pleaseInputContent')" />
      </template>
      <el-select
        v-model="filterRelation"
        class="filter-item filter-relation"
        :placeholder="$t('common.relation')"
      >
        <el-option v-for="(item,key) in filterRelations" :key="key" :label="item" :value="key" />
      </el-select>
      <el-button class="filter-item" icon="el-icon-plus" @click="handleOptionPlus" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilterUser">{{ filterBtnName }}</el-button>
      <el-button class="filter-item" type="" @click="handleFilterClear">{{ $t('common.reset') }}</el-button>
      <el-button class="down-button" type="text"><i class="el-icon-arrow-down" /></el-button>
    </div>
    <div v-show="filterSelected.length > 0" class="filter-selected">
      <el-tag
        v-for="(item,key) in filterSelected"
        :key="key"
        class="selected-tag"
        closable
        @close="handleCloseTag(key)"
      >{{ item.filterTypeName }} {{ item.filterSymbolName }} {{ item.filterName }}
      </el-tag>
    </div>
    <el-dialog :title="$t('filter.memberSelect')" :visible.sync="filterUserDialogShow" width="80%">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column :label="$t('filter.memberNumber')">
          <template slot-scope="scope">
            {{ scope.row.USER_NAME }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('filter.name')">
          <template slot-scope="scope">
            {{ scope.row.REAL_NAME }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('filter.idNumber')" width="180">
          <template slot-scope="scope">
            {{ scope.row.ID_CARD }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('filter.phoneNumber')">
          <template slot-scope="scope">
            {{ scope.row.MOBILE }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('filter.memberLevel')">
          <template slot-scope="scope">
            {{ scope.row.DEC_LV ? filterCustomType.decLevel.values[scope.row.DEC_LV]['LEVEL_NAME'] : '' }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('filter.level')">
          <template slot-scope="scope">
            {{ scope.row.EMP_LV ? filterCustomType.empLevel.values[scope.row.EMP_LV]['LEVEL_NAME'] : '' }}
          </template>
        </el-table-column>
      </el-table>
      <div class="white-box-footer">
        <el-button type="primary" size="small" :disabled="multipleSelectionUserId == undefined || multipleSelectionUserId.length <= 0?true:false" @click="handleSelectValue(false)">{{ $t('filter.confirmSelect') }}</el-button>
        <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { filterUser } from '@/api/filter'
import baseInfo from '@/utils/baseInfo'
import store from '@/utils/vuexStore'
import Pagination from './Pagination'
import filterHelper from '@/utils/filterHelper'

export default {
  name: 'FilterUser',
  components: { Pagination },
  props: {
    filterTypes: {
      type: Object,
      default() {
        return {
          'USER_NAME': { isUserTable: true, name: this.$t('filter.memberNumber') },
          'REAL_NAME': { isUserTable: true, name: this.$t('filter.memberName') },
          'ID_CARD': { isUserTable: true, name: this.$t('filter.ID') },
          'MOBILE': { isUserTable: true, name: this.$t('filter.phoneNumber') },
          'CREATED_AT': { isUserTable: true, name: this.$t('filter.addAt'), other: 'date' }
        }
      }
    },
    filterBtnName: {
      type: String,
      default() {
        return this.$t('filter.memberSelect')
      }
    }
  },
  data() {
    return {
      loading: false,
      filterUserDialogShow: false,
      tableData: [],
      currentPage: 1,
      totalPages: 1,
      totalCount: 1,
      pageSize: 20,
      filterCustomType: {
        decLevel: {
          placeholder: this.$t('filter.pleaseSelectDecLevel'),
          labelField: 'LEVEL_NAME',
          valueField: 'ID',
          values: baseInfo.decLevels()
        },
        empLevel: {
          placeholder: this.$t('filter.pleaseSelectEmpLevel'),
          labelField: 'LEVEL_NAME',
          valueField: 'ID',
          values: baseInfo.empLevels()
        },
        decRole: {
          placeholder: '请选择报单中心级别',
          labelField: 'ROLE_NAME',
          valueField: 'ID',
          values: baseInfo.decRoles()
        },
        subCompany: {
          placeholder: '请选择分公司',
          labelField: 'COM_NAME',
          valueField: 'ID',
          values: baseInfo.subCompanies()
        },
        status: {
          placeholder: '请选择会员状态',
          labelField: 'label',
          valueField: 'value',
          values: baseInfo.allStatus()
        },
        dealTypes: {
          placeholder: '请选择交易类型',
          labelField: 'TYPE_NAME',
          valueField: 'ID',
          values: baseInfo.dealTypes()
        },
        systems: {
          placeholder: '请选择体系',
          labelField: 'SYSTEM_NAME',
          valueField: 'ID',
          values: baseInfo.systems()
        },
        sex: {
          placeholder: '请选择性别',
          labelField: 'label',
          valueField: 'value',
          values: {
            '男': { label: '男', value: '男' },
            '女': { label: '女', value: '女' }
          }
        },
        yesOrNo: {
          placeholder: '请选择是否',
          labelField: 'label',
          valueField: 'value',
          values: {
            1: { label: '是', value: 1 },
            0: { label: '否', value: 0 }
          }
        },
        banks: {
          placeholder: '请选择开户行',
          labelField: 'BANK_NAME',
          valueField: 'BANK_CODE',
          values: baseInfo.allOpenBank()
        },
        nations: {
          placeholder: '请选择民族',
          labelField: 'name',
          valueField: 'id',
          values: baseInfo.allNation()
        },
        location: {
          placeholder: '请选择市场',
          labelField: 'label',
          valueField: 'value',
          values: {
            1: { label: '一市场', value: 1 },
            2: { label: '二市场', value: 2 },
            3: { label: '三市场', value: 3 },
            4: { label: '四市场', value: 4 },
            5: { label: '五市场', value: 5 }
          }
        }
      },
      filterModel: {
        userId: ''
      },
      allFilterTypes: this.filterTypes,
      filterType: '',
      filterSymbol: '',
      filterSymbols: {
        '=': this.$t('filter.eq'),
        'like': this.$t('filter.like'),
        '<>': this.$t('filter.noeq'),
        'notLike': this.$t('filter.nolike'),
        '>': this.$t('filter.moreThan'),
        '>=': this.$t('filter.moreThanEq'),
        '<': this.$t('filter.less'),
        '<=': this.$t('filter.lessThan')
      },
      filterRelation: 'and',
      filterRelations: {
        'and': this.$t('filter.and'),
        'or': this.$t('filter.or')
      },
      filterValue: '',
      filterName: '',
      filterSelected: [],
      selectData: [],
      multipleSelection: [],
      multipleSelectionUserId: [],
      regionData: store.state.regionInfo.regionData,
      filterAreaValue: [],
      filterRequest: {}
    }
  },
  watch: {
    filterTypes(newVal) {
      this.allFilterTypes = this.filterTypes
    }
  },
  methods: {
    handleFilterTypeChange() {
      this.filterValue = ''
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.multipleSelectionUserId = []
      for (const i in this.multipleSelection) {
        this.multipleSelectionUserId.push(this.multipleSelection[i].ID)
      }
    },
    handleCurrentChange(page) {
      this.getData(this.filterRequest, page, this.pageSize)
    },
    handleSizeChange(pageSize) {
      this.getData(this.filterRequest, this.currentPage, pageSize)
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        filterUser({ kw: query }).then(response => {
          this.selectData = response
          this.loading = false
        }).catch(err => {
          this.loading = false
        })
      }
    },
    handleOptionPlus() {
      if (this.filterType === '' || this.filterSymbol === '' || (this.filterValue === '' && this.filterAreaValue === [])) {
        this.$message({
          message: this.$t('filter.selectContentNotice'),
          type: 'warning'
        })
        return false
      }
      let valueName = this.filterValue
      if (this.filterType !== '' && this.allFilterTypes[this.filterType].hasOwnProperty('other')) {
        // 获取下拉筛选时的选中项
        if (this.allFilterTypes[this.filterType].other === 'select') {
          let nameObj = []
          const _this = this
          if (!Array.isArray(this.allFilterTypes[this.filterType].selectData)) {
            nameObj[0] = this.allFilterTypes[this.filterType].selectData[_this.filterValue]
          } else {
            nameObj = (this.allFilterTypes[this.filterType].selectData).filter(function(item, index, array) {
              return item.id === _this.filterValue
            })
          }
          valueName = nameObj[0] ? nameObj[0].name : null
        } else if (this.allFilterTypes[this.filterType].other === 'area') {
          if (this.filterSymbol !== '=') {
            this.$message({
              message: this.$t('filter.areaSelectNotice'),
              type: 'warning'
            })
            return false
          }
          this.filterValue = this.filterAreaValue.join(',')
          valueName = ''
          for (const i in this.regionData) {
            if (this.regionData[i].value === this.filterAreaValue[0]) {
              valueName += this.regionData[i].label + ','
              for (const j in this.regionData[i].children) {
                if (this.regionData[i].children[j].value === this.filterAreaValue[1]) {
                  valueName += this.regionData[i].children[j].label + ','
                  for (const h in this.regionData[i].children[j].children) {
                    if (this.regionData[i].children[j].children[h].value === this.filterAreaValue[2]) {
                      valueName += this.regionData[i].children[j].children[h].label
                      break
                    }
                  }
                  break
                }
              }
              break
            }
          }
        } else if (this.filterCustomType.hasOwnProperty(this.allFilterTypes[this.filterType].other)) {
          const allCustomData = this.filterCustomType[this.allFilterTypes[this.filterType].other].values
          const customField = this.filterCustomType[this.allFilterTypes[this.filterType].other].labelField
          valueName = allCustomData[this.filterValue][customField]
        }
      }
      // 如果是筛选会员编号，则把会员编号转成小写
      // if(this.filterType === 'USER_NAME'){
      //   this.filterValue = this.filterValue.toLowerCase()
      // }

      this.filterSelected.push({
        filterType: this.filterType,
        filterTypeName: this.allFilterTypes[this.filterType].name,
        filterSymbol: this.filterSymbol,
        filterSymbolName: this.filterSymbols[this.filterSymbol],
        filterValue: this.filterValue,
        filterRelation: this.filterRelation,
        filterRelationName: this.filterRelations[this.filterRelation],
        filterName: valueName,
        filterOther: this.filterType !== '' && this.allFilterTypes[this.filterType].hasOwnProperty('other') ? this.allFilterTypes[this.filterType].other : null,
        isUserTable: this.allFilterTypes[this.filterType].isUserTable
      })
    },
    handleCloseTag(tag) {
      this.filterSelected.splice(tag, 1)
    },
    handleFilterUser() {
      console.log('===>>>', this.filterSelected.length, '<<===')
      if (this.filterSelected.length > 0) {
        this.loading = true
        this.filterRequest = {}
        for (const i in this.filterSelected) {
          if (this.filterSelected[i].isUserTable) {
            let reqFilterValue = `${this.filterSelected[i].filterSymbol},${this.filterSelected[i].filterValue}`
            if (this.filterSelected[i].hasOwnProperty('filterOther')) {
              reqFilterValue += `,${this.filterSelected[i].filterOther}`
            }
            const filterType = this.filterSelected[i].filterType
            if (this.filterRequest[filterType]) {
              this.$set(this.filterRequest, filterType, (this.filterRequest[filterType] + '|' + reqFilterValue))
            } else {
              this.$set(this.filterRequest, filterType, reqFilterValue)
            }
          }
        }
        if (Object.keys(this.filterRequest).length === 0) {
          this.handleSelectValue(true)
        } else {
          this.getData(this.filterRequest, this.currentPage)
        }
      }
    },
    getData(request, page = null, pageSize = null) {
      request.page = page
      request.pageSize = pageSize

      filterUser(this.listQuery).then(response => {
        this.filterUserDialogShow = true
      })
    },
    handleSelectValue(isAll = false) {
      const otherFilterTypes = []
      for (const i in this.filterSelected) {
        if (!this.filterSelected[i].isUserTable) {
          otherFilterTypes.push(this.filterSelected[i])
        }
      }
      let userIds = this.multipleSelectionUserId
      if (isAll) {
        userIds = 'all'
      }
      this.$emit('select-value', {
        userIds: userIds,
        otherFilterTypes: otherFilterTypes
      })
      this.filterUserDialogShow = false
    },
    handleFilterClear() {
      Object.assign(this.$data, this.$options.data())
      this.allFilterTypes = this.filterTypes
      // 清空地址栏
      filterHelper.clearFilterOption(this)
      this.$emit('select-value', { userIds: 'all', otherFilterTypes: [] })
    }
  }
}
</script>

  <style scoped>
    .filter-option:after {
      content: '';
      clear: both;
      display: table;
    }

    .filter-item {
      float: left;
      margin-left: 10px;
    }

    .filter-value {
      width: 200px;
    }

    .filter-relation {
      width: 100px;
      display: none;
    }

    .down-button {
      float: right;
    }

    .filter-selected {
      clear: both;
      margin: 10px;
      padding: 5px;
      border: 1px solid #ebeef5;
    }

    .selected-tag {
      margin-left: 10px;
    }
  </style>
