<template>
  <div class="selector-content" v-if="selectorType === 'card'" key="s-content">
    <div class="search-container">
      <el-input v-model.trim="searchContent" placeholder="搜索" prefix-icon="el-icon-search"></el-input>
    </div>
    <div class="select-list scrollbar" ref="selectList">
      <div
        v-for="(item, key) in cateListMap"
        :key="key"
        class="select-group-container"
        :class="{
          global: key === '#'
        }"
      >
        <div class="index-anchor" :id="key" :data-index="key" v-if="key !== '#'">{{ key }}</div>
        <div class="select-group">
          <button v-for="(cate, i) in item" :key="999-i"
            class="j-button-item"
            :class="{
              active: cate.selected,
              [cate.id]: true
            }"
            @click="changeCateState($event,cate)">{{ cate.name }}
            </button>
            <button
              :class="{
                active: notClass.selected,
                [notClass.id]: true
              }"
              class="j-button-item"
              v-if="item[0].name === '全部'"
              @click="changeCateState($event,notClass)"
            >匹配未分类行业</button>
            <img class="icon-quesion" src="@/assets/images/icon/question.png" v-if="item[0].name === '全部'" @click="dialogTip = true" />
        </div>
      </div>
    </div>
    <el-dialog
      custom-class="buyer-dialog"
      title="匹配未分类行业"
      :visible.sync="dialogTip"
      width="24%"
      center
      :show-close="false"
      append-to-body
      >
      <p style="font-size:14px;color:#1D1D1D;line-height:22px;">每条信息的采购单位行业属性由机器自动识别，会存在少数无法识别进行分类的情况。</p>
      <p style="margin-top:4px;font-size:14px;color:#686868;line-height:22px;">注：选择全部行业时，未分类行业默认被选中，关闭无效</p>
      <span slot="footer" class="dialog-footer">
        <el-button style="background: #2cb7ca;border-radius: 6px;border:0;" type="primary" @click="dialogTip = false">我知道了</el-button>
      </span>
    </el-dialog>
  </div>
  <div class="selector-content" :class="{ 'no-more': !showMore }" v-else-if="selectorType === 'line'" key="s-content">
    <span class="action-button show-more" @click="showMore = !showMore">
      <span class="action-text">{{ showMore ? '收起' : '更多' }}</span>
      <span class="el-icon-arrow-down" :class="showMore ? 'rotate180' : ''"></span>
    </span>
    <div
      v-for="(item, key) in cateListMap"
      :key="key"
      class="select-group-container"
    >
      <!-- <div class="index-anchor" :id="key" :data-index="key" v-if="key !== '#'">{{ key }}</div> -->
      <div class="select-group">
        <button v-for="(cate, i) in item" :key="999-i"
          class="j-button-item bgc"
          :class="{
            active: cate.selected,
            [cate.id]: true,
            all: cate.name === '全部'
          }"
          @click="changeCateState($event,cate)">{{ cate.name }}</button>
      </div>
    </div>
  </div>
</template>

<script>
import { Input, Dialog, Button } from 'element-ui'
import { cateListMapExp } from '@/assets/js/selector.js'
import { debounce, getRandomString } from '@/utils/'
export default {
  name: 'buyerclass-selector-content',
  components: {
    [Input.name]: Input,
    [Dialog.name]: Dialog,
    [Button.name]: Button
  },
  props: {
    selectorType: {
      type: String,
      default: 'card' // card/line
    },
    initCate: {
      type: Array,
      default () {
        return [] // '财政', '传媒', '城管', '出版广电'
      }
    }
  },
  data () {
    return {
      searchContent: '',
      // 原始数据
      cateListMapExp,
      // 页面中循环的数据
      cateListMap: {},
      cateExp: {
        name: '全部',
        selected: false,
        level: 0,
        id: ''
      },
      // indexBar数据
      indexList: [],
      showMore: false,
      dialogTip: false,
      notClass: {
        id: 'bc-ppwfl',
        level: 1,
        name: '匹配未分类',
        selected: true
      }
    }
  },
  watch: {
    initCate (newVal, oldVal) {
      // console.log(...arguments)
      this.setCateState(newVal)
    },
    searchContent: debounce(function (newVal, oldVal) {
      const search = newVal
      const index = this.getIndexWithString(search)
      if (index) {
        this.$nextTick(() => {
          const wrapper = document.querySelector('.buyerclass-selector.s-card')
          this.$refs.selectList.scrollTop = wrapper.querySelector(`[data-index=${index}]`).offsetTop
        })
      }
    }, 300)
  },
  created () {
    this.initCateMap()
    this.setCateState(this.initCate)
  },
  methods: {
    // 初始化数据
    initCateMap () {
      const cateListMap = {}
      for (const key in this.cateListMapExp) {
        this.indexList.push(key)
        const cateArr = []
        this.cateListMapExp[key].forEach(cateName => {
          const cateExp = JSON.parse(JSON.stringify(this.cateExp))
          cateExp.name = cateName
          cateExp.id = `bc-${getRandomString(8).toLowerCase()}`
          if (cateName !== this.cateExp.name) {
            cateExp.level = 1
          } else {
            cateExp.level = 0
            cateExp.selected = true
          }
          cateArr.push(cateExp)
        })
        cateListMap[key] = cateArr
      }

      for (const k in cateListMap) {
        this.$set(this.cateListMap, k, cateListMap[k])
      }
    },
    changeCateState (e, item) {
      // 循环所有数据，判断并改变状态
      switch (item.level) {
        case 0: {
          this.setCateState()
          break
        }
        case 1: {
          this.cateListMap['#'][0].selected = false
          item.selected = !item.selected
          break
        }
        default: {
          console.log('未知level')
        }
      }

      if (item.level !== 0) {
        const allSelected = this.checkAllSelectedState()
        if (allSelected.allSelected || allSelected.allNotSelected) {
          this.setCateState()
        }
      }

      if (this.selectorType === 'line') {
        this.onChange()
      }
    },
    // 检查是否全部选中了/全部不选中
    checkAllSelectedState () {
      const allSelectedArr = []
      for (const key in this.cateListMap) {
        // 跳过全部进行筛选
        if (key === '#') continue
        this.cateListMap[key].forEach(item => {
          allSelectedArr.push(item.selected)
        })
      }

      return {
        // 找不到false，就说明全部被选中
        allSelected: allSelectedArr.indexOf(false) === -1,
        // 找不到true，就说明没有一个被选中
        allNotSelected: allSelectedArr.indexOf(true) === -1
      }
    },
    /**
     * 初始化页面选中状态
     * @param { Array | undefined } data 要恢复的数据
     */
    setCateState (data) {
      // 设置全部按钮
      if (!data || data.length === 0) {
        // 其他全部设置不选中，全部按钮设置选中
        for (const key in this.cateListMap) {
          this.cateListMap[key].forEach(item => {
            item.selected = false
          })
        }

        this.cateListMap['#'][0].selected = true
      } else {
        this.setCateState()
        this.cateListMap['#'][0].selected = false

        if (Array.isArray(data)) {
          for (const key in this.cateListMap) {
            this.cateListMap[key].forEach(function (item) {
              if (data.indexOf(item.name) !== -1) {
                item.selected = true
              }
            })
          }
        } else {
          console.error('参数必须为undefined或数组')
        }
      }
    },
    // 获取选中的数据
    getSelected () {
      const data = []
      for (const key in this.cateListMap) {
        // 跳过全部进行查找
        if (key === '#') continue
        this.cateListMap[key].forEach(item => {
          if (item.selected) {
            data.push(item.name)
          }
        })
      }
      return data
    },
    getIndexWithString (s = '') {
      if (!s) return
      let giveMyIndex = ''
      for (const key in this.cateListMapExp) {
        const wowFindIt = this.cateListMapExp[key].find(item => {
          return item.includes(s)
        })
        if (wowFindIt) {
          giveMyIndex = key
          break
        }
      }
      return giveMyIndex
    },
    onChange () {
      const selected = this.getSelected()
      this.$emit('onChange', selected)
    }
  }
}
</script>

<style lang="scss" scoped>
  .s-card {
    font-size: 14px;
    .select-group-container {
      border-bottom: 1px solid rgba(0,0,0,.05);
      .select-group {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        margin: 0 16px;
      }
    }
    .icon-quesion{
      width: 18px;
      height: 18px;
      margin-left: 2px;
      cursor: pointer;
    }
  }

  .s-line {
    .selector-content {
      position: relative;
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      padding-right: 45px;
      &.no-more {
        height: 38px;
        overflow: hidden;
      }
    }
    .select-group-container {
      display: flex;
      flex-wrap: wrap;
      .select-group {
        display: flex;
        flex-wrap: wrap;
      }
    }
  }
</style>
