<!--
 * @Author: your name
 * @Date: 2020-10-21 14:22:25
 * @LastEditTime: 2021-02-04 15:46:01
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \dbadmin\src\components\HeaderQueryForm.vue
-->
<template>
  <div class="header-query__component">
    <el-form
      :model="form"
      :rules="rules"
      label-position="left"
      :label-width="labelWidth"
      :size="size"
      @keydown.enter.native.prevent="request"
      inline
      v-bind="$attrs"
    >
      <slot></slot>
      <el-button v-if="btn" type="primary" :size="size" @click="request">
        {{ queryLabel }}
      </el-button>
    </el-form>
  </div>
</template>

<script>
import { Component, Prop, Emit } from 'vue-property-decorator'
import Vue from 'vue'
import { getModule } from 'vuex-module-decorators'
import QueryStore, { DEFAULT_TAG as DEFAULT_QUERY_TAG } from '@/store/modules/query'

import store from '@/store'
const queryStore = getModule(QueryStore, store)

@Component({
  name: 'HeaderQuery'
})
export default class HeaderQuery extends Vue {
  @Prop({ type: String, default: DEFAULT_QUERY_TAG })
  tag

  @Prop({ type: Object, required: true })
  form

  @Prop({ type: Object, default: () => ({}) })
  rules

  @Prop({ type: String, default: 'mini' })
  size

  @Prop({ type: String, default: '查询' })
  queryLabel

  @Prop({ type: Boolean, default: true })
  btn

  @Prop({ type: Boolean, default: true })
  cache

  @Prop({ type: String, default: undefined })
  labelWidth

  pageData = null

  get storeData() {
    return queryStore.data[this.path][this.tag] || {}
  }

  set storeData(data) {
    queryStore.setData({ path: this.path, data, tag: this.tag })
  }

  get path() {
    return this.$route.path
  }

  get fetch() {
    return queryStore.fetchs[this.path][this.tag]
  }

  created() {
    queryStore.init({ tag: this.tag, path: this.path, initData: Object.assign({}, this.form) })
    this.pageData = queryStore.pageData[this.path][this.tag]
    this.emitUpdateQuery()
  }

  /**
   * 触发外部更新值
   */
  @Emit('update:form')
  emitUpdateQuery() {
    return Object.assign({}, this.storeData)
  }

  @Emit('submit')
  async request() {
    this.pageData.page = 1
    this.storeData = this.form
    this.fetch()
    return this.storeData
  }
}
</script>

<style lang="scss" scoped></style>
