<template>
  <div :style="pageStyle">
    <q-card
      v-if="showSearchPanel"
      style="margin-bottom: 15px;"
    >
      <q-resize-observable @resize="onSearchPanelResize"></q-resize-observable>
      <q-card-main>
        <slot name="search-form"></slot>
      </q-card-main>
      <q-card-actions align="center">
        <div class="w3-container">
          <q-btn
            color="primary"
            @click="searchOk"
            :label="$t('sys.search')"
            style="min-width:80px;"
          ></q-btn>
          <q-btn
            color="secondary"
            v-if="showDownloadBtn"
            @click="downloadCsv"
            :label="$t('sys.export')"
            style="min-width:80px;"
          ></q-btn>
          <slot name="search-panel-actions"></slot>
        </div>
      </q-card-actions>
    </q-card>
    <q-modal
      position="top"
      no-backdrop-dismiss
      no-esc-dismiss
      v-model="searchOpened"
    >
      <div style="min-width:300px;min-height:100px;">
        <div class="w3-padding">
          <slot name="search-form"></slot>
        </div>
        <div class="w3-padding w3-center">
          <q-btn
            color="primary"
            @click="searchOk"
            :label="$t('sys.search')"
            style="width:100px;"
          ></q-btn>
          <q-btn
            color="secondary"
            @click="searchCancel"
            :label="$t('sys.cancel')"
            style="width:100px;"
          ></q-btn>
        </div>
      </div>
    </q-modal>
    <div>
      <q-search
        v-if="showSearchFieldWithMobile"
        v-model="filter"
        clearable
      ></q-search>
    </div>
    <q-table
      :title="title"
      :data="data"
      :filter="filter"
      :columns="columns"
      :row-key="rowKey"
      :pagination.sync="pagination"
      :selection="selection"
      :selected.sync="selfSelected"
      :rows-per-page-options="rowsPerPageOptions"
    >
      <template
        v-if="!showSearchFieldWithMobile"
        :slot="showSearchField ? 'top-right' : ''"
      >
        <div>
          <div class="col-xs-12 q-pa-xs">
            <q-search
              v-model="filter"
              clearable
            ></q-search>
          </div>
        </div>
      </template>
      <q-tr
        slot="body"
        slot-scope="props"
        :props="props"
        @click.native="rowClick(props,event)"
      >
        <q-td
          auto-width
          class="text-center"
          v-if="selection=='multiple' || selection=='single'"
        >
          <q-checkbox
            color="primary"
            v-model="props.selected"
          ></q-checkbox>
        </q-td>
        <q-td
          v-for="col in props.cols"
          :key="col.name"
          :props="props"
        >
          <slot
            v-if="col.$$is_slot"
            :name="'row_col_'+col.name"
            :row_data="props"
          ></slot>
          <div
            v-else-if="col.$$is_num_format"
            v-text="$root.FnFormatNumber(col.value,col.$$num_format_decimal)"
          ></div>
          <div
            v-else-if="col.$$is_date_format"
            v-text="moment(col.value).format('YYYY/MM/DD')"
          ></div>
          <div
            v-else-if="col.$$is_datetime_format"
            v-text="moment(col.value).format('YYYY/MM/DD HH:mm:ss')"
          ></div>
          <div
            v-else
            v-text="col.value"
          ></div>
        </q-td>
        <q-td
          style="width:10px;"
          align="center"
        >
          <slot
            name="row-control"
            :row_data="props"
          ></slot>
        </q-td>
      </q-tr>
    </q-table>
    <q-page-sticky
      position="top-right"
      :offset="[10, 10]"
    >
      <!-- 預設有一個 search button //-->
      <q-btn
        round
        v-if="showSearchBtn"
        color="primary"
        @click="searchOpened=true"
        icon="search"
      ></q-btn>
      <q-btn
        round
        v-if="showSearchBtn && showDownloadBtn"
        color="primary"
        @click="downloadCsv"
        icon="download"
      ></q-btn>
      <slot name="page-sticky">
      </slot>
    </q-page-sticky>
  </div>
</template>

<script>
module.exports = {
  name: "data-table",
  props: {
    "title": {
      "type": "String",
    },
    "offset-screen-height": { // 微調螢幕的長度, 因為要算每頁筆數, 本元件可能有配合父頁版面調整大小
      "type": "Number",
      "default": -150,
    },
    "show-search-btn": { // 是否顯示查詢按鈕
      "type": "Boolean",
      "default": false
    },
    "show-search-panel": { // 是否顯示查詢面版
      "type": "Boolean",
      "default": false
    },
    "show-download-btn": { // 是否顯示下載按鈕
      "type": "Boolean",
      "default": false
    },
    "show-search-field": { // 是否顯示slot top-left
      "type": "Boolean",
      "default": false
    },
    'rows-num': { // 一頁要幾筆
      default: 0
    },
    "outfilter": { // 來自外部的過濾
      "default": ""
    },
    "selection": {
      "type": "String" // 是否出現checkbox選單(原quasar功能), single:單選, multiple:多選
    },
    "selected": { // 回傳選擇記錄後的值給父層, 父層需使用.sync修飾詞 <data-table :selected.sync="xxx" />
      "type": "Array",
      "default": []
    },
    "row-key": { // 表格資料的主key
      "default": "__index"
    },
    "columns": { // 欄位清單
      "type": "Array",
      "default": []
    },
    "data": { // 資料清單
      "type": "Array",
      "default": []
    },
    "page-style": { // 放在頁面 template / div 的 style
      "type": "String",
      "default": "",
    }
  },
  data () {
    return {
      "filter": "",
      "pagination": { rowsPerPage: 10 },
      "searchOpened": false,
      "searchPanelHeight": 0
    }
  },
  computed: {
    isDesktop () { // 是否為桌面平台
      return this.$root.VarIsDesktop;
    },
    isMobile () { // 是否為手機平台
      return this.$root.VarIsMobile;
    },
    isTablet () { // 是否為平板平台
      return this.$root.VarIsTablet;
    },
    isMenuOpen () { // 是否開啟選單
      return this.$root.VarIsMenuOpen;
    },
    screenIsVertical () { // 螢幕是否直立
      return this.$root.VarScreenIsVertical;
    },
    showSearchFieldWithMobile () { // 是否顯示查詢框, 加上 mobile 判斷
      return this.showSearchField && ((this.isMobile && this.screenIsVertical) || (this.isTablet && this.isMenuOpen));
    },
    layoutScreenHeight () { // 螢幕的高
      return this.$root.VarLayoutScreenHeight;
    },
    layoutContainerHeight () { // 螢幕的寬
      return this.$root.VarLayoutContainerHeight;
    },
    rowsPerPage () { // 每頁顯示幾筆, 會根據螢幕高度與平台計算
      var newNum = 0;
      if (this.rowsNum > 0) {
        newNum = this.rowsNum
      } else {
        var screenHeightNow = this.layoutScreenHeight + this.offsetScreenHeight;
        if (this.isMobile && this.screenIsVertical) { // 手機 & 垂直
          newNum = Math.round((screenHeightNow - this.searchPanelHeight) / 70)
        } else if (this.isMobile) {
          newNum = Math.round(screenHeightNow / 120)
        } else if (this.isTablet && this.screenIsVertical) { // 平板 & 垂直
          newNum = Math.round((screenHeightNow - this.searchPanelHeight) / 70)
          // } else if (this.isTablet && this.isMenuOpen) { // 沒效, 有空再找原因
          //   return Math.round(this.layoutContainerHeight / 60) - 2
        } else if (this.isTablet) {
          newNum = Math.round(screenHeightNow / 100)
        } else { // 桌面
          newNum = Math.round((screenHeightNow - this.searchPanelHeight) / 70)
        }
      }
      return newNum
    },
    rowsPerPageOptions () { // 每頁筆數選單
      if (this.isPhone) {
        return _.uniq([Math.round(this.rowsPerPage), 0])
      } else {
        return _.uniq([Math.round(this.rowsPerPage), 5, 10, 20, 30, 0])
      }
    },
    selfSelected: { // 選擇哪些row
      get () {
        return this.selected
      },
      set (val) {
        this.$emit('update:selected', val) // 為了讓父層 :selected.sync 生效
      }
    }
  },
  watch: {
    layoutScreenHeight () { // 當螢幕高度變更時(如:水平與垂值切換), 會變更rowsPerPage,所以要選擇該頁
      this.pagination.rowsPerPage = this.rowsPerPage;
    },
    searchPanelHeight () { // 當search panel 高度變更時, 會變更rowsPerPage,所以要選擇該頁
      if (this.showSearchPanel) {
        this.pagination.rowsPerPage = this.rowsPerPage;
      }
    },
    outfilter (nv) {
      this.filter = nv
    }
  },
  mounted () {
    this.pagination.rowsPerPage = this.rowsPerPage;
    this.filter = this.outfilter;
  },
  methods: {
    rowClick (props, evt) {
      this.$emit("row-click", props, evt);
    },
    searchOk (evt) {
      this.$emit("search-ok", evt);
      this.searchOpened = false;
    },
    searchCancel (evt) {
      this.$emit("search-cancel", evt);
      this.searchOpened = false;
    },
    downloadCsv () {
      this.$root.FnReportDownload("csv", this.data, this.columns);
    },
    onSearchPanelResize (props) {
      if (this.showSearchPanel) { // 若不顯示 search panel 則不需要取得它的高度
        this.searchPanelHeight = props.height;
      }
    }
  }
}
</script>

<style scoped>
.q-table-top {
  background-color: #334048;
  color: #fff;
  font-size: 13pt;
}
.q-table-top .q-input-target,
.q-table-top .q-if {
  color: #fff;
  font-size: 13pt;
}
.q-select .q-input-target {
  width: 10px !important;
  font-size: 12pt;
}
.q-table > thead > tr > th {
  text-align: center !important;
}
th {
  font-size: 14pt;
  font-weight: bold;
  color: #287dd1;
}
td {
  font-size: 13pt !important;
}
</style>
