<template>
  <el-row class="JNPF-common-search-box" :gutter="16" v-if="searchList.length">
    <!--    <ColumnFilter @onAddSearchChange="SearchFilterChange" ref="ColumnFilter" v-if="setSeachFlag"></ColumnFilter>-->
    <el-form @submit.native.prevent>
      <el-col :span="6" v-for="(item, index) in searchList" :key="index">
        <el-form-item :label="item.__config__.label" v-show="index < 3 || (index >= 3 && showAll)">
          <!--          设置搜索过滤器-->
          <template v-if="item.conditions && item.conditions.length">
            <template v-if="item.__config__.viewDataType === 'STRING'">
              <template v-if="item.conditions[0].function === 'like'">
                <el-input v-model="item.conditions[0].values[0]" :placeholder="item.__config__.label" clearable class="item"> </el-input>
              </template>
              <template v-else-if="item.conditions[0].function === 'in'">
                <el-cascader
                  class="item"
                  :props="{
                    label: 'VALUE',
                    value: 'KEY',
                    children: item.cascadeSet && item.cascadeSet.childrenName ? item.cascadeSet.childrenName : '',
                    multiple: true,
                    emitPath: false,
                    expandTrigger: 'hover'
                  }"
                  filterable
                  :options="item.options"
                  collapse-tags
                  clearable
                  :show-all-levels="false"
                  v-model="item.conditions[0].values"
                  :placeholder="'请选择' + item.__config__.label"
                ></el-cascader>
              </template>
              <template v-else-if="item.conditions[0].function === 'eq'">
                <el-cascader
                  class="item"
                  :props="{
                    label: 'VALUE',
                    value: 'KEY',
                    children: item.cascadeSet && item.cascadeSet.childrenName ? item.cascadeSet.childrenName : '',
                    multiple: false,
                    emitPath: false,
                    expandTrigger: 'hover'
                  }"
                  filterable
                  :options="item.options"
                  collapse-tags
                  clearable
                  :show-all-levels="false"
                  v-model="item.conditions[0].values[0]"
                  :placeholder="'请选择' + item.__config__.label"
                ></el-cascader>
              </template>
            </template>
            <template v-else-if="item.__config__.viewDataType === 'NUMBER'">
              <template v-if="item.conditions[0].function === 'eq'">
                <el-input v-model="item.conditions[0].values[0]" :placeholder="item.__config__.label" clearable class="item"> </el-input>
              </template>
              <template v-if="item.conditions[0].function === 'between'">
                <num-range v-model="item.conditions[0].values"></num-range>
              </template>
              <template v-if="item.conditions[0].function === 'single'">
                <el-cascader
                  class="item"
                  :props="{ label: 'VALUE', value: 'KEY', multiple: false, emitPath: false, expandTrigger: 'hover' }"
                  filterable
                  :options="item.options"
                  collapse-tags
                  clearable
                  :show-all-levels="false"
                  v-model="item.conditions[0].values[0]"
                  :placeholder="'请选择' + item.__config__.label"
                ></el-cascader>
              </template>
            </template>
            <template v-else-if="item.__config__.viewDataType === 'DATETIME'">
              <el-date-picker
                v-model="item.conditions[0].values"
                :value-format="item.dateFormat"
                :format="item.dateFormat"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="item"
                type="daterange"
              />
            </template>
          </template>
          <template v-else>
            <template v-if="useInputList.indexOf(item.__config__.jnpfKey) > -1">
              <el-input v-model="item.value" :placeholder="item.__config__.label" clearable @change="elFormChange" class="item"> </el-input>
            </template>
            <template v-else-if="useDateList.indexOf(item.__config__.jnpfKey) > -1">
              <el-date-picker
                v-model="item.value"
                :value-format="item.format"
                :format="item.format"
                @change="elFormChange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="item"
                type="daterange"
              />
            </template>
            <template v-else-if="useSelectList.indexOf(item.__config__.jnpfKey) > -1">
              <el-select v-model="item.value" :placeholder="'请选择' + item.__config__.label" clearable @change="elFormChange" filterable class="item">
                <el-option :label="oItem[item.__config__.props.label]" v-for="(oItem, i) in item.__slot__.options" :value="oItem[item.__config__.props.value]" :key="i"></el-option>
              </el-select>
            </template>
            <template v-else>
              <template v-if="item.__config__.jnpfKey === 'numInput' || item.__config__.jnpfKey === 'calculate'">
                <num-range @change="elFormChange" v-model="item.value"></num-range>
              </template>
              <template v-if="item.__config__.jnpfKey === 'cascader'">
                <el-cascader
                  v-model="item.value"
                  :options="item.options"
                  clearable
                  @change="elFormChange"
                  :show-all-levels="item['show-all-levels']"
                  :props="item.props.props"
                  filterable
                  :placeholder="'请选择' + item.__config__.label"
                  class="item"
                ></el-cascader>
              </template>
              <template v-if="item.__config__.jnpfKey === 'time' || item.__config__.jnpfKey === 'timeRange'">
                <el-time-picker
                  v-model="item.value"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  @change="elFormChange"
                  clearable
                  :value-format="item.format"
                  :format="item.format"
                  is-range
                  class="item"
                />
              </template>
              <template v-if="item.__config__.jnpfKey === 'date'">
                <el-date-picker
                  v-model="item.value"
                  :type="item.type + 'range'"
                  @change="elFormChange"
                  :value-format="item.format"
                  :format="item.format"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  class="item"
                >
                </el-date-picker>
              </template>
              <template v-if="item.__config__.jnpfKey === 'dateRange'">
                <el-date-picker
                  v-model="item.value"
                  :type="item.type"
                  @change="elFormChange"
                  :value-format="item.format"
                  :format="item.format"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  class="item"
                >
                </el-date-picker>
              </template>
              <template v-if="commonList.includes(item.__config__.jnpfKey)">
                <component :is="item.__config__.tag" v-model="item.value" @change="elFormChange" :placeholder="'请选择' + item.__config__.label" class="item" />
              </template>
              <template v-if="item.__config__.jnpfKey === 'address'">
                <JNPFAddress v-model="item.value" :placeholder="'请选择' + item.__config__.label" @change="elFormChange" :level="item.level" class="item" clearable />
              </template>
              <template v-if="item.__config__.jnpfKey === 'treeSelect'">
                <JNPF-TreeSelect v-model="item.value" :placeholder="'请选择' + item.__config__.label" @change="elFormChange" :options="item.options" :multiple="item.multiple" class="item" clearable />
              </template>
              <template v-if="item.__config__.jnpfKey === 'createUser' || item.__config__.jnpfKey === 'modifyUser'">
                <userSelect v-model="item.value" :placeholder="'请选择' + item.__config__.label" @change="elFormChange" class="item" />
              </template>
              <template v-if="item.__config__.jnpfKey === 'currOrganize'">
                <comSelect v-model="item.value" :placeholder="'请选择' + item.__config__.label" @change="elFormChange" class="item" />
              </template>
              <template v-if="item.__config__.jnpfKey === 'currDept'">
                <depSelect v-model="item.value" :placeholder="'请选择' + item.__config__.label" @change="elFormChange" class="item" />
              </template>
              <template v-if="item.__config__.jnpfKey === 'currPosition'">
                <posSelect v-model="item.value" :placeholder="'请选择' + item.__config__.label" @change="elFormChange" class="item" />
              </template>
            </template>
          </template>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item>
          <el-button @click="search()">{{ $t('common.search') }} </el-button>
          <el-button @click="reset()">{{ $t('common.reset') }} </el-button>
          <template v-if="searchList.length > 4">
            <el-button type="text" icon="el-icon-arrow-down" @click="showAll = true" v-if="!showAll"> 展开 </el-button>
            <el-button type="text" icon="el-icon-arrow-up" @click="showAll = false" v-else> 收起</el-button>
          </template>
        </el-form-item>
      </el-col>
    </el-form>
  </el-row>
</template>

<script>
import { deepClone } from '@/utils'
import { dyOptionsList, useDateList, useInputList, useSelectList } from '@/components/Generator/generator/comConfig'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import ColumnFilter from '@/components/ColumnFilter/index'
import { getAPIData, getCondAPIData } from '@/components/Dataset-filter/util'
import { dictDetail } from '@/api/newbi/dict'
import AmisSdk from '@/components/AmisSdk.vue'

export default {
  props: ['list', 'treeBoxSearch'],
  components: { AmisSdk, ColumnFilter },
  data() {
    return {
      showAll: false,
      setSeachFlag: false,
      searchList: [],
      commonList: ['comSelect', 'depSelect', 'posSelect', 'userSelect', 'dicSelect'],
      useInputList,
      useDateList,
      useSelectList,
      selectSearchId: null
    }
  },
  watch: {
    list: {
      handler: function (val) {
        this.searchList = deepClone(val)
        this.buildOptions(this.searchList)
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    // this.search()
  },
  methods: {
    elFormChange(val) {
      this.buildOptions(this.searchList)
    },
    buildOptions(componentList) {
      componentList.forEach((cur) => {
        const config = cur.__config__
        //添加过滤器
        if (cur.conditions && cur.conditions.length) {
          //设置api接口请求 并且设置apiid
          if (cur.enumSource === '2' && cur.enumId) {
            getCondAPIData(cur.enumId, cur.apiProps, cur.cascadeSwitch).then((res) => {
              //开启级联
              if (cur.cascadeSwitch) {
                try {
                  let data = res.filter((i) => i[cur.cascadeSet.idKey] || i[cur.cascadeSet.pidKey])
                  let treeData = g.T.toTree(data, cur.cascadeSet.childrenName, cur.cascadeSet.idKey, cur.cascadeSet.pidKey)
                  this.$set(cur, 'options', treeData)
                } catch {}
              } else {
                this.$set(cur, 'options', res)
              }
            })
          }
        }
        if (dyOptionsList.indexOf(config.jnpfKey) > -1) {
          let isTreeSelect = config.jnpfKey === 'treeSelect' || config.jnpfKey === 'cascader'
          if (config.dataType === 'dictionary') {
            if (!config.dictionaryType) return
            dictDetail({ id: config.dictionaryType }).then((res) => {
              let content = JSON.parse(res.data.data.content || '[]')
              isTreeSelect ? (cur.options = content.map((i) => ({ fullName: i.value, id: i.key }))) : (cur.__slot__.options = content.map((i) => ({ fullName: i.value, id: i.key })))
            })
          }
          if (config.dataType === 'dynamic') {
            if (!config.propsUrl) return
            if (isTreeSelect) {
              if (cur.conditions && cur.conditions.length) return
              getAPIData(cur, config.propsUrl, config.ApiParams, componentList, 'search', config.apiProps).then((res) => {
                this.$set(cur, 'options', res)
              })
            } else {
              getAPIData(cur.__slot__, config.propsUrl, config.ApiParams, componentList, 'search', config.apiProps).then((res) => {
                this.$set(cur.__slot__, 'options', res)
              })
            }
          }
        }
      })
    },
    search() {
      let arr = []
      for (let i = 0; i < this.searchList.length; i++) {
        const e = this.searchList[i]
        if (e.conditions && e.conditions.length && e.conditions[0] && e.conditions[0].values && e.conditions[0].values.length && e.conditions[0].values[0] !== '') {
          let obj = {}
          obj.cubeColumnId = e.__vModel__
          obj.function = e.conditions[0].function
          obj.values = this.filterNullArr(e.conditions[0].values)
          arr.push(obj)
        } else if (e.value) {
          let obj = {}
          if (Array.isArray(e.value)) {
            if (e.value.length) {
              obj.cubeColumnId = e.__vModel__
              obj.function = e.__config__.viewDataType === 'STRING' ? (e.function = 'like') : e.__config__.viewDataType === 'NUMBER' ? (e.function = 'between') : 'between'
              obj.values = e.value
              arr.push(obj)
            }
          } else {
            obj.cubeColumnId = e.__vModel__
            obj.function = e.__config__.viewDataType === 'STRING' ? (e.function = 'like') : e.__config__.viewDataType === 'NUMBER' ? (e.function = 'between') : 'between'
            obj.values = [e.value]
            arr.push(obj)
          }
        }
      }
      let json = JSON.stringify(arr) === '[]' ? [] : JSON.stringify(arr)
      this.$emit('search', json)
    },
    //排空
    filterNullArr(values) {
      try {
        return values
          .map((o, i) => {
            if (o !== '') {
              return o
            }
          })
          .filter((l) => l !== undefined)
      } catch {
        return values
      }
    },
    reset() {
      this.searchList = deepClone(this.list)
      this.buildOptions(this.searchList)
      this.search()
      this.$emit('reset')
    },
    treeReset() {
      this.searchList = deepClone(this.list)
    }
  }
}
</script>
<style lang="scss" scoped>
.elSearchIcon {
  cursor: pointer;
  position: absolute;
  top: -4px;
  right: -20px;
}
.JNPF-common-search-box {
  ::v-deep .el-form-item--small .el-form-item__content {
    line-height: 37px !important;
  }
}
</style>
