<template>
  <section class="message">
    <form
      name="form"
      @submit.prevent="selectData"
    >
      <!-- Collapse시 padding 0 -->
      <div
        class="message-header level"
        :class="{'collapse-message': isCollapse}"
      >
        <p class="txt_primary level-left">
          <!-- Collapse 버튼 -->
          <!-- prop_collapse가 true일때만 랜더링 -->
          <!-- @click 이벤트 : collapse 유무 토글 -->
          <!-- collapse-btn : 버튼 테두리 제거 css -->
          <b-button
            v-if="collapse"
            class="collapse-btn"
            @click="isCollapse=!isCollapse"
          >
            {{ isCollapse ? '▼' : '▶' }}
          </b-button>
        </p>
        <!-- Collapse시 화면에서 숨김 -->
        <b-button
          v-show="!isCollapse"
          class="btn_search"
          native-type="submit"
        >
          <p>
            <img
              class="icon_search"
              src="../assets/icon/icon_search.png"
            >검색
          </p>
        </b-button>
      </div>
      <!-- Collapse시 화면에서 숨김 -->
      <div
        v-show="!isCollapse"
        class="message-body"
      >
        <b-field grouped>
          <b-field
            v-for="(item, index) in this.property.params"
            :key="index"
            :label="item.label"
            custom-class="search-style"
            expanded
          >
            <div v-if="item.search == 'Y'">
              <b-input
                v-if="item.fieldType == 'textbox'"
                v-model="search[item.field]"
                expanded
                type="search"
                custom-class="is-small"
              />
              <b-select
                v-if="item.fieldType == 'combobox'"
                v-model="search[item.field]"
                :placeholder="item.label"
                size="is-small"
                expanded
                @keypress.native.enter="enterPressEvent($event, item.field)"
              >
                <option
                  v-for="option in item.comboData"
                  :key="option.description"
                  :value="option.value"
                >
                  {{ option.description }}
                </option>
              </b-select>
              <check-combo
                v-if="item.fieldType == 'checkcombo'"
                :field-name="item.field"
                :service-name="serviceName"
                :method-name="methodName"
                @select="dropdownSelect"
              />
              <b-autocomplete
                v-if="item.fieldType == 'autocomplete'"
                v-model="name[item.field]"
                :data="item.comboData"
                custom-class="is-small"
                @focus="selectAutoData(item)"
                @typing="option(item)"
              >
                <template slot="empty">
                  No results found
                </template>
              </b-autocomplete>

              <date-picker
                v-if="item.fieldType == 'datetime'"
                v-model="search[item.field]"
                expanded
                :name="item.field"
                :today-btn-show="true"
                :init-date="initDate[item.field]"
                @selectedDate="selectDate"
              />
              <b-input
                v-if="item.fieldType == 'textarea'"
                v-model="search[item.field]"
                expanded
                type="textarea"
                minlength="0"
                maxlength="400"
              />
            </div>
          </b-field>
        </b-field>
      </div>
    </form>
  </section>
</template>

<script>
// import datePicker from './DatePicker.vue';

export default {
  // components: {
  //   datePicker,
  // },
  props: {
    data: {
      type: Array,
    },
    methodName: {
      type: String,
    },
    serviceName: {
      type: String,
    },
    autoComMethod: {
      type: String,
    },
    initSearchDate: {
      type: Object,
    },
    // collapse 버튼 추가 설정 유무
    collapse: {
      type: Boolean,
    },
  },
  data() {
    return {
      search: {},
      property: { params: [] },
      autoComData: [''],
      name: {},
      initDate: {},
      selectedIndex: {},
      // collapse 유무 flag
      isCollapse: false,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    enterPressEvent(e, field) {
      const index = e.target.selectedIndex;
      if (e.srcElement.selectedIndex !== -1 && this.selectedIndex[field] !== index) {
        e.preventDefault();
        this.selectData();
        this.selectedIndex[field] = index;
      }
    },
    selectDate(params) {
      if (params.id === 'startDate') {
        if (params.value == null || params.value === '') {
          this.search.startDate = new Date();
        } else {
          this.search.startDate = params.value;
        }
      } else if (params.id === 'endDate') {
        if (params.value == null || params.value === '') {
          this.search.endDate = new Date();
        } else {
          this.search.endDate = params.value;
        }
      }
    },
    init() {
      const tmp = [];
      for (let i = 0; i < this.data.length; i += 1) {
        if (this.data[i].search === 'Y') {
          tmp.push(this.data[i]);
        }
      }
      this.property.params = tmp;
      const servicePath = `/${this.serviceName}/${this.methodName}`;
      this.property.params.map((combo) => {
        if (combo.fieldType === 'combobox') {
          const param = { where: combo.where };
          this.$service.read(servicePath, param).then(({ data }) => {
            combo.comboData = data;
            combo.comboData.unshift({
              value: null,
              description: ' -- 선택 -- ',
            });
          });
        }
      });
      for (let i = 0; i < this.property.params.length; i += 1) {
        if (this.property.params[i].fieldType !== 'checkcombo') {
          this.search[this.property.params[i].field] = '';
        }
      }
      if (this._props.initSearchDate !== undefined) {
        let startDate = new Date();
        let endDate = new Date();
        startDate.setHours(0, 0, 0, 0);
        endDate.setHours(0, 0, 0, 0);
        if (this._props.initSearchDate.type === 'A') {
          startDate.setDate(
            startDate.getDate() + this._props.initSearchDate.startDate,
          );
          endDate.setDate(
            endDate.getDate() + this._props.initSearchDate.endDate,
          );
        } else if (this._props.initSearchDate.type === 'B') {
          startDate = (this._props.initSearchDate.startDate === '0'
            ? startDate
            : new Date(this._props.initSearchDate.startDate));
          endDate = (this._props.initSearchDate.endDate === '0'
            ? endDate
            : new Date(this._props.initSearchDate.endDate));
        }
        this.initDate.startDate = startDate;
        this.initDate.endDate = endDate;
      }
    },
    selectData() {
      let sDate = this.search.startDate == null || this.search.startDate === ''
        ? new Date()
        : new Date(this.search.startDate);
      const sDy = sDate.getFullYear();
      let sDm = sDate.getMonth() + 1;
      let sDd = sDate.getDate();

      if (sDm < 10) {
        sDm = `0${sDm}`;
      }
      if (sDd < 10) {
        sDd = `0${sDd}`;
      }
      sDate = `${sDy}-${sDm}-${sDd}`;
      this.search.startDate = sDate;

      let eDate = this.search.endDate == null || this.search.endDate === ''
        ? new Date()
        : new Date(this.search.endDate);
      const eDy = eDate.getFullYear();
      let eDm = eDate.getMonth() + 1;
      let eDd = eDate.getDate();

      if (eDm < 10) {
        eDm = `0${eDm}`;
      }
      if (eDd < 10) {
        eDd = `0${eDd}`;
      }
      eDate = `${eDy}-${eDm}-${eDd}`;
      this.search.endDate = eDate;
      this.$emit('grid-search', this.search);
    },
    selectAutoData(item) {
      const param = { where: item.field };
      const autoComPath = `/${this.serviceName}/${this.autoComMethod}`;
      this.isLoading = true; // 로딩 부분 시작지점
      this.$service
        .read(autoComPath, param)
        .then(({ data }) => {
          for (let i = 0; i < data.length; i += 1) {
            this.autoComData[i] = data[i][item.field];
          }
        })
        .catch(() => {
          // console.log(error);
        })
        .finally(() => {
          this.isLoading = false; // 로딩 부분 닫아주기
        });
    },
    option(value) {
      this.search = this.name;
      const item = value;
      item.comboData = this.autoComData.filter((option) => (
        option
          .toString()
          .toLowerCase()
          .indexOf(this.search[item.field]) >= 0
      ));
    },
    dropdownSelect(field, data) {
      this.search[field] = data;
    },
  },
};
</script>

<style scoped>
/* Collapse일때는 배경색 바뀌지 않게 :not 추가 */
.button:focus:not(.collapse-btn) {
  color: white;
}
</style>

<style>
/* Collapse 버튼 테두리 제거 */
.collapse-btn {
  border: none;
}
/* Collapse일때 padding 0 */
.collapse-message {
  padding: 0;
}
</style>
