<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form
        ref="form"
        :model="form">
        <div class="filter-view">
          <el-form-item
            label=""
            class="flex-item flex1"
            style="min-width: 200px; max-width: 400px;">
            <el-input
              v-model="form.criteria"
              placeholder="Search by Email, Phone or Group Name"
              clearable/>
          </el-form-item>
          <div>
            <el-button
              @click="onClickSearch"
              icon="el-icon-search"
              type="primary">
              Search
            </el-button>
          </div>
          <div class="filter-flex-button"></div>
          <my-upload
            accept=".xls,.xlsx,.csv"
            :limit="1"
            :is-blob="true"
            :action="action"
            :headers="headers"
            :file-list="fileList"
            :show-file-list="false"
            :before-upload="onImportStart"
            :on-success="onImportExcel"
            :on-error="onImportExcelErr">
            <el-button
              icon="el-icon-upload2"
              type="primary"
              :loading="loading.upload">
              Import Excel
            </el-button>
          </my-upload>
          <div>
            <el-button
              icon="el-icon-download"
              type="primary"
              :loading="loading.download"
              @click="onDownloadTmp">
              Download Template
            </el-button>
          </div>
          <div>
            <el-button
              icon="el-icon-plus"
              type="primary"
              @click="onClickAdd">
              Add Group User
            </el-button>
          </div>
        </div>
      </el-form>
    </div>
    <el-table :data="table.list" v-loading="loading.table">
      <el-table-column
        align="center"
        label="User ID"
        prop="userPk"
        width="100">
        <template slot-scope="{row}" >
          <router-link
            class="link-type"
            :to="{
              name: 'DriverDetail',
              query: {
                id: row.userPk,
                dispatch: true,
              },
            }">
            {{ row.userPk }}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        width="200"
        align="center"
        label="Name"
        prop="nickName"
      ></el-table-column>
      <el-table-column
        align="center"
        label="Email"
        prop="email"
      ></el-table-column>
      <el-table-column
        width="150"
        align="center"
        label="Phone"
        prop="phone"
      ></el-table-column>
      <el-table-column
        align="center"
        label="Group"
        prop="groupName"
      ></el-table-column>
      <el-table-column
        align="center"
        label="Status"
        prop="groupStatus"
        width="150"
      ></el-table-column>
      <el-table-column
        align="center"
        label="Action"
        width="210"
      >
        <template slot-scope="{ row }">
          <TableAction
            :showEdit="isDriverOperation(row)"
            @edit="onClickEditButton(row)"
            @delete="onClickDeleteButton(row)"/>
        </template>
      </el-table-column>
    </el-table>
    <div class="right">
      <pagination
        v-show="table.total > 0"
        :total="table.total"
        :page.sync="table.pageNo"
        :limit.sync="table.pageSize"
        @pagination="handlePageChange" />
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import TableAction from '@/components/TableAction'
import api from '@/http/api/driver'
import { baseURL } from '@/http/http'
import { getToken } from '@/utils/auth'
import MyUpload from '@/components/MyUpload'
export default {
  name: "GroupList",
  components: { Pagination, TableAction,MyUpload },
  data() {
    return {
      form: {
        criteria: ''
      },
      table: {
        list: [],
        total: 0,
        pageNo: 1,
        pageSize: 10,
      },
      loading: {
        table: false,
        upload: false,
        download: false
      },
      fileList: []
    }
  },
  computed: {
    action() {
      return baseURL + process.env.VUE_APP_API_PREFIX + '/driver/batch/create'
    },
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  methods: {
    isDriverOperation(driver) {
      return driver.groupStatus === 'Pending Review'
    },
    async getDriverPages() {
      const params = {
        pageSize: this.table.pageSize,
        pageNo: this.table.pageNo,
        pageVo: {
          criteria: this.form.criteria,
        }
      }
      const { success, data, total } = await api.fetchDriverPages(params)
      if (success) {
        this.table.list = data
        this.table.total = total
      }
    },
    onImportStart() {
      this.loading.upload = true;
    },
    onImportExcel(res, file, fileList) {
      fileList = [];
      this.fileList = [];
      if (res.success == undefined) {
        this.downloadExcel(res, "batch_create_result.xls");
        this.loading.upload = false;
      } else {
        this.onImportExcelErr(res.msg, file, fileList);
      }
    },
    onImportExcelErr(err, file, fileList) {
      this.$message({
        type: 'error',
        message: err
      })
      this.loading.upload = false;
    },
    onDownloadTmp() {
      this.loading.download = true;
      api.downloadTemplate().then(res => {
        this.downloadExcel(res, "driver-template.xlsx")
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
      }).finally(() => {
        this.loading.download = 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)
      }
    },
    onClickSearch() {
      this.table.pageNo = 1
      this.getDriverPages()
    },
    onClickAdd() {
      this.$router.push({ name: 'DriverDetail' })
    },
    async onClickDeleteButton(driver) {
      this.$confirm('Are you sure you want to delete this driver?', 'Delete', {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(res => {
        this.deleteUser(driver);
      })
    },
    async deleteUser(driver) {
      try {
        const { success, msg } = await api.deleteDriver({
          userPk: driver.userPk
        })
        if (success) {
          this.$notify.success(msg)
          this.getDriverPages()
        }
      } catch (error) {
        this.$notify.error(error)
      }
    },
    onClickEditButton(driver) {
      this.$router.push({
        name : "DriverDetail",
        query: { id: driver.userPk },
      })
    },
    handlePageChange() {
      this.listLoading = true;
      this.getDriverPages()
    }
  },
  created() {
    this.getDriverPages()
  }
}
</script>

<style lang="scss" scoped>

</style>