<template>
  <div class="ws-data-expand-list">
    <div
      v-if="searchMode"
      class="search-section"
    >
      <WsSearchInput
        @submit="$_onSearchSubmit()"
        v-model="searching"
        :placeholder="`搜尋${label}`"
      ></WsSearchInput>
      <WsBtn @click="$_onSearchSubmit()">搜尋</WsBtn>
    </div>
    <div
      v-if="fetchLoading"
      class="mt-5"
    >
      <v-skeleton-loader
        v-for="n in 3"
        :key="`skeleton-${n}`"
        type="list-item-three-line"
        :tile="true"
        class="mt-5"
      ></v-skeleton-loader>
    </div>
    <div
      v-else
      class="ws-data-expand-list__content"
    >
      <div
        v-if="modelDatas"
        class="ws-data-expand-list__title"
      >{{label}} 共 {{modelDatas.length}} 筆</div>
      <WsDataExpandListItem
        v-for="(modelData,modelDataKey) in modelDatas"
        :key="modelDataKey"
        :modelName="modelName"
        :titleKey="titleKey"
        :modeVersions="modeVersions"
        :value="modelData"
        :fields="fields"
        :fieldsRead="fieldsRead"
        :locale="locale"
        @delete="$_onDelete($event)"
        @update-submit="$_onUpdateSubmit($event)"
      ></WsDataExpandListItem>
    </div>
    <WsCard v-if="createModeActive">
      <ValidationObserver ref="form">
        <v-form
          ref="createForm"
          @submit.prevent
        >
          <div class="ws-content">
            <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"
                  :displayLabel="field.displayLabel"
                  :rules="field.rules"
                  :uploadUrl="field.uploadUrl"
                  :autofocus="field.autofocus"
                  :getText="field.getText"
                  :items="field.items"
                  :modelName="field.modelName"
                  v-model="createData[fieldKey]"
                />
              </v-col>
            </v-row>
          </div>
        </v-form>
      </ValidationObserver>
      <v-divider></v-divider>
      <v-card-actions class="pa-5">
        <v-spacer></v-spacer>
        <WsBtn
          @click="$_onCreateCancel()"
          minWidth="100px"
          color="textSecondary"
          outlined
        >取消</WsBtn>
        <WsBtn
          @click="$_onCreateSubmit()"
          minWidth="100px"
          :loading="createSubmitLoading"
          color="primary"
        >儲存</WsBtn>
      </v-card-actions>
    </WsCard>
    <div
      v-else
      class="ws-button-group"
    >
      <WsBtn
        @click="$_createOpen()"
        color="primary"
        outlined
      >
        <v-icon left>mdi-plus</v-icon> 單筆新增{{label}}
      </WsBtn>
      <WsBtn
        v-show="batchMode"
        :to="`${_batchLink}?redirect=${$route.fullPath}`"
        color="primary"
      >前往批次上傳模式</WsBtn>
    </div>
  </div>
</template>

<script>
export default {
  data: () => ({
    searching: "",
    modelDatas: null,
    createModeActive: false,
    createData: {},
    createSubmitLoading: false,
    fetchLoading: false,
  }),
  methods: {
    $_onSearchSubmit() {
      this.fetchData();
    },
    $_onUpdateSubmit() {
      this.fetchData();
    },
    $_onDelete($event) {
      const tarIndex = this.modelDatas.findIndex((e) => {
        return e.id == $event;
      });
      this.modelDatas.splice(tarIndex, 1);
    },
    $_onCreateCancel() {
      this.createModeActive = false;
    },
    async $_onCreateSubmit() {
      const isValidate = await this.$refs.form.validate();
      if (!isValidate) {
        return;
      }
      try {
        this.createSubmitLoading = true;
        const postUrl =
          this.parentState && this.parentModelName
            ? `/${this.parentModelName}/${this.parentState}/${this.modelName}`
            : `/${this.modelName}`;
        const postData = JSON.parse(JSON.stringify(this.createData));
        const res = await this.$axios.post(postUrl, postData);
        this.createModeActive = false;
        if (this.modeVersions) {
          try {
            await this.$axios.post(
              `/${this.modelName}/${res.data.data.id}/${this._versionModelName}`,
              this.createData.last_version
            );
            this.createSubmitLoading = false;
            this.fetchData();
          } catch (error) {
            alert("新增錯誤");
            this.createSubmitLoading = false;
          }
        } else {
          this.createSubmitLoading = false;
          this.fetchData();
        }
      } catch (error) {
        alert("新增錯誤");
        this.createSubmitLoading = false;
      }
    },
    $_createOpen() {
      this.createModeActive = true;
    },
    async fetchData() {
      this.fetchLoading = true;
      try {
        const getUrl =
          this.parentState && this.parentModelName
            ? `/${this.parentModelName}/${this.parentState}/${this.modelName}`
            : `/${this.modelName}`;
        const params = {
          search: this.searching,
          lang: this.locale,
          order_by: this.orderBy,
          order_way: this.orderWay,
        };
        const res = await this.$axios.get(getUrl, {
          params: params,
        });
        this.modelDatas = res.data.data;
      } catch (error) {
        alert(error);
      } finally {
        this.fetchLoading = false;
      }
    },
  },
  computed: {
    _updateFields() {
      return this.$_CMS_geUpdateFields(this.fields);
    },
    _batchLink() {
      if (this.parentModelName && this.parentState) {
        return `/${this.parentModelName}/${this.parentState}/${this.modelName}/create/batch`;
      } else {
        return `/${this.modelName}/create/batch`;
      }
    },
    _versionModelName() {
      return `${this.modelName}_version`;
    },
  },
  props: {
    modeVersions: {
      type: Boolean,
      default: false,
    },
    batchMode: {
      type: Boolean,
      default: false,
    },
    searchMode: {
      type: Boolean,
      default: false,
    },
    locale: {
      type: String,
      default: null,
    },
    titleKey: {
      type: String,
      default: null,
    },
    modelName: {
      type: String,
      default: null,
    },
    label: {
      type: String,
      default: null,
    },
    parentModelName: {
      type: String,
      default: null,
    },
    parentState: {},
    fields: {
      type: Object,
      default: null,
    },
    fieldsRead: {
      type: Array,
      default: null,
    },
    orderBy: {
      type: String,
      default: "sequence",
    },
    orderWay: {
      type: String,
      default: "asc",
    },
  },
  mounted() {
    this.fetchData();
    this.$_CMS_updateDataSetFromFields(this, this.createData, this.fields);
  },
};
</script>

<style lang="scss">
@import "../assets/scss/ws-data-expand-list.scss";
</style>