<template>
  <div class="filter-user">
    <div class="filter-option">
      <el-select class="filter-item"
                 v-model="filterType"
                 placeholder="Filter type"
                 @change="handleFilterTypeChange"
      ><!-- 筛选类型 -->
        <el-option v-for="(item,key) in allFilterTypes" :key="key" :label="item.name" :value="key"></el-option>
      </el-select>
      <el-select class="filter-item"
                 v-model="filterSymbol"
                 placeholder="Filter mode"
      ><!-- 筛选方式 -->
        <el-option v-for="(item,key) in filterSymbols" :key="key" :label="item" :value="key"></el-option>
      </el-select>
      <template
          v-if="filterType !== '' && allFilterTypes[filterType].hasOwnProperty('other') && allFilterTypes[filterType].other === 'date'">
        <el-date-picker
            class="filter-item"
            v-model="filterValue"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="Select date"><!-- 选择日期 -->
        </el-date-picker>
      </template>
      <template
          v-else-if="filterType !== '' && allFilterTypes[filterType].hasOwnProperty('other') && allFilterTypes[filterType].other === 'month'">
        <el-date-picker
            class="filter-item"
            v-model="filterValue"
            value-format="yyyyMM"
            type="month"
            placeholder="Select month"><!-- 选择月份 -->
        </el-date-picker>
      </template>
      <template
          v-else-if="filterType !== '' && allFilterTypes[filterType].hasOwnProperty('other') && allFilterTypes[filterType].other === 'area'">
        <el-cascader
            class="filter-item"
            :options="regionData" :props="{ checkStrictly: true }"
            v-model="filterAreaValue">
        </el-cascader>
      </template>
      <template
          v-else-if="filterType !== '' && allFilterTypes[filterType].hasOwnProperty('other') && allFilterTypes[filterType].other === 'select'">
        <el-select class="filter-item"
                   v-model="filterValue"
                   :placeholder="`Please select ${allFilterTypes[filterType].name}`"
        ><!-- 请选择 -->
          <el-option v-for="(item,key) in allFilterTypes[filterType].selectData" :key="key" :label="item.name"
                     :value="item.id"></el-option>
        </el-select>
      </template>
      <template
          v-else-if="filterType !== '' && allFilterTypes[filterType].hasOwnProperty('other') && filterCustomType.hasOwnProperty(allFilterTypes[filterType].other)">
        <el-select class="filter-item" v-model="filterValue" :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-option>
        </el-select>
      </template>
      <template v-else>
        <el-input class="filter-item filter-value" v-model="filterValue" placeholder="Please enter the content"><!-- 请输入内容 --></el-input>
      </template>
      <el-select class="filter-item filter-relation"
                 v-model="filterRelation"
                 placeholder="关系"
      >
        <el-option v-for="(item,key) in filterRelations" :key="key" :label="item" :value="key"></el-option>
      </el-select>
      <el-button class="filter-item" icon="el-icon-plus" @click="handleOptionPlus"></el-button>
      <el-button class="filter-item" type="primary" @click="handleFilterUser" icon="el-icon-search">{{filterBtnName}}</el-button>
      <el-button class="filter-item" type="" @click="handleFilterClear">Reset<!-- 重置 --></el-button>
      <el-button class="down-button" type="text"><i class="el-icon-arrow-down"></i></el-button>
    </div>
    <div class="filter-selected" v-show="filterSelected.length > 0">
      <el-tag class="selected-tag" v-for="(item,key) in filterSelected" :key="key" closable
              @close="handleCloseTag(key)">{{item.filterTypeName}} {{item.filterSymbolName}} {{item.filterName}}
      </el-tag>
    </div>
    <el-dialog title="会员筛选" :visible.sync="filterUserDialogShow" width="80%">
      <el-table :data="tableData" stripe style="width: 100%;" @selection-change="handleSelectionChange"
                v-loading="loading">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="会员编号">
          <template slot-scope="scope">
            {{scope.row.USER_NAME}}
          </template>
        </el-table-column>
        <el-table-column label="姓名">
          <template slot-scope="scope">
            {{scope.row.REAL_NAME}}
          </template>
        </el-table-column>
        <el-table-column label="证件号码" width="180">
          <template slot-scope="scope">
            {{scope.row.ID_CARD}}
          </template>
        </el-table-column>
        <el-table-column label="手机号码">
          <template slot-scope="scope">
            {{scope.row.MOBILE}}
          </template>
        </el-table-column>
        <el-table-column label="会员级别">
          <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="聘级">
          <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" @click="handleSelectValue(false)" :disabled="multipleSelectionUserId == undefined || multipleSelectionUserId.length <= 0?true:false">确认筛选</el-button>
        <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange"></pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import network from '@/utils/network'
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: '会员编号'},
          'REAL_NAME': {isUserTable: true, name: '会员姓名'},
          'ID_CARD': {isUserTable: true, name: '身份证'},
          'MOBILE': {isUserTable: true, name: '手机号'},
          'CREATED_AT': {isUserTable: true, name: '加入时间', other: 'date'}
        }
      }
    },
    filterBtnName: {
      type: String,
      default () {
        return 'Select' // 筛选
      }
    }
  },
  data () {
    return {
      loading: false,
      filterUserDialogShow: false,
      tableData: [],
      currentPage: 1,
      totalPages: 1,
      totalCount: 1,
      pageSize: 20,
      filterCustomType: {
        decLevel: {
          placeholder: 'Select entry level', // 请选择报单级别
          labelField: 'LEVEL_NAME',
          valueField: 'ID',
          values: baseInfo.decLevels()
        },
        empLevel: {
          placeholder: 'Select Employee Level', // 请选择聘级
          labelField: 'LEVEL_NAME',
          valueField: 'ID',
          values: baseInfo.empLevels()
        },
        crownLevel: {
          placeholder: 'Select Crown Level', // 请选择聘级
          labelField: 'LEVEL_NAME',
          valueField: 'ID',
          values: baseInfo.crownLevels()
        },
        decRole: {
          placeholder: 'Select Stockist Level',
          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: 'Select Yes or No',
          labelField: 'label',
          valueField: 'value',
          values: {
            1: {label: 'Yes', value: 1},
            0: {label: 'No', 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: {
        '=': 'Is equal to', // 等于
        'like': 'Is including', // 包含
        '<>': 'Is not', // 不等于
        'notLike': 'not Is including ', // 不包含
        '>': 'Is greater than', // 大于
        '>=': 'Is greater than or equal to', // 大于等于
        '<': 'Is smaller than', // 小于
        '<=': 'Is smaller than or equal to'// 小于等于
      },
      filterRelation: 'and',
      filterRelations: {
        'and': '并且',
        '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 (let 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
        network.getData(`user/filter-user`, {kw: query}).then(response => {
          this.selectData = response
          this.loading = false
        }).catch(error => {
          console.log(error)
          this.loading = false
        })
      }
    },
    handleOptionPlus () {
      if (this.filterType === '' || this.filterSymbol === '' || (this.filterValue === '' && this.filterAreaValue === [])) {
        this.$message({
          message: 'please complete the selection', // 请填写完整筛选内容
          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 = []
          let _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: '地区仅限于"等于"的筛选方式',
              type: 'warning'
            })
            return false
          }
          this.filterValue = this.filterAreaValue.join(',')
          valueName = ''
          for (let i in this.regionData) {
            if (this.regionData[i].value === this.filterAreaValue[0]) {
              valueName += this.regionData[i].label + ','
              for (let j in this.regionData[i].children) {
                if (this.regionData[i].children[j].value === this.filterAreaValue[1]) {
                  valueName += this.regionData[i].children[j].label + ','
                  for (let 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)) {
          let allCustomData = this.filterCustomType[this.allFilterTypes[this.filterType].other].values
          let 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 () {
      if (this.filterSelected.length > 0) {
        this.loading = true
        this.filterRequest = {}
        for (let 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}`
            }
            let 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) {
      network.getPageData(this, 'user/filter-user', page, pageSize, request, response => {
        this.filterUserDialogShow = true
      })
    },
    handleSelectValue (isAll = false) {
      let otherFilterTypes = []
      for (let 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>
