<template>
  <div class="main">
    <div class="form-tips">{{ page.tips }}</div>
    <v-form
      ref="form"
      :model="formModel"
      :fields="page.form.fields"
      @submit="onSubmit"
    ></v-form>
    <div class="fixed-box">
      <div class="fixed-inner">
        <div class="fixed-button" @click="handleSubmit">提交</div>
      </div>
    </div>
  </div>
</template>

<script>
import pages from '@/pages'
import VForm from '@/components/Form'
import * as api from '@/api/index'

export default {
  name: 'Edit',
  components: { VForm },
  metaInfo() {
    return {
      title: this.page.title
    }
  },
  data() {
    return {
      formModel: {}
    }
  },
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler(route) {
        if (!route.query.channel) {
          this.$dialog
            .alert({
              message: '请选择事务'
            })
            .then(() => {
              this.$router.replace({
                name: 'index',
                query: this.$route.query
              })
            })
        }
      }
    }
  },
  computed: {
    // 页面配置
    page() {
      const channel = this.$route.query.channel
      return pages[channel] ? pages[channel]['edit'] : {}
    },
    channelId() {
      return this.$route.query.channel_id
    },
    viewId() {
      return this.$route.query.view_id
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.form.submit()
    },
    onSubmit(data) {
      data.affair_id = this.channelId
      if (data.payment_instrument) {
        const [first = { url: '' }] = data.payment_instrument
        data.payment_instrument = first.url
      }
      api.updateAffair(this.viewId, data).then(response => {
        if (response.success) {
          this.$dialog
            .alert({ confirmButtonText: '确定', message: '修改成功' })
            .then(() => {
              this.$router.push({ name: 'list', query: this.$route.query })
            })
        } else {
          this.$toast(response.message)
        }
      })
    },
    getDetail() {
      const toast = this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      })
      api
        .getAffair(this.viewId)
        .then(response => {
          this.formModel = response.form
          toast.clear()
        })
        .catch(toast.clear)
    }
  },
  beforeMount() {
    this.getDetail()
  }
}
</script>

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