<template>
  <div>
    <el-dialog
      v-el-drag-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="60%"
    >
      <el-form ref="form" v-loading="loading" class="form-full" :model="formItem" label-width="120px" label-suffix=" : " />
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">{{ $t('ec.table.close') }}</el-button>
        <el-button v-if="method !== 'view'" type="primary" :loading="saveLoading" @click="save">{{ $t('ec.table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import { findByPrimaryKey, save, update } from 'ecip-web/api/web/stat/visit/ecipVisitStatApi'

export default {
  name: 'WebStatVisitEcipVisitStatForm',
  components: {},
  data() {
    return {
      visible: false,
      loading: false, // 页面加载遮罩
      saveLoading: false, //  保存加载
      method: '',
      title: '',
      record: {},
      formItem: {
      }
    }
  },
  methods: {
    init(method, record) {
      Object.assign(this.$data, this.$options.data())

      this.method = method
      this.record = record
      if (method === 'add') {
        this.title = this.$t('ec.table.add')
      } else if (method === 'edit') {
        this.title = this.$t('ec.table.edit')
      } else if (method === 'view') {
        this.title = this.$t('ec.table.view')
      }
      this.visible = true
      this.loading = false
      this.$nextTick(async() => {
        this.$refs.form.clearValidate()
        if (method === 'edit' || method === 'view') { // 修改或者查看
          this.loading = true
          const { data } = await findByPrimaryKey(record.id)
          this.formItem = Object.assign({}, this.formItem, data)
          this.loading = false
        }
      })
    },
    save() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            this.saveLoading = true
            if (this.method === 'edit') {
              await update(this.record.id, this.formItem)
            } else {
              await save(this.formItem)
            }
            this.$notify.success(this.$t('ec.message.saveSuccess'))
            this.$emit('refreshData')
            this.visible = false
          } finally {
            this.saveLoading = false
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
