<!-- @desc:下拉菜单  @auth:周兴  @time:2022/11/15 15:49 -->
<template>
  <div style="width:100%;min-width: 75px">
    <div ref="select" :id="'select'+id" style="width:100%;position: relative;" class="xm-select-size">
    </div>
    <!--    <div class="more-class" v-if="model!== null && model.length > 0">-->
    <!--      <Icon v-if="showClear && !disabled" type="ios-close-circle" @click.stop="clearAll"/>-->
    <!--    </div>-->
    <div class="all-display-class" v-if="allFlag" :style="{width:(allWidth+ 2) + 'px'}">
      <DkButton class="all-display-btn-class" type="primary" ref="confirm" size="small" @click="handleOpen">
        {{ vm.$t('all') }}&nbsp;
        <Icon type="md-close" size="30px" style="font-size: 15px;margin-top: -1px;cursor: pointer"
              @click.stop="clearAll"/>
      </DkButton>
    </div>
  </div>
</template>

<script>
import '_c/sub/xm-select/xm-select.js'
import uuidv4 from "uuid/v4";

export default {
  name: "xm-select",
  props: {
    value: {
      type: [String, Number, Array],
      default: null
    },
    options: {
      type: Array,
      default: () => []
    },
    labelKey: {
      type: String,
      default: 'label'
    },
    valueKey: {
      type: String,
      default: 'value'
    },
    placeholder: {
      type: String,
      default: null
    },
    disabled: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: true
    },
    // 是否显示全部清除
    showClear: {
      type: Boolean,
      default: false
    },
    // 每项上是否显示清空图标
    showItemClear: {
      type: Boolean,
      default: true
    },
    // 是否显示过滤框
    showFilter: {
      type: Boolean,
      default: true
    },
    // 是否显示工具栏（全选和清空）
    showToolbar: {
      type: Boolean,
      default: false
    },
    // 是否为树形结构
    treeFlag: {
      type: Boolean,
      default: false
    },
    // 是否严格父子级关系（如果是true,只能选择子级节点）
    treeStrict: {
      type: Boolean,
      default: true
    },
    // 选中后关闭（单选才有用）
    clickCloseFlag: {
      type: Boolean,
      default: true
    },
    // 是否显示全部图标
    allFlag: {
      type: Boolean,
      default: false
    },
    allWidth: {
      type: Number,
    }
  },
  data() {
    const vm = window.vm
    return {
      vm: vm,
      select: null,
      id: uuidv4(),
      model: [],
      data: [],
    }
  },
  methods: {
    init() {
      let self = this
      this.select = xmSelect.render({
        el: '#select' + this.id,
        size: 'mini',
        radio: !this.multiple,
        tips: this.placeholder,
        disabled: this.disabled,
        searchTips: '请输入过滤条件',
        language: 'zn',
        filterable: this.showFilter,
        enableKeyboard: true,
        style:{
        },
        theme: {
          color:'#57a3f3'
        },
        toolbar: {
          show: this.showToolbar,
          showIcon: false,
          list: ['ALL', 'CLEAR', {
            name: '刷新', method(data){
              // this.handleRefresh(data);
              self.$emit('refresh');
            }
          }]
        },
        model: {
          label: {
            type: this.showClear ? 'block' : 'text',
            block: {
              //最大显示数量, 0:不限制
              showCount: 0,
              //是否显示删除图标
              showIcon: this.showItemClear,
            }
          }
        },
        data: this.data,
        // 选中关闭，单选才会生效
        clickClose: this.multiple ? false : this.clickCloseFlag,
        // 树形
        tree: {
          show: this.treeFlag,
          showFolderIcon: true,
          expandedKeys: false,
          showLine: false,
          strict: this.treeStrict,
        },
        on: this.onChange,
        hide: this.hideSelect,
        filterMethod: this.filterMethod,
        filterDone: this.filterDone
      })
      this.setValue() // 设置值
    },
    /**
     * @desc   : 刷新塑胶
     * @author : 周兴
     * @date   : 2023/12/27 8:55
     */
    handleRefresh(data){
      this.$emit('refresh');
    },
    /**
     * @desc   : 给数据赋值
     * @author : 周兴
     * @date   : 2022/12/30 15:22
     */
    setData(data) {
      if (!this.treeFlag) {
        data?.map(it => {
          return Object.assign(it, {
            name: it[this.labelKey],
            value: it[this.valueKey],
            initPy: (it[this.labelKey] + '').getInitialPy().toLowerCase(),
            fullPy: (it[this.labelKey] + '').getFullPy()?.toLowerCase(),
          })
        })
        this.data = data;
      } else {
        if (data) {
          data.map(it => {
            return Object.assign(it, {
              name: it[this.labelKey],
              value: it[this.valueKey],
              initPy: (it[this.labelKey] + '').getInitialPy().toLowerCase(),
              fullPy: (it[this.labelKey] + '').getFullPy().toLowerCase(),
            })
          })
          this.data = this.convertToChildren(data);
        }
      }
    },
    /**
     * @desc   : 过滤
     * @author : 周兴
     * @date   : 2022/12/30 15:10
     */
    filterMethod(val, item, index, prop) {
      if (!this.showFilter) return false;
      if (item && item.name) {
        let flag = false;
        let valt = val?.toLowerCase();
        if ((item.name + '').indexOf(val) !== -1) {
          flag = true;
        } else if ((item.initPy + '').indexOf(valt) !== -1) {
          flag = true;
        } else if ((item.fullPy + '').indexOf(valt) !== -1) {
          flag = true;
        }
        // return (item.name + '').indexOf(val) !== -1 || (item.initPy + '').indexOf(valt) !== -1 || (item.fullPy + '').indexOf(valt) !== -1;
        return flag
      }
    },
    /**
     * @desc   : 过滤完成事件
     * @author : 周兴
     * @date   : 2023/2/7 11:35
     */
    filterDone(val, list) {
      if (this.treeFlag) {
        if (val) {
          let keys = []
          let filters = this.options.filter(it => it[this.labelKey].includes(val))
          if (filters && filters.length > 0) {
            filters.forEach(item => {
              let key = this.getExpandKeys(item.parentId)
              if (key && key.length > 0) {
                keys = keys.union(key);
              }
            })
          }
          if (keys && keys.length > 0) {
            this.select.changeExpandedKeys(keys)
          }
        } else {
          this.select.changeExpandedKeys(false)
        }
      }
    }
    ,
    /**
     * @desc   : 获取展开点
     * @author : 周兴
     * @date   : 2023/2/7 10:15
     */
    getExpandKeys(id) {
      let keys = []
      let filters = this.options.filter(it => it[this.valueKey] === id)
      // console.log('t',filters,this.options,id)
      if (filters && filters.length > 0) {
        keys.push(filters[0][this.valueKey])
        if (filters[0].parentId) {
          let tempKeys = this.getExpandKeys(filters[0].parentId)
          if (tempKeys && tempKeys.length > 0) {
            keys = tempKeys.union(keys)
            // console.log('tempKeys',keys,tempKeys)
            return keys;
          }
        } else {
          return keys;
        }
      }
    }
    ,
    /**
     * @desc   : 设置值
     * @author : 周兴
     * @date   : 2022/12/27 11:27
     */
    setValue() {
      let val = this.value
      let _val = val ? (this.multiple ? val : [val]) : []
      this.model = _val;
      this.select.setValue(_val)
    }
    ,
    /**
     * @desc   : 值改变事件
     * @author : 周兴
     * @date   : 2022/12/26 17:26
     */
    onChange(data) {
      let val = data.arr.map(it => it.value);
      let _val = this.multiple ? val : (val.length > 0 ? val[0] : null)
      // 如果是单选，以前有只，现在没有值就不用赋值，避免点击同一条数据就去掉的问题
      if(!this.multiple && !_val  ){
        this.model = _val;
        this.$emit('on-change', _val)
        return;
      }
      this.model = _val;
      this.$emit('input', _val)
      this.$emit('on-change', _val)
      // 如果是单选 那么需要处理
      if (!this.multiple) {
        return data.change.slice(0, 1)
      }
    }
    ,
    /**
     * @desc   : 清空选择项
     * @author : 周兴
     * @date   : 2022/11/7 11:52
     */
    clearAll() {
      this.model = [];
      this.$emit('clearAll')
    }
    ,
    /**
     * @desc   : desc
     * @author : 周兴
     * @date   : 2023/9/12 9:19
     */
    handleOpen() {
      this.openNow();
    },
    /**
     * @desc   : 打开select
     * @author : 周兴
     * @date   : 2022/12/26 17:03
     */
    open() {
      setTimeout(() => {
        this.select.opened();
      }, 500)
    }
    ,
    /**
     * @desc   : 打开select
     * @author : 周兴
     * @date   : 2022/12/26 17:03
     */
    openNow() {
      setTimeout(() => {
        this.select.opened();
      }, 10)
    },
    /**
     * @desc   : 关闭select
     * @author : 周兴
     * @date   : 2022/12/26 17:03
     */
    close() {
      this.select.closed();
    },
    /**
     * @desc   : 隐藏下拉框
     * @author : 周兴
     * @date   : 2022/12/27 11:13
     */
    hideSelect(e) {
      this.$emit('close-select', e)
    },
    changeAll() {
      setTimeout(() => {
        let list = this.$refs.select.firstChild.childNodes[2].firstChild.firstChild.childNodes
        if (list && list.length > 0) {
          list.forEach((it, index) => {
            // if (index === 0) {
            //   it.firstChild.innerText = '全部'
            // } else {
            //   it.style.display = 'none'
            // }
            it.style.display = 'none'
          })
        }
      }, 500)
    },
  },
  watch: {
    options(n, o) {
      this.setData(n);  // 设置数据
      this.init()
    },
    labelKey() {
      this.init()
    },
    valueKey() {
      this.init()
    },
    placeholder() {
      this.init()
    },
    disabled() {
      this.init()
    },
    value(n, o) {
      this.init()
    },
    multiple() {
      this.init()
    }
  },
  beforeDestroy() {
    this.select = null;
  },
  mounted() {
    // this.changeAll();
  },
  created() {
    this.setData(this.options);  // 设置数据
    this.$nextTick(() => {
      this.init()
      // 增加全部
      // if(this.multiple){
      //   let allItem = {}
      //   allItem[this.labelKey] = '全部'
      //   allItem[this.valueKey] = -1;
      //   this.options.unshift(allItem);
      //   this.model.push(-1);
      // }
    })
  }
}
</script>

<style scoped>
/deep/ .xm-tips {
  color: #c5c8ce;
  display: block !important;
  overflow: hidden !important;
  padding: 0 7px !important;
}

.more-class {
  cursor: pointer;
  width: 18px;
  position: absolute;
  display: flex;
  top: 5px;
  right: 25px;
  align-items: center;
  justify-content: center;
  height: 18px;
  color: #a0a5ac;
  z-index: 33;
}

.xm-select {
  border: 1px solid red !important;
}

/deep/ .xm-search .xm-iconfont {
  font-family: "iconfont" !important;
  font-size: 14px !important;
}

/deep/ .xm-icon-sousuo:before {
  content: "\e63c" !important;
}


/deep/ .scroll-body {
  max-width: 400px !important;
}

.all-display-class {
  height: calc(100% - 4px);
  top: 3px;
  margin-left: 2px;
  background: #fff;
  position: absolute;
  z-index: 99;
  display: flex;
  align-items: center;
}

.all-display-btn-class {
  height: 18px;
  line-height: 18px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 1px 8px;
  padding-left: 3px;
  padding-right: 3px;
}



/deep/xm-select:focus{
  border-color: #57a3f3 !important;
  box-shadow: 0 0 0 2px rgba(45, 140, 240, 0.2);
}

/deep/xm-select:hover{
  border-color: #57a3f3 !important;
}


</style>
