<template>
  <el-form
    class="save-form"
    v-bind="{...$attrs, ...$props}"
    v-on="$listeners"
    @submit.stop.native="submit"
    @reset.stop.native="reset"
    ref="form"
  >
    <slot/>
  </el-form>
</template>
<script>
import { Searchs } from '@/helpers'
export default {
  name: 'save-form',
  props: ['model', 'save-key'],
  data() {
    return {
      searchs: null
    }
  },
  mounted() {
    const searchs = new Searchs(this.saveKey || this.$route.path)
    this.searchs = searchs
    const active = searchs.get()
    for (const key in active.form) {
      if (active.form.hasOwnProperty(key)) {
        const item = active.form[key]
        this.model[key] = item
      }
    }
    if (this.saveKey) {
      this.searchs.update(this.$route.path, undefined, 'bind')
    }
  },
  methods: {
    submit(evt) {
      evt.stopPropagation()
      evt.stopImmediatePropagation()
      evt.preventDefault()
      this.searchs.update(this.model, undefined, 'form')
      if (this.$listeners.submit) {
        this.$listeners.submit(evt)
      }
    },
    reset() {
      if (this.$listeners.reset) {
        this.$listeners.reset()
        this.$nextTick(() => {
          this.resetFields()
        })
      } else {
        this.resetFields()
      }
    },
    save(search = null, type = 'form') {
      search = search ? search : this.model
      this.searchs.update(search, undefined, type)
    },
    validate(FC) {
      this.$refs.form.validate(valid => {
        FC(valid)
        if (valid) {
          this.searchs.update(this.model, undefined, 'form')
        }
      })
    },
    resetFields() {
      this.$refs.form.resetFields()
      this.searchs.update(this.model, undefined, 'form')
      this.searchs.update({}, undefined, 'page')
    }
  },
}
</script>
<style lang="less" scoped>
.save-form{
  /deep/ .el-input__inner{
    width: 180px;
  }
  /deep/ .el-form-item__content .el-col {
    width: 180px;
  }
  /deep/ .el-col.line{
    width: 15px!important;
    text-align: center;
  }
  /deep/ .el-date-editor--daterange{
    width: 375px;
  }
  /deep/ .el-form-item__content .el-col:last-child .el-form-item{
    margin-right: 0;
  }
}

</style>
