<template>
  <div class="app-container">
    <div
      class="filter-container"
      v-loading="loading">
      <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" @change="changeReportType">
              <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' && reportFilter.reportType !== 'MAF'"
            class="row-item">
            <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>
          <el-form-item
            label="Site:"
            class="row-item"
            v-if="reportFilter.reportType == 'MAF' || reportFilter.reportType == 'MSS'">
            <el-select
              filterable
              remote
              v-model="reportFilter.sitePk"
              :remote-method="(s) => getSiteOptions(s)"
              placeholder="Select with search">
              <el-option
                v-for="(item, index) in siteOptions"
                :key="index"
                :label="item.siteName"
                :value="item.sitePk"/>
            </el-select>
          </el-form-item>
        </div>

        <div class="row">
          <el-form-item
            label="Year:"
            class="row-item"
            v-if="reportFilter.reportType != 'MAF'">
            <el-date-picker
              v-model="reportFilter.year"
              format="yyyy"
              value-format="yyyy"
              type="year"
              :clearable="false"/>
          </el-form-item>
          <el-form-item
            label="Month:"
            class="row-item"
            v-if="reportFilter.reportType != 'MAF'">
            <el-select v-model="reportFilter.month">
              <el-option
                v-for="month in monthOptions"
                :label="month.name"
                :value="month.value"
                :key="month.value"/>
            </el-select>
          </el-form-item>
          <el-form-item
            label="Date Range:"
            class="row-item"
            v-if="reportFilter.reportType == 'MAF'">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              start-placeholder="Start Date"
              end-placeholder="End Date"
              :picker-options="pickerOptions"/>
          </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>
    </div>
    <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="160">
          <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>
</template>

<script>
import api from '@/http/api/dashboard'
import site from '@/http/api/site'
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,
      dateRange: [],
      siteOptions: [],
      reportTypeOptions: [],
      serviceProviderOptions: [],
      monthOptions: [],
      yearOptions: [],
      reportFilter: {
        sitePk: "",
        reportType: '',
        providerPk: '',
        year: ''+new Date().getFullYear(),
        month: '',
      },
      reports: [],
      total: 0,
      pagination: {
        limit: 10,
        page: 1,
      },
      pickerOptions: {
        shortcuts: [{
          text: 'Nearest Week',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },
  methods: {
    getData() {
      this.loading = true
      Promise.all([
        this.getServiceProviderTypeOptions(),
        this.getMonthOptions(),
        this.getReportTypeOptions(),
        this.getSiteOptions()
      ]).then(() => {
        this.loading = false
      })
    },
    changeReportType() {
      this.getSiteOptions("")
    },
    validate(isGen) {
      var valid = true;
      if (this.reportFilter.reportType == 'MAF') {
        if (this.dateRange.length == 2) {
          this.reportFilter.dateStart = this.dateRange[0]
          this.reportFilter.dateEnd = this.dateRange[1]
        } else if (isGen) {
          this.$message({
            type: 'error',
            message: "Please select date range"
          });
          valid = false;
        }
      }
      if (/*this.reportFilter.reportType == 'MSUR' || */this.reportFilter.reportType == 'MAF') {
        if (!this.reportFilter.sitePk && isGen) {
          this.$message({
            type: 'error',
            message: "Please select a site"
          });
          valid = false;
        }
      }
      return valid;
    },
    handleGenerateReport() {
      if (!this.validate()) {
        return;
      }
      this.loading = true
      this.getReportsPages()
    },
    async reGenerateReport() {
      if (!this.validate(true)) {
        return;
      }
      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
          }
        })
    },
    getSiteOptions(search) {
      site.getAllSiteList({siteName: search ?? ""}).then(res => {
        if (res.data && res.data.length > 0) {
          this.siteOptions = res.data
        }
      });
    },
    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;
    padding-left: 30px;
    margin-top: 20px;
    margin-bottom: 30px;
    font-size: 15px;
    user-select: none;
    line-height: 24px;
    font-weight: 700;
    font-family: sans-serif;
    text-transform: uppercase;
  }

  .row {
    display: flex;
    flex-wrap: wrap;
  }

  .row-item {
    position: relative;
    margin-right: 20px;
  }
  
  .row-item > * {
    width: 100%;
  }

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

  .export-button {
    background-color: #fff;
  }
  @media screen and (max-width: 500px) {
    .view-content {
      padding: 15px 30px;
    }
  }
</style>