<!-- 
 /* @name   查询条件组件
 * @authors pen (you@example.org)
 * @date    2022-06-13
 * @version 1.0.2
 */
 -->
 <template>
  <el-row ref="queryForm" :gutter="10" :type="showMore ? 'none' : 'flex'">
    <el-col
      :class="{ 'hidden-lg-and-down': !showMore && (index == 5 || index == 4) }"
      class="query_form_set_col_margin"
      :xs="item.xs === undefined ? 5 : item.xs"
      :sm="item.sm === undefined ? 5 : item.sm"
      :md="item.md === undefined ? 5 : item.md"
      :lg="item.lg === undefined ? 4 : item.lg"
      :xl="item.xl === undefined ? 3 : item.xl"
      v-for="(item, index) in formList"
      :key="index"
    >
      <form-item-view
        :item="item"
        @update-form="updateForm"
        :inputStyle="queryInputStyle"
        @enter-event="enterEvent"
        @item-click="itemClick"
        @focus-event="focusEvent"
        @remote-method="remoteMethod"
        @mix-input-button-event="mixInputButtonEvent"
      />
      <!-- slot -->
      <div v-if="item.customSlot">
        <template>
          <slot v-bind:customSlotData="item" :name="item.customSlot"></slot>
        </template>
      </div>
    </el-col>
    <!-- 操作栏-->
    <el-col
      v-if="showSearchBtn"
      class="query_form_set_col_margin"
      :xs="10"
      :sm="10"
      :md="10"
      :lg="10"
      :xl="3"
    >
      <div class="search_btn_list">
        <slot name="button"></slot>
        <el-popover
          v-if="collapseList.length"
          v-model="moreVisible"
          @hide="hidepopover"
          placement="bottom"
          width="250"
          trigger="manual"
          popper-class="query_form_show_more_pop"
        >
          <div class="query_form_wrapper show_more_wrapper">
            <div class="form_item_list_box form_item_show_more">
              <span>更多筛选</span
              ><i
                class="el-icon-close show_hand common_close"
                @click="moreVisible = false"
              ></i>
            </div>
            <div></div>
            <div
              v-for="(item, index) in collapseList"
              :key="index"
              class="show_more_item"
            >
              <form-item-view
                :item="item"
                @update-form="updateForm"
                :inputStyle="queryInputStyle"
                @enter-event="enterEvent"
                @item-click="itemClick"
                @focus-event="focusEvent"
                @remote-method="remoteMethod"
                @mix-input-button-event="mixInputButtonEvent"
              />
              <!-- slot -->
              <div v-if="item.customSlot">
                <template>
                  <slot
                    v-bind:customSlotData="item"
                    :name="item.customSlot"
                  ></slot>
                </template>
              </div>
            </div>
            <div class="show_more_bottom">
              <button-view
                :buttons="queryFormButton"
                @button-click="buttonClick"
              />
            </div>
          </div>
          <button
            slot="reference"
            class="btn btn_item query_show_more_box"
            :class="{ btn_change_border: moreVisible || hasCollapseVal }"
            type="text"
            @click="moreVisible = !moreVisible"
          >
            <svg
              class="iconpark-icon"
              :style="{
                color: moreVisible || hasCollapseVal ? '#fc5610' : '#666'
              }"
            >
              <use href="#shaixuan"></use>
            </svg>
          </button>
        </el-popover>
        <el-button class="btn btn_item" type="primary" @click="check"
          >搜索</el-button
        >
      </div>
    </el-col>
  </el-row>
</template>

<script>
import 'element-ui/lib/theme-chalk/display.css'
import formMixin from '../mixins/formMixin.js'
import handleOptionsMixin from '../mixins/handleOptions.js'
import tools from '../utils/tools.js'
import formItemView from './baseView/formItem.vue'
import buttonView from './buttons.vue'
export default {
  name: 'query-form-view',
  mixins: [formMixin, handleOptionsMixin],
  components: {
    formItemView,
    buttonView
  },
  props: {
    queryInputStyle: Object,
    showSearchBtn: {
      type: Boolean,
      default: true
    },
    queryFormItems: {
      type: Array,
      default: () => []
    },
    queryFormButton: {
      type: Array,
      default: () => {
        return [
          {
            text: '重置',
            id: 'reset'
          },
          {
            text: '搜索',
            id: 'check',
            type: 'primary'
          }
        ]
      }
    }
  },
  data() {
    return {
      moreVisible: false,
      MATCH_TYPE: 'matchType',
      RANGE_OPTION: 'rangeOptions',
      formItemstyle: {
        marginBottom: '0PX'
      },
      showMore: false,
      screenWidth: document.body.clientWidth, //屏幕宽度
      dataList: []
    }
  },
  created() {
    this.dataList = this.queryFormItems
    // 处理当日期类型为pickerOptionDate的组件 该组件要有默认值 遂在此添加
    let arr = this.dataList.find(p => p.type === 'pickerOptionDate')
    if (arr && arr.value) {
      let endDate = new Date()
      let start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      let eDate =
        endDate.getFullYear() +
        '-' +
        (endDate.getMonth() + 1) +
        '-' +
        endDate.getDate() +
        ' 23:59:59'
      let sDate =
        start.getFullYear() +
        '-' +
        (start.getMonth() + 1) +
        '-' +
        start.getDate() +
        ' 00:00:00'
      arr.value = [sDate, eDate]
    }
  },
  mounted() {
    this.updateForm()
    // this.dataList = JSON.parse(JSON.stringify(this.queryFormItems))
    // 该方法是从handleOptionsMixin引入的 用于处理下拉框数据
    this.handleQueryOptions()
    window.addEventListener(
      'resize',
      tools.debounce(this.watchWidth, 300),
      false
    )
    this.watchWidth()
  },
  beforeDestroy() {
    window.removeEventListener('resize', tools.debounce(this.watchWidth, 300))
  },
  computed: {
    formList: function () {
      let arr = []
      let data = this.dataList.filter(p => p.visible || p.visible === undefined)
      if (data.length > 6) arr = this.showMore ? data : data.slice(0, 6)
      else arr = data
      return arr
    },
    collapseList: function () {
      let arr = []
      let data = this.dataList.filter(p => p.visible || p.visible === undefined)
      if (this.screenWidth < 1920 && data.length > 4) arr = data.slice(4)
      if (this.screenWidth >= 1920 && data.length > 6) arr = data.slice(6)
      return arr
    },
    hasCollapseVal: function () {
      let isTure = false
      if (this.collapseList.length) {
        isTure = this.collapseList.some(p => {
          if (typeof p.value === 'string') return p.value !== ''
          if (typeof p.value === 'boolean') return p.value !== ''
          if (Array.isArray(p.value)) return p.value.length
        })
      }
      return isTure
    }
  },
  methods: {
    //
    buttonClick(arg) {
      switch (arg.id) {
        case 'check':
          this.search()
          break
        case 'reset':
          this.reset()
          break
        default:
          break
      }
    },
    handleQueryOptions() {
      this.handleOptions(this.dataList)
    },
    // 重置数据
    reset() {
      this.dataList.forEach(p => {
        if (typeof p.value === 'string' || typeof p.value === 'boolean')
          p.value = ''
        if (Array.isArray(p.value)) p.value = []
        if (p.type == 'rangeInput' && p[this.RANGE_OPTION].length) {
          p[this.RANGE_OPTION][0].value = ''
          p[this.RANGE_OPTION][1].value = ''
        }
        // else {
        //   p.value = ''
        // }
      })
      this.updateForm()
      console.log(this.dataList)
      this.moreVisible = false
    },
    // 搜索
    search() {
      this.check()
      this.$emit('collapse-search')
      this.moreVisible = false
    },
    // 监听窗口宽度变化
    watchWidth() {
      this.screenWidth = document.body.clientWidth
      if (
        this.screenWidth >= 1920 &&
        this.dataList.length <= 6 &&
        this.dataList.length > 4
      )
        this.showMore = false
    },
    check() {
      this.$emit('check')
    },
    hidepopover() {
      this.$emit('hide-popover')
    },
    // 显示更多
    showMoreEvent() {
      this.showMore = !this.showMore
    },
    // 更新组装表单数据
    updateForm(val, item) {
      // this.$nextTick(()=>{
      var obj = {}
      if (this.dataList.length) {
        this.dataList.forEach(p => {
          // 组装输入框类型为matchInput的数据
          if (p.type == 'matchInput' && p[this.MATCH_TYPE]) {
            obj[p[this.MATCH_TYPE].name] = p[this.MATCH_TYPE].value
          }
          // 组装输入框类型为rangeInput的数据
          if (p.type == 'rangeInput' && p[this.RANGE_OPTION].length) {
            obj[p[this.RANGE_OPTION][0].name] = p[this.RANGE_OPTION][0].value
            obj[p[this.RANGE_OPTION][1].name] = p[this.RANGE_OPTION][1].value
          }
          // 组装输入框类型为daterange,pickerOptionDate,datetimerange的数据
          if (
            p.type == 'daterange' ||
            p.type == 'pickerOptionDate' ||
            (p.type === 'datetime' && p.dateType === 'datetimerange')
          ) {
            let name = p.name.split('--'),
              isTrue = p.value && p.value.length
            obj[name[0]] = isTrue ? p.value[0] : ''
            obj[name[1]] = isTrue ? p.value[1] : ''
          }
          obj[p.name] = p.value
        })
      }
      // 去除多余的属性
      let arr = ['rangeInput', 'daterange', 'pickerOptionDate']
      this.dataList
        .filter(
          p =>
            arr.includes(p.type) ||
            (p.type === 'datetime' && p.dateType === 'datetimerange')
        )
        .forEach(p => {
          delete obj[p.name]
        })
      this.$emit('query-update-form', obj, val, item)
      // })
    }
  }
}
</script>
<style>
.query_form_show_more_pop {
  padding: 12px 0;
}
</style>
<style lang="less" scoped>
.show_more_wrapper {
  /deep/ .el-input__inner {
    border-radius: 6px;
  }
}
.query_show_more_box {
  width: 32px;
  height: 32px;
  background: #fff;
  border: 1px solid #d2d2d7;
  border-radius: 6px !important;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  svg {
    width: 16px;
    height: 16px;
  }
}
.btn_change_border {
  border: 1px solid #fc6510;
}
.show_more_bottom {
  margin-top: 12px;
  padding: 12px 12px 0 12px;
  text-align: center;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  .bottom_btn {
    border-radius: 6px;
    height: 32px;
    width: 60px;
    line-height: 0;
  }
}

.form_item_list_box {
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.form_item_show_more {
  padding: 0 12px 6px 12px;
}
.show_more_item {
  margin: 12px 12px 0 12px;
  /deep/ .el-checkbox-group {
    display: flex;
    flex-direction: column;
    .el-checkbox:first-child {
      margin-top: 10px;
    }
    .el-checkbox {
      margin-bottom: 18px;
    }
  }
}

.query_form_set_col_margin {
  margin: 10px 0;
  .btn {
    border-radius: 6px;
    height: 32px;
    line-height: 0;
  }
  .btn {
    white-space: nowrap;
  }
  .search_btn_list {
    display: flex;
    align-items: center;
    span {
      display: flex;
      align-items: center;
      /deep/ .el-popover__reference-wrapper {
        height: 32px;
      }
    }
    .query_form_wrapper {
      display: flex;
      flex-direction: column;
    }
    .btn_item {
      margin-right: 10px;
    }
  }
}
// 关闭按钮样式
.common_close {
  color: #909399;
}
.common_close:hover {
  color: #fff;
  border-radius: 50%;
  padding: 2px;
  background: rgba(0, 0, 0, 0.25);
}
</style>
