<template>
  <div
    class="ws-main"
    :style="[{'padding-bottom':'120px'}]"
  >
    <WsBreadCrumbs :items="_breadcrumbsItems"></WsBreadCrumbs>
    <WsTitle>新增{{label}}</WsTitle>
    <div class="ws-content-section">
      <ValidationObserver
        ref="form"
        class="ws-content-section-observer"
      >
        <v-form
          ref="createForm"
          @submit.prevent
        >
          <div class="ws-content-section">
            <div class="ws-content-section__primary">
              <WsStateContentBlock
                v-for="(item,itemKey) in primary"
                :key="itemKey"
                :type="item.type"
                :label="item.label"
                :title="item.title"
                :remark="item.remark"
                :floors="item.floors"
                :modedFields="_updateFields"
                :fields="item.fields"
                :field="item.field"
                :modelName="item.modelName"
                :modeVersions="item.modeVersions"
                :modeParent="item.modeParent"
                :customButtons="item.customButtons"
                :fieldsRead="item.fieldsRead"
                :updateData="createData"
                :parentModelName="$_getParentModelName(item)"
              ></WsStateContentBlock>
            </div>
            <div class="ws-content-section__secondary">
              <WsStateContentBlock
                v-for="(item,itemKey) in secondary"
                :key="itemKey"
                :type="item.type"
                :label="item.label"
                :title="item.title"
                :remark="item.remark"
                :floors="item.floors"
                :modedFields="_updateFields"
                :fields="item.fields"
                :field="item.field"
                :modelName="item.modelName"
                :modeVersions="item.modeVersions"
                :modeParent="item.modeParent"
                :customButtons="item.customButtons"
                :fieldsRead="item.fieldsRead"
                :updateData="createData"
                :parentModelName="$_getParentModelName(item)"
              ></WsStateContentBlock>
            </div>
          </div>
        </v-form>
      </ValidationObserver>
    </div>
    <WsMainBottomNav>
      <WsBtn
        @click="$router.go(-1)"
        color="textSecondary"
        outlined
      >取消</WsBtn>
      <WsBtn
        @click="$_onSubmit()"
        :loading="submitLoading"
      >送出</WsBtn>
    </WsMainBottomNav>
  </div>
</template>

<script>
export default {
  data: () => ({
    isMounted: false,
    parentModelData: null,
    createData: {},
    submitLoading: false,
  }),
  methods: {
    async $_onSubmit() {
      const isValidate = await this.$refs.form.validate();
      if (!isValidate) {
        return;
      }
      this.submitLoading = true;
      try {
        let postUrl;
        if (this.parentModelName && this.parentId) {
          postUrl = `/${this.parentModelName}/${this.parentId}/${this.modelName}`;
        } else {
          postUrl = `/${this.modelName}`;
        }
        const postData = JSON.parse(JSON.stringify(this.createData));
        const res = await this.$axios.post(postUrl, postData);
        if (this._updateFields.last_version) {
          try {
            await this.$axios.post(
              `/${this.modelName}/${res.data.data.id}/${this._versionModelName}`,
              this.createData.last_version
            );
            this.submitLoading = false;
            this.$store.dispatch("app/stopNeedSave");
            if (this.$route.query && this.$route.query.redirect) {
              this.$router.push(this.$route.query.redirect);
            } else {
              this.$router.push(`/${this.modelName}`);
            }
          } catch (error) {
            alert("版本儲存發生錯誤");
            this.submitLoading = false;
          }
        } else {
          this.$store.dispatch("app/stopNeedSave");
          if (this.$route.query && this.$route.query.redirect) {
            this.$router.push(this.$route.query.redirect);
          } else {
            this.$router.push(`/${this.modelName}`);
          }
        }
      } catch (error) {
        alert("儲存錯誤");
        this.submitLoading = false;
      }
    },
    $_getParentModelName(primaryItem) {
      if (primaryItem.modeVersions) {
        return `${this.modelName}_version`;
      } else {
        return this.modelName;
      }
    },
    async $_parentDetchData() {
      this.$store.dispatch("app/startPageLoading");
      let getUrl = `/${this.parentModelName}/${this.parentId}`;
      try {
        const res = await this.$axios.get(getUrl);
        this.parentModelData = res.data.data;
      } catch (error) {
        alert(error);
      } finally {
        this.$store.dispatch("app/stopPageLoading");
      }
    },
  },
  computed: {
    _parentTitle() {
      if (!this.parentModelName) {
        return null;
      } else if (!this.parentModelData) {
        return this.parentLabel;
      } else {
        return this.$_CMS_getValueByFieldKey(
          this.parentTitleKey,
          this.parentModelData
        );
      }
    },
    _breadcrumbsItems() {
      const _breadcrumbsItems = [];
      if (
        this.parentModelName &&
        this.parentId &&
        this.parentLabel &&
        this.parentTitleKey
      ) {
        _breadcrumbsItems.push({
          text: this.parentLabel,
          to: `/${this.parentModelName}`,
          disabled: false,
        });
        _breadcrumbsItems.push({
          text: this._parentTitle,
          to: `/${this.parentModelName}/${this.parentId}`,
          disabled: false,
        });
      }
      _breadcrumbsItems.push({
        text: `新增${this.label}`,
        disabled: true,
      });
      return _breadcrumbsItems;
    },
    _versionModelName() {
      return `${this.modelName}_version`;
    },
    _updateFields() {
      return this.$_CMS_geUpdateFields(this.fields);
    },
  },
  props: {
    parentTitleKey: {
      type: String,
      default: null,
    },
    parentLabel: {
      type: String,
      default: null,
    },
    parentId: {
      type: [String, Number],
      default: null,
    },
    parentModelName: {
      type: String,
      default: null,
    },
    primary: {
      type: Array,
      default() {
        return [];
      },
    },
    secondary: {
      type: Array,
      default() {
        return [];
      },
    },
    modelName: String,
    label: String,
    fields: Object,
  },
  mounted() {
    if (this.parentModelName && this.parentId) {
      this.$_parentDetchData();
    }
    this.$_CMS_updateDataSetFromFields(
      this,
      this.createData,
      this._updateFields
    );
    setTimeout(() => {
      this.isMounted = true;
    }, 0);
  },
  watch: {
    createData: {
      handler() {
        if (this.isMounted) {
          this.$store.dispatch("app/startNeedSave");
        }
      },
      deep: true,
    },
  },
};
</script>