<template>
  <!-- 全面的筛选组件：初级普通筛选 + 高级筛选（按照配置来判断显示情况）-->
  <!-- todo:使用v-if每次重新赋值，与接口查询保持一致 -->
  <div 
    class="searchOverallComponent" 
    :style="{height:componentsHeight+'px',overflow:isShowMoreList ? 'unset' : 'hidden'}" 
    v-show="isShow"
  >
    <div 
      class="border-outer" 
      ref="searchOverallComponent_inner"
    >
      <!-- 整体背景遮罩 -->
      <!-- <div 
        v-if="isShow && isShowMoreList" 
        class="fullPageCover"
        :style="{height:searchOverallCoverHeight}"
      ></div> -->
      <!-- <div class="title" v-if="isShowMoreList">高级筛选</div> -->
      <!-- 普通筛选界面 -->
      <searchPrimary
        v-if="primarySearchOption && primarySearchOption.length > 0"
        ref="searchPrimaryRef"
        :showBaseButton="!isShowMoreList"
        :primarySearchOption="primarySearchOption"
        :primarySearchButton="isShowMoreList ? primarySearchButton : primarySearchAllButton"
        @primarySearchButtonClick="primarySearchButtonClick"
        @primarySearchBaseHandle="primarySearchBaseHandle"
        >
        <slot></slot>
      </searchPrimary>
      <!-- 高级筛选界面 -->
      <div v-if="isShow && isShowMoreList" class="moreListOuter">
        <curren-Form
          :style="`--navFilterMaxHeight: ${selectMaxHeight};`"
          class="navFilter"
          size="medium"
          labelWidth="0"
          :searchData="moreListData"
        >
            <el-row :gutter="20">
              <el-form-item
                v-for="(item, index) in moreListData.filters"
                :key="index"
              >
                <el-col :span="5">
                  <el-form-item
                    :prop="'filters.' + index + '.column'"
                    :rules="rules && rules.column ? rules.column : []"
                  >
                    <el-select
                      v-model="item.column"
                      placeholder="请选择筛选对象"
                      :disabled="item.hide"
                      :filterable="true"
                      @change="resetSelect(item)"
                    >
                      <el-option
                        v-for="(item, index) in tableColumnsOptions(tableColumns)"
                        :key="index"
                        :label="item.label"
                        :value="
                          item.showProp
                            ? item.prop + '.' + item.showProp
                            : item.prop
                        "
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item
                    :prop="'filters.' + index + '.action'"
                  >
                    <el-select
                      v-model="item.action"
                      placeholder="请选择条件"
                      :disabled="disabledAction || item.column == '' || item.hide ? true : false"
                    >
                    <!-- moreListOptions.action -->
                      <el-option
                        v-for="item in formatMoreListOptions(item.column) "
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item
                    :prop="'filters.' + index + '.value'"
                    :rules="rules && rules.value ? rules.value : []"
                  >
                    <el-select
                      v-if="inputOrSelect(item.column)"
                      v-model="item.value"
                      placeholder="请选择内容"
                      :disabled="item.column == '' || item.hide ? true : false"
                      :filterable="true"
                      @change="inputOrSelect(item.column)"
                      clearable
                    >
                      <el-option
                        v-for="item in inputOrSelect(item.column)"
                        :key="item.value"
                        :label="item.label"
                        :value="
                          typeof item.value == 'string'
                            ? item.value
                            : String(item.value)
                        "
                      >
                      </el-option>
                    </el-select>
                    <!-- 日期时间 -->
                    <el-date-picker
                    v-else-if="getColumnType(item.column) == 'datetime'"
                      type="datetime"
                      v-model="item.value"
                      :placeholder="'选择日期时间'"
                      style="width: 100%"
                      format="yyyy-MM-dd HH:mm:ss"
                      value-format="yyyy-MM-ddTHH:mm:ss"
                    ></el-date-picker>
                    <el-input
                      v-else
                      v-model="item.value"
                      placeholder="请输入内容"
                      :disabled="item.column == '' || item.hide ? true : false"
                      clearable
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item
                    :prop="'filters.' + index + '.logic'"
                  >
                    <el-select
                      v-model="item.logic"
                      placeholder="请选择关系"
                      :disabled="disabledLogic || item.column == '' || item.hide ? true : false"
                    >
                      <el-option
                        v-for="item in moreListOptions.logic"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="1" v-if="!item.hide">
                  <!-- 删除条件按钮 -->
                  <el-button
                    type="danger"
                    icon="el-icon-minus"
                    circle
                    size="mini"
                    @click="moreListDelete(index,item)"
                  ></el-button>
                </el-col>
              </el-form-item>
            </el-row>
        </curren-Form>
        <div class="buttonsContent">
          <div class="leftButtons">
            <!-- 添加筛选条件 -->
            <el-button size="small" @click="moreListPush(true)">+ 添加筛选条件</el-button>
            <!-- 收起 -->
            <el-button
              type="text"
              size="small"
              @click="moreListButtonHandle({ label:'收起筛选', name:'moreList-up', type: 'text', icon:'el-icon-arrow-up',  iconRight:true})"
            >
              收起筛选
              <i 
                style="margin-left:0" 
                :class="['el-icon--right','el-icon-arrow-up']"
              ></i>
            </el-button>
          </div>
          <!-- 按钮 -->
          <div class="rightButtons" v-if="moreListbuttons && moreListbuttons.length > 0" >
            <el-button
              v-for="(item,index) in moreListbuttons"
              :key="index"
              :type="item.type"
              :size="item.size || 'small'"
              @click="moreListButtonHandle(item)"
              :icon="item.iconRight ? '' : item.icon"
            >
              {{ item.label }}
              <!-- 自定义右侧图标 -->
              <i 
                style="margin-left:0" 
                v-if="item.iconRight" 
                :class="['el-icon--right',item.icon]"
              ></i>
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
  </template>
  <script>
  import searchPrimary from "@/components/searchPrimary"
  export default {
    name:'searchOverallComponent',
    components: {
      searchPrimary,
    },
    watch:{
      // 监听显示切换
      showSearchOverall(n){
        // 控制是否显示 + 动画效果处理
        // 没有普通查询配置
        if(this.primarySearchOption.length <= 0){
          this.changeSearchOverallShow(n)
          this.changeMoreListShow(n)
          this.$nextTick(()=>{
            this.componentsHeight = this.getAllSearchInnerHeight() + 20
            // 收起
            if(!n && this.$parent.changeTableHeight){
              this.$parent.changeTableHeight()
            }
          })
          return
        }
        // 有普通查询配置
        if(n){ 
          this.changeSearchOverallShow(n)
          this.changeMoreListShow(false)
        }
        this.$nextTick(()=>{
          if(n){
              this.componentsHeight = this.getSearchPrimaryHeight() + 20
          }else{
            this.componentsHeight = 0
            this.changeMoreListShow(false)
            // setTimeout(()=>{
            //   this.changeSearchOverallShow(n)
            // },500)
          }
        })
        this.setOverallSearchData(this.httpOverallSearchData)
      },
      // 监听接口搜索的筛选数据
      httpOverallSearchData(n,o){
        this.setOverallSearchData(n)
      },
      isShowMoreList(){
        this.setOverallSearchData(this.httpOverallSearchData)
      }
    },
    props: {
      // 筛选条件最大高度
      selectMaxHeight:{
        type: String,
        default: '174px'
      },
      // 筛选遮罩高度
      searchOverallCoverHeight:{
        type: String,
        default: 'calc(100vh - 200px)'
      },
      // 禁用选择条件
      disabledAction:{
        type: Boolean,
        default: false
      },
      // 禁用选择关系
      disabledLogic:{
        type: Boolean,
        default: false
      },
      // 是否显示全面筛选组件
      showSearchOverall:{
        type: Boolean,
        default: false
      },
      // 是否显示高级筛选
      showMoreSearch:{
        type: Boolean,
        default: true
      },
      //普通筛选绑定表单数据
      primarySearchOption: {
        type: Array,
        default: () => {
          return []
        }
      },
      //普通筛选自定义按钮
      primarySearchButton:{
        type: Array,
        default: () => {
          return []
        }
      },
      // 显示数据配置
      tableColumns: {
        type: Array,
        default: () => {
          return []
        }
      },
      // 当前接口中的筛选数据（用于同步全面筛选的数据）
      httpOverallSearchData:{
        type: Object,
        default: null
      },
      // 自定义配置条件
      filterActionOptions:{
        type: Array,
        default: null
      },
    },
    data() {
      return {
        // 普通筛选自定义所有按钮(包括高级筛选)
        primarySearchAllButton:[],
        // 高级筛选列表是否显示
        isShowMoreList:false,
        // 组件高度（用于动画效果）
        componentsHeight:0,
        // 是否显示总组件，与showSearchOverall相通（重新定义一遍目的是为了动画效果）
        isShow:false,
        // 高级筛选列表内部按钮
        moreListbuttons: [
          { label: "搜索", type: "primary", name: "moreList-search" },
          { label: '重置', name: 'moreList-reset' },
          // { label:'收起筛选', name:'moreList-up', type: 'text', icon:'el-icon-arrow-up',  iconRight:true}
        ],
        // 高级筛选数据列表/值
        moreListData: {filters:[]},
        // 高级筛选条件列表配置
        moreListOptions: {
          action: [{
            value: '==',
            label: '等于'
          }, {
            value: '!=',
            label: '不等于'
          }, {
            value: '>',
            label: '大于'
          }, {
            value: '<',
            label: '小于'
          }, {
            value: '>=',
            label: '大于等于'
          }, {
            value: '<=',
            label: '小于等于'
          }, {
            value: 'Like',
            label: '包含'
          }, {
            value: 'NotLike',
            label: '不包含'
          },
            //  {
            //   value: 'In',
            //   label: '包含'
            // }, {
            //   value: 'NotIn',
            //   label: '不包含'
            // }
          ],
          logic: [
            {
              value: 'And',
              label: '并且'
            },
            {
              value: 'Or',
              label: '或者'
            }
          ],
        },
        // 高级筛选rules暂未使用验证，但是不能删除rules定义
        // todo:优化后放开，优化内容：如果选择了筛选对象【column】，则验证【value】，否则都不验证
        rules:{
        //   column: [
        //     { required: true, message: '请选择筛选对象', trigger: 'change' }
        //   ],
        //   value: [
        //     { required: true, message: '请输入内容', trigger: 'blur' }
        //   ],
        },
      }
    },
    created() {
      this.moreListPush()
    },
    mounted() {
      // 配置普通筛选默认按钮(是否包含高级筛选按钮)
      this.setPrimarySearchAllButton()
    },
    methods: {
      // 获取普通筛选的高度,外部也有使用，用于动画样式
      getSearchPrimaryHeight(){
        return document.getElementsByClassName('searchPrimaryComponent')[0].clientHeight
      },
      // 获取普高级筛选的高度,外部也有使用，用于动画样式
      getAllSearchInnerHeight(){
        return this.$refs.searchOverallComponent_inner ? this.$refs.searchOverallComponent_inner.clientHeight : 0
      },
      // 配置普通筛选自定义按钮
      setPrimarySearchAllButton(){
        let _more_btn = [{
          label:'高级筛选',
          name:'more',
          type: 'text',
          icon:'el-icon-arrow-down',
          iconRight:true
        }]
        if(this.showMoreSearch){
          this.primarySearchAllButton = _more_btn.concat(this.primarySearchButton)
        }else{
          this.primarySearchAllButton= this.primarySearchButton
        }
      },
      // 普通查询基础按钮点击事件
      primarySearchBaseHandle(item,data, option, that){
        this.overallSearchFormClick(item,data, option, that)
      },
      // 普通筛选自定义按钮点击事件
      primarySearchButtonClick( item,data, option,that){
        // 点击[高级筛选]按钮
        if(item.name == 'more'){
          this.changeMoreListShow(true)
        }
        this.overallSearchFormClick(item,data, option, that)
      },
      // 高级筛选基础按钮点击事件
      moreListButtonHandle(item){
        this.overallSearchFormClick(item)
      },
      // 设置moreList的列表值（默认按tableColumns设置）
      tableColumnsOptions(val) {
        const data = JSON.parse(JSON.stringify(val));
        let num = 0
        val.forEach((item, index) => {
          if (item.showProp) {
            data.splice(index - num, 1)
            num++
          }
        })
        return data
      },
      // 判断筛选类型是否是时间格式
      getColumnType(val) {
        var columnsType = this.tableColumns.filter(item => item.prop == val)
        if (columnsType.length > 0) {
          if (columnsType[0].apiBaseType) {
            return columnsType[0].apiBaseType
          } 
        }  else {
          return ''
        }
      },
      // 筛选条件改变重置其他项
      resetSelect(val) {
        val.action = "=="
        val.value = ""
      },
      // 根据数据内容约束条件选项
      formatMoreListOptions(val) {
        // 自定义配置条件filterActionOptions
        if(this.filterActionOptions){
          this.moreListOptions.action = this.filterActionOptions
          return this.moreListOptions.action
        }
        if (val) {
          for(var i =0; i< this.tableColumns.length; i++) {
            if (val == this.tableColumns[i].prop) {
              if (this.tableColumns[i].filters) {
                return this.moreListOptions.action.filter(item => item.value == '==' || item.value == '!=')
              } else if (this.tableColumns[i].type == 'dateTime') {
                return this.moreListOptions.action.filter(item => 
                  item.value == '==' || 
                  item.value == '!=' ||
                  item.value == '>' ||
                  item.value == '<' ||
                  item.value == '>=' ||
                  item.value == '<=' )
              } else {
                return this.moreListOptions.action
              }
            }
          }
        }
        return this.moreListOptions.action
      },
      // 设置moreList列表的内容项是input还是select
      inputOrSelect(val) {
        let data = null
        if (val) {
          this.tableColumns.forEach((key) => {
            if (val == key.prop) {
              if (key.enums_list && key.enums_list.length > 0) {
                data = key.enums_list
              } 
            }
          })
        } 
        return data
      },
      // 高级筛选列表-删除筛选条件行
      moreListDelete(val,item) {
        if (this.moreListData.filters.length == 1) {
          this.$warningMsg('必须保留一条筛选条件！')
        } else {
          this.$confirm('您确定删除吗, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.moreListData.filters.splice(val, 1)
          }).catch(() => {
            //   this.modalAppendToBody = false
          });
        }
        this.overallSearchFormClick({name:'moreList-deleteRow'})
      },
      // 高级筛选列表-添加筛选条件行
      moreListPush(handle) {
        let data = {
          logic: "And",
          column: "",
          action: "==",
          value: ""
        }
        this.moreListData.filters.push(data)
        this.overallSearchFormClick({name:'moreList-addRow'})
        if(handle){
          this.$nextTick(()=>{
            this.componentsHeight = this.getAllSearchInnerHeight() + 20
            this.$parent.changeTableHeight(this.getAllSearchInnerHeight())
          })
        }
      },
      // 重置数据，高级（单纯节点显示数据，不重新查询接口）
      resetMoreListData(){
        this.moreListData = {filters:[]}
        this.moreListPush()
      },
      // 设置数据值，高级（单纯节点显示数据，不重新查询接口）
      setMoreListData(val){
        this.moreListData = JSON.parse(JSON.stringify(val))
      },
      // 重置数据，普通+高级（单纯节点显示数据，不重新查询接口）
      resetOverallSearchData(){
        if(this.$refs.searchPrimaryRef)this.$refs.searchPrimaryRef.resetPrimarySearchData();
        this.resetMoreListData()
      },
      // 设置数据，普通+高级（单纯节点显示数据，不重新查询接口）
      setOverallSearchData(data){
        // 普通筛选数据同步
        if(data && data.params){
          if(this.$refs.searchPrimaryRef)this.$refs.searchPrimaryRef.setPrimarySearchData(data.params)
        }else{
          if(this.$refs.searchPrimaryRef)this.$refs.searchPrimaryRef.resetPrimarySearchData()
        }
        // 高级筛选数据同步
        if(data && data.moreList){
          let _list = {filters:[]}
          data.moreList.filters.forEach(item=>{
            if(String(item.column).length > 0 && String(item.value).length > 0){
              _list.filters.push(item)
            }
          })
          if(_list.filters.length <= 0){
            _list.filters.push({
              logic: "And",
              column: "",
              action: "==",
              value: ""
            })
          }
          this.setMoreListData(_list)
        }else{
          this.resetMoreListData()
        }
      },
      // 展开-收缩高级筛选
      changeMoreListShow(val){
        this.isShowMoreList = val || false
        // 如果没有初级筛选 
        if(!this.primarySearchOption || this.primarySearchOption.length <= 0){
          // 关闭时候直接整个全面筛选组件
          if(!this.isShowMoreList){
            this.isShow = false
            this.$emit("getShowSearchOverall",this.isShow)
          }
        }
      },
      // 关闭整个全面组件
      changeSearchOverallShow(val){
        if(!val){
          this.changeMoreListShow(false)
        }
        this.isShow = val || false
        this.$emit("getShowSearchOverall",this.isShow)
      },
      // 全面筛选组件所有按钮事件
      overallSearchFormClick(item,data, option) {
        // 页面功能
        // 收缩筛选
        if(item.name == 'moreList-up'){
          this.changeMoreListShow(false)
        }
        // 高级筛选内-重置 || 普通格式-重置
        else if(item.name == "moreList-reset" || item.name == "reset"){
          this.resetOverallSearchData()
        }
        // 抛出函数传参
        let _searchPrimaryRef = this.$refs.searchPrimaryRef
        let _options = {
          item:item,
          data_primary:_searchPrimaryRef ? _searchPrimaryRef.getPrimarySearchData() : null,
          data_moreList:this.moreListData,
          option_primary:this.primarySearchOption,
          option_moreList:this.tableColumns,
          vm_primary:_searchPrimaryRef,
          vm_moreList:this
        }
        this.$emit("overallSearchFormClick",_options)
      },
    }
  
  }
  </script>
  <style lang="scss" scoped>
  @import "./style/index.scss";
  </style>