<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-view">
        <el-input
          class="filter-input"
          v-model="filters.pageVo.criteria"
          placeholder="Search by Email, Phone or Group Name"
          clearable/>
        <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"
          v-if="!$route.meta.onlyView">
          <el-button
            icon="el-icon-upload2"
            type="primary"
            :loading="loading.upload">
            Import Excel
          </el-button>
        </my-upload>
        <div v-if="!$route.meta.onlyView">
          <el-button
            icon="el-icon-download"
            type="primary"
            :loading="loading.download"
            @click="onDownloadTmp">
            Download Template
          </el-button>
        </div>
        <div v-if="!$route.meta.onlyView">
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="onAddUser">
            Add Group User
          </el-button>
        </div>
      </div>
    </div>
    <el-table
      :data="table.list"
      v-loading="loading.table">
      <el-table-column
        align="center"
        label="Name"
        prop="userPk"
        min-width="100">
        <template slot-scope="{row}" >
          <!-- <span
            class="link-type"
            @click="onViewUser(row)">
            {{ row.membershipId }}
          </span> -->
          <span
            class="link-type"
            @click="onViewUser(row)"
            v-if="!$route.meta.onlyView">
            {{ row.nickName }}
          </span>
          <span v-else>{{ row.nickName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        min-width="140"
        align="center"
        label="User Type"
        prop="userType">
        <template slot-scope="{row}">
          <span>{{row.userType || "Membership"}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="Email"
        prop="email"
        min-width="140"/>
      <el-table-column
        width="150"
        align="center"
        label="Phone"
        prop="phone"
        min-width="120"/>
      <el-table-column
        align="center"
        label="Group"
        prop="groupName"
        min-width="140"/>
      <el-table-column
        align="center"
        label="Status"
        prop="membershipStatus"
        min-width="120"/>
      <el-table-column
        align="center"
        label="Action"
        min-width="140"
        v-if="!$route.meta.onlyView">
        <template slot-scope="{ row }">
          <TableAction
            :showEdit="row.membershipStatus == 'Pending'"
            @edit="onEditUser(row)"
            @delete="onDeleteUser(row)"/>
        </template>
      </el-table-column>
    </el-table>
    <div class="right">
      <pagination
        v-show="table.total > 0"
        :total="table.total"
        :page.sync="filters.pageNo"
        :limit.sync="filters.pageSize"
        @pagination="getTableData" />
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import TableAction from '@/components/TableAction'
import MyUpload from '@/components/MyUpload'
import api from '@/http/api/group'
import { baseURL } from '@/http/http'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      filters: {
        pageNo: 1,
        pageSize: 10,
        pageVo: {
          criteria: ""
        }
      },
      table: {
        list: [],
        total: 0
      },
      loading: {
        table: false,
        upload: false,
        download: false
      },
      fileList: []
    }
  },
  computed: {
    action() {
      return baseURL + process.env.VUE_APP_API_PREFIX + '/groups/user-batch-create'
    },
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  components: {
    Pagination,
    TableAction,
    MyUpload
  },
  created() {
    this.onClickSearch()
  },
  methods: {
    onClickSearch() {
      this.filters.pageNo = 1
      this.getTableData()
    },
    getTableData() {
      this.loading.table = true;
      api.getGroupUserPages(this.filters).then(res => {
        if (res.data && res.total) {
          this.table.total = res.total;
          this.table.list = res.data;
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
        this.table.total = 0;
        this.table.list = [];
      }).finally(() => {
        this.loading.table = false;
      })
    },
    onAddUser() {
      this.$router.push({ path: '/user-management/group/add' })
    },
    onViewUser(row) {
      this.$router.push({
        path: "/user-management/group/detail/" + row.membershipId
      })
    },
    onEditUser(row) {
      this.$router.push({
        path: "/user-management/group/edit/" + row.membershipId
      })
    },
    onDeleteUser(row) {
      this.$confirm('Are you sure you want to delete this group user?', 'Delete', {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(res => {
        this.deleteUser(row.membershipId);
      })
    },
    deleteUser(id) {
      this.loading.table = true;
      api.deleteGroupUser(id).then(res => {
        this.$message({
          type: 'success',
          message: "Delete success."
        })
        this.getTableData()
      }).catch(err => {
        this.loading.table = false;
        this.$message({
          type: 'error',
          message: err
        })
      })
    },
    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, "group-user-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)
      }
    },
  }
}
</script>


<style lang="scss" scoped>
  .filter-input {
    min-width: 100px;
    max-width: 300px;
  }
</style>