<template>
  <div class="flexConatiner flexColumn">
    <div>
      <section class="message">
        <search
          :data="gridSetting"
          :service-name="serviceName"
          :method-name="methodName"
          @grid-search="searchData"
        />
      </section>
    </div>
    <div class="flexItems flexRow">
      <div class="flexItem is-8 noChild">
        <section class="message">
          <div class="message-header level">
            <p class="level-left">
              {{ boardName }}
            </p>
          </div>
          <div
            class="message-body"
            width="100%"
          >
            <span v-if="editableGrid == 'false'">
              <common-grid
                :headers="grid[0].headers"
                :grid-data="grid[0].data"
                :name="grid[0].name"
                @grid-click="gridClick"
              />
            </span>
            <span v-else>
              <check-grid
                ref="checkGrid"
                :grid-setting="gridSetting"
                :grid-data="grid[0].data"
                @grid-clicked="gridClick"
                @grid-checked="gridChecked"
              />
            </span>
          </div>
          <b-loading
            :is-full-page="isFullPage"
            :active.sync="isLoading"
            :can-cancel="true"
          >
            <b-icon
              pack="fas"
              icon="sync-alt"
              size="is-large"
              custom-class="fa-spin"
            />
          </b-loading>
        </section>
      </div>
      <div class="flexItem is-4 noChild">
        <property
          ref="props"
          :data="propsSetting"
          :primary-key="this.keyData"
          :service-name="serviceName"
          :method-name="methodName"
          @grid-create="createData"
          @grid-modify="modifyData"
          @grid-delete="deleteData"
        />
      </div>
    </div>
  </div>
</template>

<script>
import checkGrid from './CheckableGrid.vue';
import property from './Property.vue';

export default {
  components: {
    checkGrid,
    property,
  },
  props: {
    propsSetting: Array,
    gridSetting: Array,
    serviceUrl: String,
    serviceName: String,
    boardName: String,
    methodName: String,
    editableGrid: String,
  },
  data() {
    return {
      checkedRows: [],
      clickRows: {},
      chkGridCnt: 0,
      writeMode: 'read',
      dashboard: [
        {
          postNum: 0,
          boardName: '',
          title: '',
          createUser: '',
          createTime: '',
          hits: 0,
          contents: '',
        },
      ],
      isLoading: false,
      isFullPage: true,
      keyData: [],
      grid: [
        {
          headers: this.gridSetting,
          data: [{}],
        },
      ],
    };
  },
  mounted() {
    this.init();
    this.keySetting();
  },
  methods: {
    init() {
      this.dashboard[0] = {};
      this.dashboard[0].boardName = this._props.boardName;
      // this.dashboard[0].boardName = this.boardName;
      this.getGridData(null);
      if (this._props.editableGrid !== 'false') {
        this.$refs.checkGrid.resetCheckedRows();
      }
    },
    gridClick(value) {
      if (this._props.editableGrid === 'false') {
        this.dashboard[0] = value;
      }
      this.$refs.props.gridClick(value);
    },
    getGridData() {
      const basePath = this.serviceUrl;
      this.dashboard[0].boardName = this._props.boardName;
      if (this.dashboard[0].boardName == null) {
        // console.log("잘못된 게시판입니다");
      } else {
        this.isLoading = true; // 로딩 부분 시작지점
        this.$service
          .read(`${basePath}/getDashboard`, this.dashboard[0])
          .then(({ data }) => {
            this.grid[0].data = data;
          })
          .catch(() => {
            // console.log(error);
          })
          .finally(() => {
            this.isLoading = false; // 로딩 부분 닫아주기
          });
      }
    },
    getContents(value) {
      const basePath = this.serviceUrl;
      this.dashboard[0] = value;
      this.isLoading = true; // 로딩 부분 시작지점
      this.$service
        .read(`${basePath}/getContents`, this.dashboard[0])
        .then(({ data }) => {
          this.grid[0].data = data;
        })
        .catch(() => {
          // console.log(error);
        })
        .finally(() => {
          this.isLoading = false; // 로딩 부분 닫아주기
        });
    },
    searchData(value) {
      const basePath = this.serviceUrl;
      this.dashboard[0] = value;
      this.dashboard[0].boardName = this._props.boardName;
      this.isLoading = true; // 로딩 부분 시작지점
      this.$service
        .read(`${basePath}/getDashboard`, this.dashboard[0])
        .then(({ data }) => {
          this.grid[0].data = data;
        })
        .catch(() => {
          // console.log(error);
        })
        .finally(() => {
          this.isLoading = false; // 로딩 부분 닫아주기
        });
    },
    createData(value) {
      const basePath = this.serviceUrl;
      this.dashboard[0] = value;
      this.dashboard[0].boardName = this._props.boardName;
      this.isLoading = true; // 로딩 부분 시작지점
      this.$service
        .create(`${basePath}/createDashboard`, this.dashboard[0])
        .then(({ data }) => {
          if (data === 'success') {
            this.$emit('create-success');
            this.$buefy.dialog.alert({
              message: '작업에 성공하였습니다.',
              type: 'is-success',
            });
          } else if (data === 'fail') {
            this.$buefy.dialog.alert({
              message: '작업에 실패하였습니다.',
              type: 'is-danger',
            });
          } else {
            this.$emit('valid-check', data);
          }
        })
        .catch((error) => {
          // console.log(error);
          this.$buefy.dialog.alert({
            message: '작업에 실패하였습니다.',
            type: 'is-danger',
            detail: error,
          });
        })
        .finally(() => {
          this.init();
          this.isLoading = false; // 로딩 부분 닫아주기
        });
    },
    modifyData(value) {
      const basePath = this.serviceUrl;
      this.dashboard[0] = value;
      this.dashboard.boardName = this._props.boardName;
      this.isLoading = true; // 로딩 부분 시작지점
      this.$service
        .modify(`${basePath}/modifyDashboard`, this.dashboard[0])
        .then(({ data }) => {
          if (data === 'success') {
            this.$emit('create-success');
            this.$buefy.dialog.alert({
              message: '작업에 성공하였습니다.',
              type: 'is-success',
            });
          } else if (data === 'fail') {
            this.$buefy.dialog.alert({
              message: '작업에 실패하였습니다.',
              type: 'is-danger',
            });
          } else {
            this.$emit('valid-check', data);
          }
        })
        .catch((error) => {
          // console.log(error);
          this.$buefy.dialog.alert({
            message: '작업에 실패하였습니다.',
            type: 'is-danger',
            detail: error,
          });
        })
        .finally(() => {
          this.init();
          this.isLoading = false; // 로딩 부분 닫아주기
        });
    },
    deleteData() {
      const basePath = this.serviceUrl;
      if (this.chkGridCnt < 1 && this._props.editableGrid !== 'false') {
        this.$buefy.dialog.alert({
          message: '삭제 할 데이터를 선택하세요.',
          type: 'is-danger',
        });
      } else {
        this.isLoading = true; // 로딩 부분 시작지점
        for (let i = 0; i < this.dashboard.length; i += 1) {
          this.$service
            .delete(`${basePath}/deleteDashboard`, this.dashboard[i])
            .then(({ data }) => {
              if (data === 'codeNull') {
                this.$buefy.dialog.alert({
                  message: '삭제 할 데이터를 선택하세요.',
                  type: 'is-danger',
                });
              } else if (data === 'success') {
                if (i === this.dashboard.length - 1) {
                  this.$emit('create-success');
                  this.$buefy.dialog.alert({
                    message: '작업에 성공하였습니다.',
                    type: 'is-success',
                  });
                }
              } else if (data === 'fail') {
                this.$buefy.dialog.alert({
                  message: '작업에 실패하였습니다..',
                  type: 'is-danger',
                });
              }
            })
            .catch(() => {
              // console.log(error);
            })
            .finally(() => {
              this.init();
              this.isLoading = false; // 로딩 부분 닫아주기
            });
        }
      }
    },
    keySetting() {
      for (let i = 0; i < this.propsSetting.length; i += 1) {
        if (this.propsSetting[i].group === 'key') {
          this.keyData.push(this.propsSetting[i].field);
        }
      }
    },
    gridChecked(value) {
      const params = value;
      this.chkGridCnt = params.length;
      this.checkedRows = {};
      if (params.length < 1) {
        this.dashboard = [];
      } else {
        this.dashboard = params;
        for (let i = 0; i < params.length; i += 1) {
          this.dashboard[i] = params[i];
        }
      }
    },
  },
};
</script>
