<template>
  <section class="message">
    <form
      name="form"
      @submit.prevent="selectData"
    >
      <b-button
        v-show="false"
        native-type="submit"
      />
      <div class="message-body search">
        <b-field style="overflow: auto; display: block;">
          <b-field
            v-for="(row, idx) in searchList"
            :key="idx"
            grouped
            group-multiline
            style="flex-wrap: unset;"
          >
            <b-field
              v-for="(item, index) in row"
              :key="index"
              :label="item.label"
              :custom-class="!item.notColon ? 'colon' : ''"
              horizontal
              :style="{
                width: (item.width ? item.width : '200px'),
              }"
            >
              <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>
              <div
                v-if="item.fieldType == 'month'"
                style="display: flex;"
              >
                <b-select
                  v-model="search[`${item.field}_y`]"
                  :placeholder="'년'"
                  size="is-small"
                  expanded
                  @input="$emit(`${item.field}_y`, search[`${item.field}_y`])"
                >
                  <option
                    v-for="option in yearCombo"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.name }}
                  </option>
                </b-select>
                <b-select
                  v-model="search[`${item.field}_m`]"
                  :placeholder="'월'"
                  size="is-small"
                  expanded
                  @keypress.native.enter="enterPressEvent($event, `${item.field}_m`)"
                  @input="$emit(`${item.field}_m`, search[`${item.field}_m`])"
                >
                  <option
                    v-for="option in 12"
                    :key="option"
                    :value="option"
                  >
                    {{ option }}월
                  </option>
                </b-select>
              </div>
              <div
                v-if="item.fieldType == 'date'"
                style="display: flex;"
              >
                <b-select
                  v-model="search[`${item.field}_y`]"
                  :placeholder="'년'"
                  size="is-small"
                  expanded
                  @input="$emit(`${item.field}_y`, search[`${item.field}_y`])"
                >
                  <option
                    v-for="option in yearCombo"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.name }}
                  </option>
                </b-select>
                <b-select
                  v-model="search[`${item.field}_m`]"
                  :placeholder="'월'"
                  size="is-small"
                  expanded
                  @input="selectMonth(item.field, search[`${item.field}_m`])"
                >
                  <option
                    v-for="option in 12"
                    :key="option"
                    :value="option"
                  >
                    {{ option }}월
                  </option>
                </b-select>
                <b-select
                  v-model="search[`${item.field}_d`]"
                  :placeholder="'일'"
                  size="is-small"
                  expanded
                  @keypress.native.enter="enterPressEvent($event, `${item.field}_d`)"
                  @input="$emit(`${item.field}_d`, search[`${item.field}_d`])"
                >
                  <option
                    v-for="option in dayCombo[item.field]"
                    :key="option"
                    :value="option"
                  >
                    {{ option }}일
                  </option>
                </b-select>
              </div>
              <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"
              />
            </b-field>
          </b-field>
        </b-field>
      </div>
    </form>
  </section>
</template>

<script>
export default {
  props: {
    searchList: {
      type: Array,
    },
    methodName: {
      type: String,
    },
    serviceName: {
      type: String,
    },
    autoComMethod: {
      type: String,
    },
    initSearchDate: {
      type: Object,
    },
    searchFlag: Boolean,
  },
  data() {
    return {
      search: {},
      autoComData: [''],
      name: {},
      initDate: {},
      selectedIndex: {},
      yearCombo: [],
      dayCombo: {},
    };
  },
  watch: {
    searchFlag(newVal) {
      if (newVal) {
        this.selectData();
      }
    },
  },
  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;
        }
      } else if (params.id != null) {
        if (params.value == null || params.value === '') {
          this.search[params.id] = new Date();
        } else {
          this.search[params.id] = params.value;
        }
      }
    },
    selectMonth(field, param) {
      this.setDay(field);
      this.$emit(`${field}_m`, param);
    },
    setDay(field) {
      const day = new Date(this.search[`${field}_y`], this.search[`${field}_m`], 0).getDate();
      this.$set(this.dayCombo, `${field}`, day);
    },
    init() {
      const year = new Date().getFullYear();
      const month = new Date().getMonth() + 1;
      const day = new Date().getDate();
      for (let i = year - 5; i < year + 4; i += 1) {
        const temp = {
          value: i,
          name: `${i}년`,
        };
        this.yearCombo.push(temp);
      }
      this._props.searchList.forEach((list) => {
        list.forEach((item) => {
          if (item.fieldType === 'month') {
            this.search[`${item.field}_y`] = year;
            this.search[`${item.field}_m`] = month;
          } else if (item.fieldType === 'date') {
            if (item.initDay) {
              const initDate = new Date();
              initDate.setDate(initDate.getDate() + item.initDay);
              this.search[`${item.field}_y`] = initDate.getFullYear();
              this.search[`${item.field}_m`] = initDate.getMonth() + 1;
              this.setDay(item.field);
              this.search[`${item.field}_d`] = initDate.getDate();
            } else {
              this.search[`${item.field}_y`] = year;
              this.search[`${item.field}_m`] = month;
              this.setDay(item.field);
              this.search[`${item.field}_d`] = day;
            }
          }
        });
      });
      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('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>
.field.is-horizontal .field-label .label {
  width: max-content;
}
.field.is-grouped .field {
  margin-right: 0.75em;
}
.field.is-grouped.is-grouped-multiline:last-child {
  margin-bottom: unset;
}
.message-body.search {
  padding-bottom: 0.75rem;
}
@media screen and (min-width: 769px), print{
  .field.is-horizontal .field-label{
    margin-right: 1rem;
    flex-grow: unset;
  }
  .field.is-horizontal .field-label.colon .label::after {
    content: " :";
  }
  .field.is-horizontal > .field-body > .field {
    flex-shrink: unset !important;
  }
}
</style>
