<template>
  <WsCard class="ws-data-expand-list__item">
    <div
      v-if="!updateActive"
      @click="readContentToggle()"
      class="ws-data-expand-list__item__topbar"
    >
      <v-icon
        v-if="readActive"
        size="28"
        class="ws-data-expand-list__item__topbar__icon"
      >mdi-unfold-less-horizontal</v-icon>
      <v-icon
        v-else
        size="28"
        class="ws-data-expand-list__item__topbar__icon"
      >mdi-unfold-more-horizontal</v-icon>
      <div class="ws-data-expand-list__item__topbar__title">{{_title}}</div>
      <WsLineGroup>
        <WsIconBtn
          @click="$_onUpdateClick()"
          :size="38"
          tooltip="編輯"
        >mdi-pencil</WsIconBtn>
        <WsIconBtn
          v-show="modeVersions"
          :size="38"
          :to="`/${modelName}/${value.id}/version/create?redirect=${this.$route.fullPath}`"
          tooltip="更新法條版本"
        >mdi-update</WsIconBtn>
        <WsIconBtn
          v-show="modeVersions"
          :to="`/${modelName}/${value.id}/version`"
          :size="38"
          tooltip="查看版本列表"
        >mdi-book-open-variant</WsIconBtn>
        <WsIconBtn
          @click="$_onDelete(value.id)"
          :size="38"
          tooltip="刪除"
        >mdi-delete</WsIconBtn>
      </WsLineGroup>
    </div>
    <div
      v-if="readActive"
      class="ws-data-expand-list__item__content"
    >
      <v-row>
        <v-col
          v-for="(fieldKey,fieldIndex) in _displayFields"
          :key="fieldIndex"
          :cols="12"
          :sm="$_CMS_getFieldByFieldKey(fieldKey,fields).sm?$_CMS_getFieldByFieldKey(fieldKey,fields).sm:12"
        >
          <WsInfo
            :type="$_CMS_getFieldByFieldKey(fieldKey,fields).type"
            :label="$_CMS_getFieldByFieldKey(fieldKey,fields).label"
            :fields="$_CMS_getFieldByFieldKey(fieldKey,fields).fields"
            :textKey="$_CMS_getFieldByFieldKey(fieldKey,fields).textKey"
            :relationPopup="$_CMS_getFieldByFieldKey(fieldKey,fields).relationPopup"
            :modelName="$_CMS_getFieldByFieldKey(fieldKey,fields).modelName"
            :displayLabel="$_CMS_getFieldByFieldKey(fieldKey,fields).displayLabel"
            :getText="$_CMS_getFieldByFieldKey(fieldKey,fields).getText"
            :items="$_CMS_getFieldByFieldKey(fieldKey,fields).items"
            :value="$_CMS_getValueByFieldKey(fieldKey,value)"
            :locale="locale"
            :hideOnNull="true"
          ></WsInfo>
        </v-col>
      </v-row>
    </div>
    <!-- Delete Dialog -->
    <WsAlertDialog
      ref="deleteDialog"
      title="確定要刪除嗎？"
      description="刪除後資料將無法回覆"
      @submit="$_onDeleteSubmit($event)"
    />
    <template v-if="updateActive">
      <div class="ws-content no-border">
        <ValidationObserver ref="form">
          <v-form
            ref="createForm"
            @submit.prevent
          >
            <v-row>
              <v-col
                v-for="(field, fieldKey) in _updateFields"
                cols="12"
                :sm="field.sm ? field.sm : 12"
                :key="fieldKey"
              >
                <WsState
                  :type="field.type"
                  :label="field.label"
                  :fields="field.fields"
                  :rules="field.rules"
                  :displayLabel="field.displayLabel"
                  :uploadUrl="field.uploadUrl"
                  :autofocus="field.autofocus"
                  :items="field.items"
                  :textKey="field.textKey"
                  :modelName="field.modelName"
                  :getText="field.getText"
                  v-model="updateData[fieldKey]"
                  :originValue="value[fieldKey]"
                />
              </v-col>
            </v-row>
          </v-form>
        </ValidationObserver>
      </div>
      <v-divider></v-divider>
      <v-card-actions class="pa-5">
        <v-spacer></v-spacer>
        <WsBtn
          @click="$_onUpdateCancel()"
          minWidth="100px"
          color="textSecondary"
          outlined
        >取消</WsBtn>
        <WsBtn
          @click="$_onUpdateSubmit()"
          minWidth="100px"
          :loading="updateSubmitLoading"
          color="primary"
        >儲存</WsBtn>
      </v-card-actions>
    </template>
  </WsCard>
</template>

<script>
export default {
  data: () => ({
    readActive: false,
    updateActive: false,
    updateSubmitLoading: false,
    updateData: {},
  }),
  methods: {
    $_onUpdateCancel() {
      this.updateActive = false;
    },
    async $_onUpdateSubmit() {
      const isValidate = await this.$refs.form.validate();
      if (!isValidate) {
        return;
      }
      this.updateSubmitLoading = true;
      try {
        const postData = JSON.parse(JSON.stringify(this.updateData));
        // delete postData.versions;
        const res = await this.$axios.patch(
          `/${this.modelName}/${this.value.id}`,
          postData
        );
        if (this.fields.last_version) {
          if (this.value.last_version) {
            try {
              await this.$axios.patch(
                `/${this._versionModelName}/${this.value.last_version.id}`,
                this.updateData.last_version
              );
              this.updateSubmitLoading = false;
              this.$store.dispatch("app/stopNeedSave");
              this.updateActive = false;
              this.$emit("update-submit", {
                ...this.updateData,
                id: this.value.id,
              });
            } catch (error) {
              this.updateSubmitLoading = false;
              this.$store.dispatch("app/stopNeedSave");
              alert("更新錯誤");
            }
          } else {
            try {
              await this.$axios.post(
                `/${this.modelName}/${res.data.data.id}/${this._versionModelName}`,
                this.updateData.last_version
              );
              this.updateSubmitLoading = false;
              this.$store.dispatch("app/stopNeedSave");
              this.updateActive = false;
              this.$emit("update-submit", {
                ...this.updateData,
                id: this.value.id,
              });
            } catch (error) {
              this.updateSubmitLoading = false;
              this.$store.dispatch("app/stopNeedSave");
              alert("更新錯誤");
            }
          }
        } else {
          this.updateSubmitLoading = false;
          this.$store.dispatch("app/stopNeedSave");
          this.updateActive = false;
          this.$emit("update-submit", {
            ...this.updateData,
            id: this.value.id,
          });
        }
      } catch (error) {
        alert("更新錯誤");
        this.updateSubmitLoading = false;
      }
    },
    $_onUpdateClick() {
      this.$_CMS_updateDataSetFromFields(
        this,
        this.updateData,
        this.fields,
        this.value
      );
      this.readActive = false;
      this.updateActive = true;
      setTimeout(() => {
        this.isMounted = true;
      }, 0);
    },
    $_onDelete($event) {
      this.$refs.deleteDialog.open($event);
    },
    async $_onDeleteSubmit($event) {
      this.$refs.deleteDialog.startLoading();
      try {
        await this.$axios.delete(`/${this.modelName}/${$event}`);
        this.$emit("delete", $event);
      } catch (error) {
        alert(error);
      } finally {
        this.$refs.deleteDialog.close();
      }
    },
    readContentToggle() {
      this.readActive = !this.readActive;
    },
  },
  computed: {
    _displayFields() {
      const _displayFields = [];
      this.fieldsRead.forEach((fieldKey) => {
        const _value = this.$_CMS_getValueByFieldKey(fieldKey, this.value);
        if (!(_value == undefined || _value.length == 0)) {
          _displayFields.push(fieldKey);
        }
      });
      return _displayFields;
    },
    _updateFields() {
      return this.$_CMS_geUpdateFields(this.fields);
    },
    _versionModelName() {
      return `${this.modelName}_version`;
    },
    _title() {
      return this.$_CMS_getValueByFieldKey(this.titleKey, this.value);
    },
  },
  props: {
    modeVersions: {
      type: Boolean,
      default: false,
    },
    modelName: {
      type: String,
      default: null,
    },
    locale: {
      type: String,
      default: "name",
    },
    titleKey: {
      type: String,
      default: "name",
    },
    value: {
      type: Object,
      default: null,
    },
    fields: {
      type: Object,
      default: null,
    },
    fieldsRead: {
      type: Array,
      default: null,
    },
  },
  watch: {
    updateData: {
      handler() {
        if (this.isMounted) {
          this.$store.dispatch("app/startNeedSave");
        }
      },
      deep: true,
    },
  },
};
</script>