<template>
  <div class="create-box">
    <app-card :title="!$route.query.id ? '新建模板' : '编辑模板'">
      <template v-if="$route.query.id">
        <stepTwo @submit="submit" v-if="Object.keys(step2Data).length" :data="step2Data"></stepTwo>
      </template>
      <template v-else>
        <stepTwo @submit="submit" :data="step2Data"></stepTwo>
      </template>
    </app-card>
  </div>
</template>

<script>
import stepTwo from '../components/stepTwo.vue'
import { createTemplate, getDetails, updateTemplate } from '../api'
export default {
  components: {
    stepTwo
  },
  data() {
    return {
      active: 0,
      form: {
        title: '',
        rule: '0'
      },
      step2Data: {},
      loading: null
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  created() {
    if (this.id) {
      this.loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.9)'
      })
    }
  },
  methods: {
    submit(data) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.9)'
      })
      if (this.$route.query.id) {
        data.id = this.$route.query.id
        updateTemplate(Object.assign(this.form, data))
          .then(res => {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.$router.go(-1)
            loading.close()
          })
          .catch(() => {
            loading.close()
          })
      } else {
        createTemplate(Object.assign({ title: this.$route.query.title, rule: this.$route.query.rule }, data))
          .then(res => {
            this.$message({
              message: '提交成功',
              type: 'success'
            })
            this.$router.go(-1)
            loading.close()
          })
          .catch(() => {
            loading.close()
          })
      }
    },
    getDetails() {
      getDetails({ id: this.id }).then(res => {
        const data = res.data
        this.form = {
          title: data.title,
          rule: '0' + data.rule
        }
        this.step2Data = JSON.parse(data.info)
        this.loading.close()
      })
    }
  },
  mounted() {
    if (this.id) {
      this.getDetails()
    }
  }
}
</script>

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