<template>
  <div class="view-container">
    <div
      class="view-content"
      v-loading="loading">
      <div class="section-title">Report</div>
      <el-form
        label-width="130px"
        :model="reportFilter">
        <div class="row">
          <el-form-item
            label="Report Type:"
            class="row-item">
            <el-select v-model="reportFilter.reportType">
              <el-option
                v-for="reportType in reportTypeOptions"
                :label="reportType.name"
                :value="reportType.value"
                :key="reportType.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="Service Provider:" v-if="reportFilter.reportType !== 'MTU'">
            <el-select v-model="reportFilter.providerPk">
              <el-option
                v-for="serviceProvider in serviceProviderOptions"
                :label="serviceProvider.name"
                :value="serviceProvider.value"
                :key="serviceProvider.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>

        <div class="row">
          <el-form-item
            label="Month:"
            class="row-item">
            <el-select v-model="reportFilter.month">
              <el-option
                v-for="month in monthOptions"
                :label="month.name"
                :value="month.value"
                :key="month.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="Year:"
            class="row-item">
            <el-date-picker
              v-model="reportFilter.year"
              format="yyyy"
              value-format="yyyy"
              type="year"
              :clearable="false"
            />
          </el-form-item>

          <el-button
            class="filter-item generate-button"
            v-waves
            type="primary"
            @click="handleGenerateReport">
            Search
          </el-button>
          <el-button
            class="filter-item generate-button"
            v-waves
            type="primary"
            :disabled="regenbtn"
            @click="reGenerateReport">
            Generate
          </el-button>
        </div>
      </el-form>

      <el-table
        :data="reports"
        fit
        style="width: 100%;">
        <el-table-column
          label="File Name"
          prop="fileName"
          align="center"
          min-width="400"
          >
          <template slot-scope="{row}">
            <span>{{ row.fileName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="Month"
          prop="monthStr"
          align="center"
          min-width="90"
        >
            <template slot-scope="{row}">
              <span>{{ row.monthStr }}</span>
            </template>
        </el-table-column>
        <el-table-column
          label="Service Provider"
          prop="providerName"
          align="center"
          min-width="170"
        >
            <template slot-scope="{row}">
              <span>{{ row.providerName }}</span>
            </template>
        </el-table-column>
        <el-table-column
          label="Creation Date/Time"
          prop="createDateTime"
          align="center"
          min-width="180"
        >
            <template slot-scope="{row}">
              <span>{{ row.createDateTime }}</span>
            </template>
        </el-table-column>
        <el-table-column
          v-if="!$route.meta.onlyView"
          label="Action"
          align="center"
          min-width="160"
        >
            <template slot-scope="{row}">
              <el-button
                :loading="row.loading"
                icon="el-icon-download"
                class="export-button"
                @click="handleExportExcel(row)"
              >
                Export
              </el-button>
            </template>
        </el-table-column>
      </el-table>
      <div class="right">
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="pagination.page"
          :limit.sync="pagination.limit"
          @pagination="handlePageChange" />
      </div>
    </div>
  </div>
</template>

<script>
import api from '@/http/api/dashboard'
import reports from '@/http/api/reports'

// waves directive
import waves from '@/directive/waves'
// secondary package based on el-pagination
import Pagination from '@/components/Pagination'
import TableAction from '@/components/TableAction.vue'

const { getProviderList } = api
const {
  getReportTypeList,
  getMonthList,
  getReportsPages,
  downloadFile,
  generateMonthlyExcel
} = reports

export default {
  name: 'Reports',
  components: { Pagination, TableAction },
  directives: { waves },
  setup() {
    
  },
  created() {
    this.getData()
    this.getReportsPages()
  },
  data() {
    return {
      loading: false,
      regenbtn: false,
      reportTypeOptions: [],
      serviceProviderOptions: [],
      monthOptions: [],
      yearOptions: [],
      reportFilter: {
        reportType: '',
        providerPk: '',
        year: ''+new Date().getFullYear(),
        month: '',
      },
      reports: [],
      total: 0,
      pagination: {
        limit: 10,
        page: 1,
      }
    }
  },
  methods: {
    getData() {
      this.loading = true
      Promise.all([
        this.getServiceProviderTypeOptions(),
        this.getMonthOptions(),
        this.getReportTypeOptions(),
      ]).then(() => {
        this.loading = false
      })
    },
    handleGenerateReport() {
      this.loading = true
      this.getReportsPages()
    },
    async reGenerateReport() {
      this.regenbtn = true;
      this.loading = true;
      generateMonthlyExcel(this.reportFilter).then(res => {
        this.loading = false;
        this.$message({
          type: res.success?'success':'error',
          message: res.msg
        })
      }).catch(err => {
        this.loading = false;
        this.$message({
          type: 'error',
          message: err
        })
      })
      
      setTimeout(() => {
        this.regenbtn = false;
      }, 5000);
    },
    getServiceProviderTypeOptions() {
      return getProviderList().then(({ data }) => {
        this.serviceProviderOptions = data
        this.reportFilter.providerPk = data[0].value
      })
    },
    getMonthOptions() {
      return getMonthList().then(({ success, data }) => {
        if (success) {
          this.monthOptions = data
          this.reportFilter.month = data[0].value
        }
      })
    },
    getReportTypeOptions() {
      return getReportTypeList()
        .then(({ success, data }) => {
          if (success) {
            this.reportTypeOptions = data
            this.reportFilter.reportType = data[0].value
          }
        })
    },
    handlePageChange(value) {
      this.loading = true
      const { limit, page } = value
      this.pagination.limit = limit
      this.pagination.page = page
      this.getReportsPages()
    },
    getReportsPages() {
      const {
        limit,
        page,
      } = this.pagination
      const params = {
        pageSize: limit,
        pageNo: page,
        pageVo: this.reportFilter,
      }
      return getReportsPages(params)
        .then(({ success, data, total }) => {
          if (success) {
            this.reports = data.map((report) => {
              report.loading = false
              return report
            })
            this.total = total
          }
        }).finally(() => {
          this.loading = false
        })
    },
    handleExportExcel(row) {
      row.loading = true
      downloadFile({ filePk: row.filePk }).then((res) => {
        this.downloadExcel(res, row.fileName)
      }).finally(() => {
        row.loading = false
      })
    },
    downloadExcel(res, fileName) {
      const blob = new Blob([res], {
        type: 'application/vnd.ms-excel;charset=utf-8'
      })
      // let href = window.URL.createObjectURL(blob)
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
      this.excelLoad = false
    }
  },
}
</script>

<style lang="scss" scoped>
  @import '../styles/variables.scss';

  .view-container {
    width: 100%;
    padding: 20px 60px;
    background-color: #F0F5FC;
  }

  .view-content {
    padding: 15px 45px;
    border-radius: 6px;
    min-height: calc(#{$mainAppMinHeight} - (2 * 20px));
    background-color: white;
  }

  .section-title {
    color: #333;
    margin-top: 20px;
    margin-bottom: 30px;
    font-size: 16px;
    user-select: none;
    line-height: 24px;
    font-weight: 500;
    font-family: sans-serif;
    text-transform: uppercase;
  }

  .row {
    display: flex;
  }

  .row-item {
    margin-right: 66px;
  }

  .generate-button {
    width: 107.9px;
    height: 40px;
  }

  .export-button {
    background-color: #fff;
  }

</style>