<template>
  <!-- 참조: https://codesandbox.io/s/3v0m1?file=/src/components/board/BoardList.vue -->
  <div>
    <b-container fluid>
      <b-row>
        <b-col> </b-col>
        <b-col>
          <b-form-group>
            <b-input-group>
              <label class="input-group-text">Filter</label>
              <b-form-input
                id="filter-input"
                v-model="filter"
                type="text"
                placeholder="Type to Filter"
              ></b-form-input>
              <b-input-group-append>
                <b-button :disabled="!filter" @click="filter = ''"
                  >Clear</b-button
                >
              </b-input-group-append>
            </b-input-group>
          </b-form-group>
        </b-col>
        <b-col>
          <div class="input-group justify-content-end">
            <label class="input-group-text">줄수</label>
            <b-form-select
              v-model="perPage"
              :options="perPageOptions"
            ></b-form-select>
          </div>
        </b-col>
      </b-row>
      <b-row class="overflow-auto">
        <b-table
          :items="items"
          :fields="fields"
          :per-page="perPage"
          :current-page="currentPage"
          :filter="filter"
          :filter-included-fields="filterOn"
          :sort-by.sync="sortBy"
          :sort-desc.sync="sortDesc"
          :sort-direction="sortDirection"
          :busy="isBusy"
          :striped="table_Attributes.striped"
          :hover="table_Attributes.hover"
          :bordered="table_Attributes.bordered"
          :dark="table_Attributes.dark"
          :head-variant="table_Attributes.headVariant"
          label-sort-asc=""
          label-sort-desc=""
          label-sort-clear=""
          @filtered="onFiltered"
        >
          <template #cell(selected)="row">
            <input
              type="checkbox"
              :value="row.item.id"
              @change="checkedIdsToggle(row.item.id)"
            />
            {{ row.item.id }}
          </template>
          <template #cell(index)="row">
            {{ total - (currentPage * perPage + row.index) + perPage }}
          </template>
          <template #table-busy>
            <div class="text-center text-danger my-2">
              <b-spinner class="align-middle"></b-spinner>
              <strong>Loading...</strong>
            </div>
          </template>
        </b-table>
      </b-row>
      <b-row>
        <b-col>
          <b-pagination
            v-model="currentPage"
            :total-rows="total"
            :per-page="perPage"
          ></b-pagination>
        </b-col>
        <b-col>
          <div class="input-group">
            <label class="input-group-text">DB</label>
            <input type="text" class="form-control" v-model="search" />
            <span class="input-group-text" @click="searchClick">검색</span>
          </div>
        </b-col>
        <b-col>
          <div class="input-group justify-content-end">
            <b-button @click="busyToggle">Toggle Busy State</b-button>
          </div>
        </b-col>
      </b-row>
    </b-container>
  </div>
</template>

<script>
// 참조 : https://vuejsexamples.com/vuejs-tables-and-select-all-checkbox/
import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:3000'
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*'
export default {
  components: {},
  data() {
    return {
      items: [],
      fields: [
        {
          key: 'selected',
          label: ''
        },
        { key: 'index', label: '번호' },
        {
          key: 'title',
          label: '타이틀',
          sortable: true,
          sortDirection: 'desc',
          filterByFormatted: true
        },
        {
          key: 'content',
          label: '내용',
          sortable: true,
          sortDirection: 'desc',
          filterByFormatted: true
        },
        {
          key: 'is_done',
          label: '사용여부',
          // formatter: (value, key, item) => {
          formatter: (value) => {
            return value ? 'Yes' : 'No'
          },
          sortable: true,
          sortByFormatted: true,
          filterByFormatted: true
        },
        // { key: 'updateAt', label: '수정일' },
        {
          key: 'createdAt',
          label: '登録日時',
          formatter: (value) => {
            return value.replace(
              /([0-9]{4})-([0-9]{2})-([0-9]{2}).*/gi,
              '$1-$2-$3'
            )
          },
          sortable: true
          // filterByFormatted: true
        }
      ],
      total: 0,
      perPage: 5, // 페이지당 보여줄 갯수
      perPageOptions: [
        { value: 5, text: '5줄' },
        { value: 10, text: '10줄' },
        { value: 15, text: '15줄' },
        { value: 100, text: 'Show a lot' }
      ],
      currentPage: 1, // 현재 페이지
      // 속성옵션
      table_Attributes: {
        striped: true,
        hover: true,
        bordered: true,
        dark: false,
        headVariant: 'null'
      },
      isBusy: false,
      sortBy: 'id',
      sortDesc: false,
      sortDirection: 'asc',
      filter: null,
      filterOn: [],
      search: null,
      checkedIds: []
    }
  },
  setup() {},
  created() {},
  mounted() {
    // var vm = this
    // setTimeout(function () {
    //   vm.records = vm.getDatas()
    // }, 1000)
    this.getDatas()
    this.total = this.items.length
  },
  unmounted() {},
  methods: {
    async getDatas() {
      this.isBusy = true
      const items = await axios
        .get('/todo/vue2', {
          params: {
            search: this.search
          }
        })
        .then((response) => {
          return response.status === 200 ? response.data : []
        })
        .catch((err) => {
          console.log(err)
          return []
        })
      //console.log(JSON.stringify(items.rows))
      this.total = items.total
      this.items = items.rows
      this.isBusy = false
    },
    searchClick() {
      this.currentPage = 1
      this.getDatas()
    },
    busyToggle() {
      this.isBusy = !this.isBusy
    },
    onFiltered(filteredItems) {
      // Trigger pagination to update the number of buttons/pages due to filtering
      this.total = filteredItems.length
      this.currentPage = 1
    },
    checkedIdsToggle(id) {
      console.log(this)
      //console.log(this.checkedIds)
      if (!this.checkedIds.includes(id)) {
        this.checkedIds.push(id)
      } else {
        this.checkedIds = this.checkedIds.filter((e) => e !== id)
      }
      console.log(this.checkedIds)
    }
  },
  computed: {
    sortOptions() {
      // Create an options list from our fields
      return this.fields
        .filter((f) => f.sortable)
        .map((f) => {
          return { text: f.label, value: f.key }
        })
    }
  }
}
</script>
<style scoped></style>
