<template>
  <div id="detail">
    <el-row>
      <el-col :span="24" class="index">
        <el-col :span="24" class="top">
          <topInfo :topTitle="pageTitle"></topInfo>
        </el-col>
        <el-col :span="24" class="main">
          <data-form :fields="fields" :data="form" :rules="rules" @save="drawerSave" :isNew="drawerIsNew"> </data-form>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import topInfo from '@/layout/public/top.vue';
import dataForm from '@/components/form.vue';
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: role } = createNamespacedHelpers('role');
export default {
  name: 'detail',
  props: {},
  components: {
    topInfo,
    dataForm,
  },
  data: function() {
    return {
      drawerIsNew: true,
      form: {},
      fields: [
        { label: '菜单名称', prop: 'role_name', model: 'role_name' },
        // { label: '权限code', prop: 'code', model: 'code' },
        { label: '菜单路由', prop: 'url', model: 'url' },
      ],
      rules: {
        role_name: [{ required: true, message: '菜单名称' }],
        code: [{ required: false, message: '权限code' }],
        url: [{ required: true, message: '请输入菜单路由' }],
      },
    };
  },
  created() {},
  methods: {
    ...role(['query', 'delete', 'update', 'create', 'fetch']),
    async search() {
      let res = await this.fetch(this.id);
      this.$set(this, `form`, res.data);
    },
    // 创建&修改
    async drawerSave({ data, isNew }) {
      let res;
      let msg;
      if (this.isNew) {
        res = await this.create(data);
        msg = `${this.keyWord}添加成功`;
      } else {
        res = await this.update(data);
        msg = `${this.keyWord}修改成功`;
      }
      if (this.$checkRes(res, msg)) this.$router.push({ path: '/role/index' });
    },
  },
  computed: {
    id() {
      return this.$route.query.id;
    },
    isNew() {
      return this.$route.query.id ? false : true;
    },
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
    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;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
  watch: {
    isNew: {
      handler(val) {
        if (!val) {
          this.search();
        }
      },
      immediate: true,
    },
  },
};
</script>

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