<template>
  <div v-if="form">
    <main-top></main-top>
    <editcon
      :key="type"
      ref="child"
      :type="type"
      :rule="rule"
      :form="form"
      @cancel="backList"
      @save="save"
    >
      <template slot-scope="{ form }" slot="content">
        <component :data="form" :is="cp" :roleList="roleList" />
      </template>
    </editcon>
  </div>
</template>

<script>
import vdetail from "./componets/detail";

import { formKey, rules } from "./data";
import { save, getDetail } from "@/configue/api";

export default {
  name: "Edit",
  components: {
    vdetail,
  },
  data() {
    let { type, id } = this.$route.params;
    return {
      val: "exhibition",
      type,
      id: String(id),
      form: "",
      roleList: [],
    };
  },
  computed: {
    cp() {
      return "v" + this.type;
    },
    rule() {
      return rules[this.type];
    },
  },
  mounted() {
    this.getDetail();
  },
  methods: {
    validate(cb) {
      let child = this.$refs.child;
      child.$refs[this.type].validate(async (valid) => {
        if (valid) {
          cb();
        }
      });
    },
    cancel() {
      this.$router.back();
    },
    save(submit = "", cb = null) {
      this.validate(() => {
        let params = {
          description: "",
          fileName: "",
          filePath: "",
          museumId: 0,
          name: "",
          thumb: "",
          type: "",
          id: this.id == "none" ? null : this.id,
          ...this.form,
          timeEnd: this.form.type == "temp" ? this.form.opening[1] : null,
          timeStart: this.form.type == "temp" ? this.form.opening[0] : null,
        };
        save(this.val, params, () => {
          if (submit) {
            cb && cb();
          } else {
            this.$alert("编辑成功", "提示", {
              confirmButtonText: "确定",
              callback: () => {
                this.backList();
              },
            });
          }
        });
      });
    },

    async getDetail() {
      if (this.id == "none") {
        this.form = this.cloneObject(formKey[this.$route.params.type]);
      } else {
        await getDetail(this.val, { id: this.id }, (res) => {
          let opening = [res.data.timeStart, res.data.timeEnd];
          this.form = { ...this.form, ...res.data, opening };

          console.log(res);
        });
      }
    },
  },
};
</script>
