<template>
  <div id="detail">
    <detail-frame :title="mainTitle" returns="/classes/index">
      <data-form v-loading="loading" :data="info" :fields="fields" :rules="rules" @save="handleSave" :isNew="isNew"> </data-form>
    </detail-frame>
  </div>
</template>

<script>
import detailFrame from '@frame/layout/admin/detail-frame';
import dataForm from '@frame/components/form';
import { createNamespacedHelpers } from 'vuex';
const { mapActions } = createNamespacedHelpers('classes');
export default {
  metaInfo: { title: '班级信息' },
  name: 'detail',
  props: {},
  components: {
    detailFrame,
    dataForm,
  },
  data: () => ({
    loading: true,
    info: {},
    fields: [
      { label: '班级名称', required: true, model: 'name' },
      { label: '人数', required: true, model: 'number' },
      { label: '批次', required: true, model: 'batch', type: 'select' },
    ],
    rules: {
      name: [{ required: true, message: '请输入班级名称' }],
      number: [{ required: true, message: '请输入人数' }],
      batch: [{ required: true, message: '请输入批次' }],
    },
  }),
  created() {},
  computed: {
    id() {
      return this.$route.query.id;
    },
    isNew() {
      return this.$route.query.id ? false : true;
    },
    mainTitle() {
      let meta = this.$route.meta;
      let main = meta.title || '';
      let sub = meta.sub || '';
      return `${main}${sub}`;
    },
    keyWord() {
      let meta = this.$route.meta;
      let main = meta.title || '';
      return main;
    },
  },
  watch: {
    isNew: {
      immediate: true,
      handler(val) {
        if (val) this.loading = false;
        else this.search();
      },
    },
  },
  methods: {
    ...mapActions(['fetch', 'create', 'update']),
    async search() {
      const res = await this.fetch(this.id);
      if (this.$checkRes(res)) this.$set(this, `info`, res.data);
      this.loading = false;
    },
    async handleSave({ isNew, data }) {
      let res;
      let msg;
      console.log(isNew);
      if (isNew) {
        res = await this.create(data);
        console.log(res);
        msg = `${this.keyWord}添加成功`;
      } else {
        res = await this.update(data);
        msg = `${this.keyWord}修改成功`;
      }
      if (this.$checkRes(res, msg)) this.$router.push({ path: '/classes/index' });
    },
  },
};
</script>

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