<template>
  <!-- <div class="syswin-searchbar" v-clickoutside="handleClickOutside"> -->
  <div class="syswin-searchbar" v-clickoutside="handleClickOutside">
    <div class="syswin-searchbar-container">
      <template v-if="$slots.searchInput">
        <slot name="searchInput"></slot>
      </template>
      <el-input v-else class="syswin-searchbar-container__input" v-model="keyword" :placeholder="placeholder" clearable size="small" @clear="handleClearInput">
        <slot slot="prepend" name="prepend"></slot>
        <slot slot="suffix" name="suffix"></slot>
      </el-input>
      <el-button v-if="showFilter" type="text" size="mini" class="syswin-searchbar-container__filter" @click="handleToggleFilterList">
        {{ shrinkFilterList ? '收起筛选' : '更多筛选' }}
        <i class="el-icon-caret-bottom" :class="{ 'is-rotate-180': shrinkFilterList }"></i>
      </el-button>
      <el-button type="primary" size="mini" class="syswin-searchbar-container__search" :class="{ 'is-margin-left-16': !showFilter }" @click="handleSearch()">
        {{ searchButtonText }}
      </el-button>
      <el-button v-if="showFilter" size="mini" class="syswin-searchbar-container__reset" @click="handleReset">
        {{ resetButtonText }}
      </el-button>
      <slot name="behind"></slot>
      <div class="syswin-searchbar-container__listBtns">
        <slot name="listBtns"></slot>
      </div>
    </div>
    <transition name="fade">
      <div class="syswin-searchbar-list" v-if="shrinkFilterList">
        <div class="syswin-searchbar-list__wrap">
          <slot></slot>

          <!-- 没有更多搜索 -->
          <template v-if="currentSearchList.length <= maxConditionLength + 1">
            <div class="syswin-filter-item" v-for="(ele, index) in currentSearchList" :key="ele.id">
              <h5 class="syswin-filter-item__title">
                {{ ele.name }}
              </h5>
              <ul class="syswin-filter-item__content">
                <li class="syswin-filter-item__li" v-for="(item, idx) in ele.itemList" :key="item.id">
                  <template v-if="item.type === 'text'">
                    <span
                      class="syswin-filter-item__span"
                      :class="{
                        'is-active': item.isActive
                      }"
                      @click="handleClick(item, idx, index)"
                      >{{ item.name }}</span
                    >
                  </template>
                  <template v-else-if="item.type === 'daterange'">
                    <span class="syswin-filter-item__name" v-if="item.name && !item.hideName">{{ item.name }}</span>
                    <el-date-picker
                      type="daterange"
                      v-model="item.value"
                      size="small"
                      :picker-options="item.pickerOptions && pickerOptions"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      :editable="false"
                      :unlink-panels="true"
                      value-format="timestamp"
                      @change="handleChangeDateragne(idx, index)"
                    >
                    </el-date-picker>
                  </template>
                  <template v-else-if="item.type === 'input'">
                    <span class="syswin-filter-item__name" v-if="item.name && !item.hideName">{{ item.name }}</span>
                    <el-input v-model.trim="item.value" :placeholder="`请输入${item.name}`"></el-input>
                  </template>
                  <template v-else-if="item.type === 'monthrange'">
                    <span class="syswin-filter-item__name" v-if="item.name && !item.hideName">{{ item.name }}</span>
                    <el-date-picker
                      type="monthrange"
                      v-model="item.value"
                      size="small"
                      range-separator="至"
                      start-placeholder="开始月份"
                      end-placeholder="结束月份"
                      :editable="false"
                      :unlink-panels="true"
                      value-format="timestamp"
                      @change="handleChangeDateragne(idx, index)"
                    >
                    </el-date-picker>
                  </template>
                  <template v-else-if="item.type === 'month' || item.type === 'year'">
                    <span class="syswin-filter-item__name" v-if="item.name && !item.hideName">{{ item.name }}</span>
                    <el-date-picker
                      :type="item.type"
                      v-model="item.value"
                      size="small"
                      :placeholder="`选择${item.type === 'month' ? '月' : '年'}`"
                      :value-format="`${item.type === 'month' ? 'yyyy-MM' : 'yyyy'}`"
                      @change="handleChangeDateragne(idx, index)"
                    >
                    </el-date-picker>
                  </template>
                  <template v-else-if="item.type === 'datetimerange'">
                    <span class="syswin-filter-item__name" v-if="item.name && !item.hideName">{{ item.name }}</span>
                    <el-date-picker
                      type="datetimerange"
                      v-model="item.value"
                      size="small"
                      :picker-options="item.pickerOptions && pickerOptions"
                      :format="item.format ? item.format : 'yyyy-MM-dd HH:mm:ss'"
                      :default-time="['00:00:00', '23:59:59']"
                      :unlink-panels="true"
                      prefix-icon="el-icon-date"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      value-format="timestamp"
                      @change="handleChangeDateragne(idx, index)"
                    >
                    </el-date-picker>
                  </template>
                  <template v-else-if="item.type === 'select'">
                    <span class="syswin-filter-item__name" v-if="item.name && !item.hideName">{{ item.name }}</span>
                    <el-select
                      size="small"
                      :multiple="!!item.multiple"
                      :filterable="item.filterable"
                      collapse-tags
                      clearable
                      v-model="item.value"
                      :placeholder="`请选择${item.name}`"
                      :style="{
                        width: item.width ? item.width : '200px'
                      }"
                      @change="handleChangeDateragne(idx, index)"
                    >
                      <el-option v-for="opt in item.options" :key="opt.id" :label="opt.label" :value="opt.value"></el-option>
                    </el-select>
                  </template>
                  <template v-else-if="item.type === 'cascade'">
                    <span class="syswin-filter-item__name" v-if="item.name && !item.hideName">{{ item.name }}</span>
                    <el-cascader size="small" v-model="item.value" :placeholder="`请选择${item.name}`" :style="{
                        width: item.width ? item.width : '200px'
                      }" :options="item.options" :props="{ multiple: !!item.multiple, checkStrictly: !!item.checkStrictly }" collapse-tags clearable @change="handleChangeDateragne(idx, index)"></el-cascader>
                  </template>
                  <template v-else-if="item.type === 'slot'">
                    <slot :name="item.slot" :item="item">内容为空</slot>
                  </template>
                </li>
              </ul>
            </div>
          </template>

          <!-- 含有更多搜索 -->
          <template v-else>
            <div class="syswin-filter-item" v-for="(ele, index) in currentSearchList.slice(0, maxConditionLength)" :key="ele.id">
              <h5 class="syswin-filter-item__title">
                {{ ele.name }}
              </h5>
              <ul class="syswin-filter-item__content">
                <li class="syswin-filter-item__li" v-for="(item, idx) in ele.itemList" :key="item.id">
                  <template v-if="item.type === 'text'">
                    <span
                      class="syswin-filter-item__span"
                      :class="{
                        'is-active': item.isActive
                      }"
                      @click="handleClick(item, idx, index)"
                      >{{ item.name }}</span
                    >
                  </template>
                  <template v-else-if="item.type === 'daterange'">
                    <span class="syswin-filter-item__name" v-if="item.name">{{ item.name }}</span>
                    <el-date-picker
                      type="daterange"
                      v-model="item.value"
                      size="small"
                      :picker-options="item.pickerOptions && pickerOptions"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      :editable="false"
                      :unlink-panels="true"
                      value-format="timestamp"
                      @change="handleChangeDateragne(idx, index)"
                    >
                    </el-date-picker>
                  </template>
                  <template v-else-if="item.type === 'monthrange'">
                    <span class="syswin-filter-item__name" v-if="item.name">{{ item.name }}</span>
                    <el-date-picker
                      type="monthrange"
                      v-model="item.value"
                      size="small"
                      range-separator="至"
                      start-placeholder="开始月份"
                      end-placeholder="结束月份"
                      :editable="false"
                      :unlink-panels="true"
                      value-format="timestamp"
                      @change="handleChangeDateragne(idx, index)"
                    >
                    </el-date-picker>
                  </template>
                  <template v-else-if="item.type === 'month' || item.type === 'year'">
                    <span class="syswin-filter-item__name" v-if="item.name && !item.hideName">{{ item.name }}</span>
                    <el-date-picker
                      :type="item.type"
                      v-model="item.value"
                      size="small"
                      :placeholder="`选择${item.type === 'month' ? '月' : '年'}`"
                      :value-format="`${item.type === 'month' ? 'yyyy-MM' : 'yyyy'}`"
                      @change="handleChangeDateragne(idx, index)"
                    >
                    </el-date-picker>
                  </template>
                  <template v-else-if="item.type === 'datetimerange'">
                    <span class="syswin-filter-item__name" v-if="item.name">{{ item.name }}</span>
                    <el-date-picker
                      type="datetimerange"
                      v-model="item.value"
                      size="small"
                      :picker-options="item.pickerOptions && pickerOptions"
                      :format="item.format ? item.format : 'yyyy-MM-dd HH:mm:ss'"
                      :default-time="['00:00:00', '23:59:59']"
                      :unlink-panels="true"
                      prefix-icon="el-icon-date"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      value-format="timestamp"
                      @change="handleChangeDateragne(idx, index)"
                    >
                    </el-date-picker>
                  </template>
                  <template v-else-if="item.type === 'select'">
                    <span class="syswin-filter-item__name" v-if="item.name && !item.hideName">{{ item.name }}</span>
                    <el-select
                      size="small"
                      :multiple="!!item.multiple"
                      :filterable="item.filterable"
                      collapse-tags
                      clearable
                      v-model="item.value"
                      :placeholder="`请选择${item.name}`"
                      :style="{
                        width: item.width ? item.width : '200px'
                      }"
                      @change="handleChangeDateragne(idx, index)"
                    >
                      <el-option v-for="opt in item.options" :key="opt.id" :label="opt.label" :value="opt.value"></el-option>
                    </el-select>
                  </template>
                  <template v-else-if="item.type === 'cascade'">
                    <span class="syswin-filter-item__name" v-if="item.name && !item.hideName">{{ item.name }}</span>
                    <el-cascader size="small" v-model="item.value" :placeholder="`请选择${item.name}`" :style="{
                        width: item.width ? item.width : '200px'
                      }" :options="item.options" :props="{ multiple: !!item.multiple, checkStrictly: !!item.checkStrictly }" collapse-tags clearable @change="handleChangeDateragne(idx, index)"></el-cascader>
                  </template>
                  <template v-else-if="item.type === 'slot'">
                    <slot :name="item.slot" :item="item">内容为空</slot>
                  </template>
                </li>
              </ul>
            </div>
            <div class="syswin-filter-item" v-if="currentSearchList.length > maxConditionLength">
              <h5 class="syswin-filter-item__title">更多搜索</h5>
              <ul class="syswin-filter-item__content">
                <li class="syswin-filter-item__li" v-for="(ele, index) in currentSearchList.slice(maxConditionLength)" :key="ele.id">
                  <h6 class="syswin-filter-item__subTitle">
                    {{ ele.name }}
                  </h6>
                  <ul class="syswin-filter-item__subContent">
                    <li class="syswin-filter-item__subLi" v-for="(item, idx) in ele.itemList" :key="item.id">
                      <template v-if="item.type === 'text'">
                        <span
                          class="syswin-filter-item__span"
                          :class="{
                            'is-active': item.isActive
                          }"
                          @click="handleClick(item, idx, index + maxConditionLength)"
                          >{{ item.name }}</span
                        >
                      </template>
                      <template v-else-if="item.type === 'daterange'">
                        <span class="syswin-filter-item__name" v-if="item.name">{{ item.name }}</span>
                        <el-date-picker
                          type="daterange"
                          v-model="item.value"
                          size="small"
                          :picker-options="item.pickerOptions && pickerOptions"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          :editable="false"
                          :unlink-panels="true"
                          value-format="timestamp"
                          @change="handleChangeDateragne(idx, index + maxConditionLength)"
                        >
                        </el-date-picker>
                      </template>
                      <template v-else-if="item.type === 'monthrange'">
                        <span class="syswin-filter-item__name" v-if="item.name">{{ item.name }}</span>
                        <el-date-picker
                          type="monthrange"
                          v-model="item.value"
                          size="small"
                          range-separator="至"
                          start-placeholder="开始月份"
                          end-placeholder="结束月份"
                          :editable="false"
                          :unlink-panels="true"
                          value-format="timestamp"
                          @change="handleChangeDateragne(idx, index + maxConditionLength)"
                        >
                        </el-date-picker>
                      </template>
                      <template v-else-if="item.type === 'datetimerange'">
                        <span class="syswin-filter-item__name" v-if="item.name">{{ item.name }}</span>
                        <el-date-picker
                          type="datetimerange"
                          v-model="item.value"
                          size="small"
                          :picker-options="item.pickerOptions && pickerOptions"
                          :format="item.format ? item.format : 'yyyy-MM-dd HH:mm:ss'"
                          :default-time="['00:00:00', '23:59:59']"
                          :unlink-panels="true"
                          prefix-icon="el-icon-date"
                          range-separator="至"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          value-format="timestamp"
                          @change="handleChangeDateragne(idx, index + maxConditionLength)"
                        >
                        </el-date-picker>
                      </template>
                      <template v-else-if="item.type === 'select'">
                        <span class="syswin-filter-item__name" v-if="item.name">{{ item.name }}</span>
                        <el-select
                          size="small"
                          :multiple="!!item.multiple"
                          :filterable="item.filterable"
                          collapse-tags
                          clearable
                          v-model="item.value"
                          :placeholder="`请选择${item.name}`"
                          :style="{
                            width: item.width ? item.width : '200px'
                          }"
                          @change="handleChangeDateragne(idx, index + maxConditionLength)"
                        >
                          <el-option v-for="opt in item.options" :key="opt.id" :label="opt.label" :value="opt.value"></el-option>
                        </el-select>
                      </template>
                      <template v-else-if="item.type === 'cascade'">
                        <span class="syswin-filter-item__name" v-if="item.name && !item.hideName">{{ item.name }}</span>
                        <el-cascader size="small" v-model="item.value" :placeholder="`请选择${item.name}`" :style="{
                            width: item.width ? item.width : '200px'
                          }" :options="item.options" :props="{ multiple: !!item.multiple, checkStrictly: !!item.checkStrictly }" collapse-tags clearable @change="handleChangeDateragne(idx, index + maxConditionLength)"></el-cascader>
                      </template>
                      <template v-else-if="item.type === 'slot'">
                        <slot :name="item.slot" :item="item">内容为空</slot>
                      </template>
                    </li>
                  </ul>
                </li>
              </ul>
            </div>
          </template>
        </div>
        <!-- <div class="syswin-searchbar-list__footer" :class="{ 'align-right': saveToLocalPosition === 'right' }" v-if="saveToLocal">
                    <el-button size="small" v-if="saveToLocalPosition === 'left'" class="syswin-footer__save" @click="handleSave">保存</el-button>
                    <el-select size="small" class="syswin-footer__condition" v-model="conditionValue" @change="handleChangeCondition">
                        <el-option v-for="(item, index) in conditionList" :key="index" :label="item.label" :value="item.value">
                            <span class="syswin-footer__label">{{ item.label }}</span>
                            <i class="syswin-footer__edit el-icon-edit-outline" @click.stop="handleEditCondition(index)"></i>
                            <i class="syswin-footer__delete el-icon-delete" @click.stop="handleDeleteCondition(index)"></i>
                        </el-option>
                    </el-select>
                    <el-button size="small" v-if="saveToLocalPosition === 'right'" class="syswin-footer__save" @click="handleSave">保存</el-button>
                </div> -->
        <save-local
          v-if="saveToLocal"
          @handleSave="handleSave"
          @handleChangeCondition="handleChangeCondition"
          @handleEditCondition="handleEditCondition"
          @handleDeleteCondition="handleDeleteCondition"
          @handleConfirmCondition="handleConfirmCondition"
          :conditionList="conditionList"
          v-model="currentData"
          :curConditionValue="conditionValue"
        />
      </div>
    </transition>
    <div class="search-condition-list" v-if="tagList.length && !customTagList">
      <el-tag v-for="tag in tagList" class="tags" :key="`${tag.pId}_${tag.id}`" size="small" closable @close="handleTagClose(tag)">
        {{ tag.pName }}: {{ tag.name }}
      </el-tag>
      <el-tag size="small" class="tags clearall" v-if="tagList.length > 1" @click="handleClearAllTags">清除所有</el-tag>
    </div>
  </div>
</template>
<script>
// import Clickoutside from 'element-ui/src/utils/clickoutside'
import _ from 'lodash'
import moment from 'moment'
import saveLocal from './save-local'

function deepCopyFunction(arr1, arr2) {
  for (let i = 0; i < arr1.length; i++) {
    const father1 = arr1[i]
    const father2 = arr2[i]
    for (let j = 0; j < father1.itemList.length; j++) {
      const item1 = father1.itemList[j]
      const item2 = father2.itemList[j]
      if (item1.type === 'slot') {
        item1.getValue = item2.getValue
        item1.setValue = item2.setValue
      }
    }
  }
}
function findTree(allData, fn) {
  function loopFn(arr, pNode) {
    for (let i = 0; i < arr.length; i++) {
      // debugger
      let result = null
      const item = arr[i]
      item.nodes = [item]
      if (pNode) {
        item.nodes = [...pNode.nodes, item]
      }
      // findTree(item.options, tItem => tItem.value === lastValue)
      const flag = fn(item)
      if (flag) {
        result = item
        if (result) return result
      }
      if (item.children) {
        result = loopFn(item.children, item)
      }
      if (result) return result
    }
  }
  const res = loopFn(allData)
  return res
}

export default {
  name: 'SySearchbar',
  components: {
    saveLocal
  },
  // directives: { Clickoutside },
  directives: {
    Clickoutside: {
      // 初始化指令
      bind(el, binding, vnode) {
        function clickHandler(e) {
          // 这里判断点击的元素是否是本身，是本身，则返回
          if (el.contains(e.target)) {
            const btnsBox = el.querySelector('.syswin-searchbar-container__listBtns') // 点击右侧的按钮时也要隐藏所有条件面板
            if (!btnsBox.contains(e.target)) {
              return false
            }
          }
          // 判断指令中是否绑定了函数
          if (binding.expression) {
            // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
            binding.value(e)
          }
        }
        // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
        el.__vueClickOutside__ = clickHandler
        document.addEventListener('click', clickHandler)
      },
      update() {},
      unbind(el, binding) {
        // 解除事件监听
        document.removeEventListener('click', el.__vueClickOutside__)
        delete el.__vueClickOutside__
      }
    }
  },
  props: {
    saveToLocal: {
      // 搜索条件保存到本地
      type: Boolean,
      default: false
    },
    searchList: {
      type: Array,
      default() {
        return []
      }
    },
    placeholder: {
      type: String,
      default: '请输入关键字'
    },
    showFilter: {
      type: Boolean,
      default: true
    },
    searchButtonText: {
      type: String,
      default: '查询'
    },
    resetButtonText: {
      type: String,
      default: '重置'
    },
    storageName: {
      type: String,
      default: 'searchbar'
    },
    saveToLocalPosition: {
      type: String,
      default: 'right',
      validator: function (value) {
        return ['left', 'right'].indexOf(value) !== -1
      }
    },
    customTagList: {
      // 自定义条件标签的显示
      type: Boolean,
      default: false
    },
    maxConditionLength: {
      type: Number,
      default: 4
    }
  },
  data() {
    return {
      keyword: '',
      currentSearchList: [],
      shrinkFilterList: false,
      conditionList: [],
      conditionValue: '',
      currentData: {},
      dialogConditionVisible: false,
      hasSetDefaultTag: false, // 是否设置过默认tag
      tagList: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '今日',
            onClick(picker) {
              const end = new Date(new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1) // 今日23:59:59的时间
              const start = new Date(new Date().setHours(0, 0, 0, 0)) // 今日0点
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  computed: {},
  watch: {
    searchList: {
      handler(value) {
        this.currentSearchList = _.cloneDeep(value)
        deepCopyFunction(this.currentSearchList, value)
        if (!this.hasSetDefaultTag) {
          this.setDefaultTagList()
          this.hasSetDefaultTag = true
        }
      },
      deep: true,
      immediate: true
    }
  },
  filters: {},
  created() {},
  mounted() {
    this.getLocalStorageConditionListData()
  },
  methods: {
    // 从localStorage里面读取已保存的筛选条件数据
    getLocalStorageConditionListData() {
      let localList = localStorage.getItem(`syswin${this.storageName}`)
      if (!['', undefined, null].includes(localList)) {
        localList = JSON.parse(localList)
        this.conditionList = localList && localList.length ? _.cloneDeep(localList) : []
      }
    },
    // 创建选中的标签数据
    createTagList() {
      const list = []
      this.currentSearchList.length &&
        this.currentSearchList.forEach((ele) => {
          ele.itemList.forEach((item) => {
            if (item.isActive || item.type === 'slot') {
              let obj = {
                pId: ele.id,
                pName: ele.name,
                // multiple: ele.multiple,
                id: item.id,
                name: '',
                value: item.value,
                type: item.type
              }
              if (item.type === 'text') {
                obj.name = item.name
              } else if (item.type === 'month' || item.type === 'year') {
                if (!item.value) return
                obj.name = item.value + (item.type === 'month' ? '月' : '年')
              } else if (item.type === 'daterange') {
                if (!item.value || !item.value[0]) {
                  return
                }
                obj.name = `${moment(item.value[0]).format('YYYY-MM-DD')}至${moment(item.value[1]).format('YYYY-MM-DD')}`
              } else if (item.type === 'monthrange') {
                if (!item.value || !item.value[0]) {
                  return
                }
                obj.name = `${moment(item.value[0]).format('YYYY-MM')}至${moment(item.value[1]).format('YYYY-MM')}`
              } else if (item.type === 'datetimerange') {
                if (!item.value || !item.value[0]) {
                  return
                }
                if (item.format && item.format === 'yyyy-MM-dd HH:mm') {
                  obj.name = `${moment(item.value[0]).format('YYYY-MM-DD HH:mm')}至${moment(item.value[1]).format('YYYY-MM-DD HH:mm')}`
                } else {
                  obj.name = `${moment(item.value[0]).format('YYYY-MM-DD HH:mm:ss')}至${moment(item.value[1]).format('YYYY-MM-DD HH:mm:ss')}`
                }
              } else if (item.type === 'select') {
                if (!item.value) return
                if (item.multiple) {
                  const valueOptions = item.value.map((x) => item.options.find((f) => f.value === x))
                  obj.name = valueOptions.map((x) => x.label).join(',')
                } else {
                  obj.name = item.options.find((x) => x.value === item.value).label
                }
              } else if (item.type === 'cascade') {
                if (!item.value) return
                if (item.multiple) {
                  if (!item.value.length) {
                    return
                  }
                  // const valueOptions = item.value.map((x) => item.options.find((f) => f.value === x))
                  const valueOptions = item.value.map((x) => {
                    // console.log('xxxxxxxxxxxxx', x) // 这里的x是个数组
                    const lastValue = x[x.length - 1]
                    const find = findTree(item.options, tItem => tItem.value === lastValue)
                    return find
                  })
                  obj.name = valueOptions.map((x) => x.nodes.map(y => y.label).join('/')).join(',')
                } else {
                  const lastValue = item.value[item.value.length - 1]
                  const find = findTree(item.options, tItem => tItem.value === lastValue)
                  obj.name = find ? find.nodes.map(y => y.label).join('/') : ''
                }
              } else if (item.type === 'slot') {
                if (!item.getValue) return
                const info = item.getValue() // 这里不能直接调，因为是深拷贝过来的
                if (!info.name || !info.value) {
                  // 如果没有选择数据，则不处理
                  return
                }
                obj.name = info.name || ''
                obj.value = info.value
                obj = Object.assign(obj, info)
              }
              list.push(obj)
            }
          })
        })
      return list
    },
    // 设置底部标签，比如日期重新设置了值，但是底部没有标签，使用该方法来生成
    /*
      this.$set(this.searchList[10].itemList[0], 'value', [1649865600000, 1657727999000])
      this.$set(this.searchList[10].itemList[0], 'isActive', true)
      this.$nextTick(() => {
        this.$refs.searchbarRef.setTagList()
      })
    */
    setTagList() {
      const filterList = this.createTagList()
      this.tagList = filterList
    },
    // 搜索按钮
    handleSearch(skipShrink) {
      if (this.$slots.default) {
        // 如果使用的是slot,则只触发on-search事件
        this.$emit('on-search', { keyword: this.keyword, filterList: [] })
        return
      }
      const filterList = this.createTagList()
      this.tagList = filterList
      if (!skipShrink) {
        this.shrinkFilterList = false
      }
      this.$emit('on-search', { keyword: this.keyword, filterList })
    },
    // 重置按钮
    handleReset() {
      this.handleClearData()
      this.conditionValue = ''
      this.$emit('on-reset', { keyword: this.keyword, filterList: [...this.tagList] })
    },
    // 更多筛选/收起筛选点击事件
    handleToggleFilterList() {
      if (this.shrinkFilterList) {
        const old = JSON.stringify(this.tagList)
        const now = JSON.stringify(this.createTagList())
        if (old !== now) {
          // 条件改变后才去执行查询
          this.handleSearch(true)
        }
      }
      this.shrinkFilterList = !this.shrinkFilterList
    },
    // 清空输入框的关键字
    handleClearInput() {
      this.keyword = ''
      const filterList = this.createTagList()
      this.$emit('on-search', { keyword: this.keyword, filterList })
    },
    handleTagClose(tag) {
      const parentItem = this.currentSearchList.find((x) => x.id === tag.pId)
      const parentIndex = this.currentSearchList.findIndex((x) => x.id === tag.pId)
      const childIndex = parentItem.itemList.findIndex((x) => x.id === tag.id)
      parentItem.itemList.forEach((item, index) => {
        if (parentItem.multiple) {
          // 多选
          index === childIndex && (item.isActive = false)
        } else {
          // 单选
          if (index === childIndex) {
            item.isActive = false
            ;(item.type === 'daterange' || item.type === 'monthrange' || item.type === 'datetimerange') && (item.value = null)
            if (item.type === 'month' || item.type === 'year') {
              item.value = ''
            }
            if (item.type === 'select') {
              item.value = item.multiple ? [] : null
            }
            if (item.type === 'cascade') {
              item.value = item.multiple ? [] : null
            }
            if (item.type === 'slot') {
              item.setValue({ name: '', value: '' })
            }
          }
        }
      })
      this.$set(this.currentSearchList, parentIndex, parentItem)
      const filterList = this.createTagList()
      this.tagList = filterList
      this.$emit('on-search', { keyword: this.keyword, filterList })
    },
    // 关闭所有的标签
    handleClearAllTags() {
      this.tagList.forEach((tag) => {
        const parentItem = this.currentSearchList.find((x) => x.id === tag.pId)
        const parentIndex = this.currentSearchList.findIndex((x) => x.id === tag.pId)
        const childIndex = parentItem.itemList.findIndex((x) => x.id === tag.id)
        parentItem.itemList.forEach((item, index) => {
          if (parentItem.multiple) {
            // 多选
            index === childIndex && (item.isActive = false)
          } else {
            // 单选
            if (index === childIndex) {
              item.isActive = false
              ;(item.type === 'daterange' || item.type === 'monthrange' || item.type === 'datetimerange') && (item.value = null)
              if (item.type === 'month' || item.type === 'year') {
                item.value = ''
              }
              if (item.type === 'select') {
                item.value = item.multiple ? [] : null
              }
              if (item.type === 'cascade') {
                item.value = item.multiple ? [] : null
              }
              if (item.type === 'slot') {
                item.setValue({ name: '', value: '' })
              }
            }
          }
        })
        this.$set(this.currentSearchList, parentIndex, parentItem)
      })
      const filterList = this.createTagList()
      this.tagList = filterList
      this.$emit('on-search', { keyword: this.keyword, filterList })
    },
    // 清除关键字/选中标签/选中条件
    handleClearData() {
      this.conditionValue = ''
      this.keyword = ''

      const currentSearchList = _.cloneDeep(this.currentSearchList)
      currentSearchList.forEach((ele) => {
        ele.itemList.forEach((item) => {
          item.isActive = !!item.default
          if (['month', 'year'].includes(item.type)) {
            item.value = item.default && item.defaultValue ? item.defaultValue : ''
          }
          if (item.type === 'daterange' || item.type === 'monthrange' || item.type === 'datetimerange') {
            item.value = item.default && item.defaultValue ? item.defaultValue : null
          }
          if (item.type === 'select') {
            if (item.default && item.defaultValue) {
              if (item.multiple) {
                const valueOptions = item.defaultValue.map((x) => item.options.find((f) => f.value === x))
                item.value = valueOptions.map((x) => x.value)
              } else {
                item.value = item.defaultValue
              }
            } else {
              item.value = null
            }
          }
          if (item.type === 'cascade') {
            if (item.multiple) {
              item.value = []
            } else {
              item.value = null
            }
          }
          item.type === 'slot' && item.setValue({ value: '', name: '' })
        })
      })
      this.currentSearchList = currentSearchList
      this.setDefaultTagList()
    },
    setDefaultTagList() {
      const list = []
      if (this.currentSearchList) {
        this.currentSearchList.forEach((ele) => {
          ele.itemList.forEach((item) => {
            if (item.default) {
              // 如果是默认值
              const obj = {
                pId: ele.id,
                pName: ele.name,
                id: item.id,
                name: '',
                value: item.value,
                type: item.type
              }
              if (item.type === 'text') {
                obj.name = item.name
              } else if (item.type === 'month' || item.type === 'year') {
                if (!item.defaultValue) return
                obj.name = item.defaultValue + (item.type === 'month' ? '月' : '年')
              } else if (item.type === 'daterange') {
                if (!item.defaultValue || !item.defaultValue[0]) {
                  return
                }
                obj.name = `${moment(item.defaultValue[0]).format('YYYY-MM-DD')}至${moment(item.defaultValue[1]).format('YYYY-MM-DD')}`
              } else if (item.type === 'monthrange') {
                if (!item.defaultValue || !item.defaultValue[0]) {
                  return
                }
                obj.name = `${moment(item.defaultValue[0]).format('YYYY-MM')}至${moment(item.defaultValue[1]).format('YYYY-MM')}`
              } else if (item.type === 'datetimerange') {
                if (!item.defaultValue || !item.defaultValue[0]) {
                  return
                }
                if (item.format && item.format === 'yyyy-MM-dd HH:mm') {
                  obj.name = `${moment(item.defaultValue[0]).format('YYYY-MM-DD HH:mm')}至${moment(item.defaultValue[1]).format('YYYY-MM-DD HH:mm')}`
                } else {
                  obj.name = `${moment(item.defaultValue[0]).format('YYYY-MM-DD HH:mm:ss')}至${moment(item.defaultValue[1]).format('YYYY-MM-DD HH:mm:ss')}`
                }
              } else if (item.type === 'select') {
                if (!item.defaultValue) return
                if (item.multiple) {
                  const valueOptions = item.defaultValue.map((x) => item.options.find((f) => f.value === x))
                  obj.name = valueOptions.map((x) => x.label).join(',')
                } else {
                  const defaultItem = item.options.find((x) => x.value === item.defaultValue)
                  obj.name = defaultItem.label
                  obj.value = defaultItem
                }
              } else if (item.type === 'slot') {
                // slot选项不设置默认值
              }
              list.push(obj)
            }
          })
        })
      }
      this.tagList = list
    },
    // text标签点击
    handleClick(childItem, childIndex, parentIndex) {
      const parentItem = this.currentSearchList[parentIndex]
      parentItem.itemList.forEach((item, index) => {
        if (parentItem.multiple) {
          // 多选
          index === childIndex && (item.isActive = !childItem.isActive)
        } else {
          // 单选
          item.isActive = index === childIndex ? !childItem.isActive : false
          ;(item.type === 'daterange' || item.type === 'monthrange' || item.type === 'datetimerange') && (item.value = null)
          if (item.type === 'month' || item.type === 'year') {
            item.value = ''
          }
          if (item.type === 'select') {
            item.value = item.multiple ? [] : null
          }
          if (item.type === 'cascade') {
            item.value = item.multiple ? [] : null
          }
        }
      })
      this.$set(this.currentSearchList, parentIndex, parentItem)
    },
    // daterage输入框点击
    handleChangeDateragne(childIndex, parentIndex) {
      const parentItem = this.currentSearchList[parentIndex]
      const item = parentItem.itemList[childIndex]
      if (!['', undefined, null].includes(item.value) && item.value.length) {
        // 限制时间间隔为一年内
        if ((item.type === 'daterange' || item.type === 'datetimerange') && item.value[1] - item.value[0] > 366 * 24 * 60 * 60 * 1000) {
          this.$message.warning('所选时间间隔不能超过一年')
          item.value = null
          item.isActive = false
          this.$set(this.currentSearchList[parentIndex].itemList, childIndex, item)
        } else {
          parentItem.itemList.forEach((ele, index) => {
            if (parentItem.multiple) {
              // 多选
              index === childIndex && (ele.isActive = true)
            } else {
              // 单选
              ele.isActive = index === childIndex
            }
          })
          this.$set(this.currentSearchList, parentIndex, parentItem)
        }
      } else {
        item.value = item.type === 'month' || item.type === 'year' ? '' : null
        item.isActive = false
        this.$set(this.currentSearchList[parentIndex].itemList, childIndex, item)
      }
    },
    // 保存按钮
    handleSave() {
      this.currentData = {}
      this.dialogConditionVisible = true
    },
    // 切换保存过滤条件的下拉框
    handleChangeCondition(value) {
      this.conditionValue = value
      const list = this.conditionList.filter((item) => item.value === value)
      if (list.length) {
        const currentSearchList = _.cloneDeep(this.currentSearchList)
        deepCopyFunction(currentSearchList, this.currentSearchList)
        const { keyword = '', filterList = [] } = list[0]
        this.keyword = keyword

        // 先清空所有标签
        currentSearchList.forEach((ele) => {
          ele.itemList.forEach((item) => {
            item.isActive = ['daterange', 'monthrange'].includes(item.type) && (item.value = null)
          })
        })

        // 设置选中的标签
        if (filterList && filterList.length) {
          filterList.forEach((ele) => {
            currentSearchList.forEach((item) => {
              if (ele.pId === item.id) {
                item.itemList.forEach((v) => {
                  if (v.type === 'text') {
                    if (item.multiple) {
                      // 多选
                      v.id === ele.id && (v.isActive = true)
                      v.id === ele.id && ['daterange', 'monthrange'].includes(v.type) && (v.value = ele.value)
                    } else {
                      // 单选
                      v.isActive = v.id === ele.id
                      v.id === ele.id && [('daterange', 'monthrange')].includes(v.type) && (v.value = v.id === ele.id ? ele.value : null)
                    }
                  } else if (v.type === 'slot') {
                    v.setValue && v.setValue({ value: ele.value, name: ele.name, ...ele })
                  } else if (v.type === 'select') {
                    if (v.multiple) {
                      v.value = ele.value
                    } else {
                      v.value = ele.value
                    }
                    if (ele.value) v.isActive = true
                  } else if (v.type === 'cascade') {
                    v.value = ele.value
                    if (ele.value) v.isActive = true
                  } else if (v.type === 'month' || v.type === 'year') {
                    v.value = ele.value
                    if (ele.value) v.isActive = true
                  } else if (v.type === 'daterange' || v.type === 'monthrange' || v.type === 'datetimerange') {
                    v.value = ele.value
                    if (ele.value.length && ele.value[0]) v.isActive = true
                  }
                })
              }
            })
          })
        }

        this.currentSearchList = currentSearchList
        const tList = this.createTagList()
        this.tagList = tList
      }
    },
    // 编辑保存过滤条件的下拉框选项
    handleEditCondition(index) {
      this.currentData = this.conditionList[index]
      this.dialogConditionVisible = true
    },
    // 删除保存过滤条件的下拉框选项
    handleDeleteCondition(index) {
      const item = this.conditionList[index]
      this.conditionValue === item.value && this.handleClearData()
      this.conditionList.splice(index, 1)

      // 删除localStorage保存的数据
      let localList = localStorage.getItem(`syswin${this.storageName}`)
      if (!['', undefined, null].includes(localList)) {
        localList = JSON.parse(localList)
        const idx = localList.findIndex((ele) => ele.value === item.value)
        idx > -1 && localList.splice(idx, 1)
        localList.length > 0
          ? localStorage.setItem(`syswin${this.storageName}`, JSON.stringify(localList))
          : localStorage.removeItem(`syswin${this.storageName}`)
      }
    },
    // 筛选器名称模态框确定按钮事件
    handleConfirmCondition(label) {
      if (_.isEmpty(this.currentData)) {
        // 新建
        const momentValue = moment().valueOf()
        this.conditionList.push({
          label,
          value: momentValue,
          keyword: this.keyword,
          filterList: this.createTagList()
        })
        this.conditionValue = momentValue
      } else {
        // 编辑
        const index = this.conditionList.findIndex((ele) => ele.value === this.currentData.value)
        const item = this.conditionList[index]
        item.label = label
        this.$set(this.conditionList, index, item)
      }
      localStorage.setItem(`syswin${this.storageName}`, JSON.stringify(this.conditionList))
    },
    handleClickOutside(e) {
      // console.log(e)
      const target = e.target
      // console.log(target)
      const dialogList = [...document.querySelectorAll('.el-dialog__wrapper')]
      for (let i = 0; i < dialogList.length; i++) {
        if (dialogList[i].contains(target)) {
          return false
        }
      }

      if (target.classList.contains('el-dialog__wrapper')) {
        // 点击弹窗遮罩时不隐藏
        return false
      }
      const conditionDialog = document.querySelector('.syswin-searchbar-dialog') // 条件设置的弹窗
      const deleteConfirm = document.querySelector('.el-message-box.syswin-searchbar-confirm') // 条件设置的删除弹窗
      if (conditionDialog && conditionDialog.contains(target)) {
        return false
      }
      if (deleteConfirm && deleteConfirm.contains(target)) {
        return false
      }
      this.shrinkFilterList = false
    }
  }
}
</script>
<style lang="scss" scoped>
@import './search-bar';
</style>
