<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="{}" @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: users } = createNamespacedHelpers('users');
export default {
  name: 'detail',
  props: {},
  components: {
    topInfo,
    dataForm,
  },
  data: function() {
    return {
      drawerIsNew: true,
      form: {},
      fields: [
        { label: '姓名', prop: 'name', model: 'name' },
        { label: '机构名称', prop: 'deptname', model: 'deptname' },
        { label: '手机号', prop: 'phone', model: 'phone' },
        { label: '密码', prop: 'password', model: 'password', type: 'password' },
      ],
    };
  },
  created() {},
  methods: {
    ...users(['fetch', 'create', 'update']),
    async search() {
      const res = await this.fetch(this.id);
      if (this.$checkRes(res)) this.$set(this, `form`, res.data);
    },
    // 创建&修改
    async drawerSave({ data, isNew }) {
      let res;
      let msg;
      if (this.isNew) {
        data.pid = this.user.uid;
        data.role = '4';
        res = await this.create(data);
        msg = '创建成功';
      } else {
        res = await this.update(data);
        msg = '修改成功';
      }
      this.$router.push({ path: '/adminUser/index' });
    },
  },
  computed: {
    ...mapState(['user']),
    id() {
      return this.$route.query.id;
    },
    isNew() {
      return this.$route.query.id ? false : true;
    },
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
  watch: {
    isNew: {
      handler(val) {
        if (!val) {
          this.search();
        }
      },
      immediate: true,
    },
  },
};
</script>

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