<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-view">
        <el-select
          class="filter-select"
          v-model="filters.pageVo.userType"
          placeholder="All User Type"
          @change="onClickSearch"
          clearable>
          <el-option
            v-for="item in userTypes"
            :key="item"
            :label="item"
            :value="item" />
        </el-select>
        <el-select
          class="filter-select"
          v-model="filters.pageVo.accountStatus"
          placeholder="All Account Status"
          @change="onClickSearch"
          clearable>
          <el-option
            label="Active"
            value="A" />
          <el-option
            label="Inactive"
            value="I" />
        </el-select>
        <el-input
          class="filter-input"
          v-model="filters.pageVo.criteria"
          placeholder="Email, Name, License Plate"
          @change="onClickSearch"
          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">
            Template
          </el-button>
        </my-upload>
        <div v-if="!$route.meta.onlyView">
          <el-button
            icon="el-icon-download"
            type="primary"
            :loading="loading.download"
            @click="onDownloadTmp">
            Template
          </el-button>
        </div>
        <div v-if="!$route.meta.onlyView">
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="onAddUser">
            Add User
          </el-button>
        </div>
      </div>
    </div>
    <el-table
      :data="table.list"
      class="no-border"
      v-loading="loading.table">
      <el-table-column
        align="center"
        label="Name"
        prop="userPk"
        min-width="150">
        <template slot-scope="{row}">
          <span
            class="link-type"
            @click="onEditUser(row)"
            v-if="!$route.meta.onlyView">
            {{ row.nickName }}
          </span>
          <span v-else>{{ row.nickName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="E-mail"
        prop="email"
        min-width="160"/>
      <el-table-column
        align="center"
        label="Vehicle"
        prop="licensePlates"
        min-width="120">
        <template slot-scope="{row}">
          <div v-for="item in row.licensePlates" :key="item">{{item}}</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="Credits"
        prop="credit"
        min-width="100"/>
      <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="Group Name"
        prop="fleetName"
        min-width="120"/>
      <el-table-column
        align="center"
        label="Group Status"
        prop="fleetStatus"
        min-width="120"/>
      <el-table-column
        width="150"
        align="center"
        label="Membership"
        prop="phone"
        min-width="120">
        <template slot-scope="{row}">
          <div v-for="(item,index) in row.memberships" :key="index">
            <span :class='"status-" + item.membershipStatus'>{{item.membershipName}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="Account Status"
        prop="accountStatus"
        min-width="140"/>
      <el-table-column
        align="center"
        label="Action"
        min-width="80"
        v-if="!$route.meta.onlyView">
        <template slot-scope="{ row }" v-if="row.accountStatus != 'Inactive'">
          <el-dropdown
            class="action-dropdown"
            @command="(v) => handleCommand(v, row)">
            <i class="el-icon-more icon-action"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                command="onEditUser">
                Edit
              </el-dropdown-item>
              <el-dropdown-item
                command="showTopupModal">
                Top Up Credits
              </el-dropdown-item>
              <el-dropdown-item
                command="toHistoryTopup">
                Top Up History
              </el-dropdown-item>
              <el-dropdown-item
                command="toHistoryCharge">
                Charging History
              </el-dropdown-item>
              <el-dropdown-item
                command="onDeleteUser">
                Delete
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </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>
    <TopUp
      :visible="actionTopup.visible"
      :userInfo="actionTopup.row"
      @hide="showTopupModal"
      @success="showTopupModal('', true)"/>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import TableAction from '@/components/TableAction'
import MyUpload from '@/components/MyUpload'
import TopUp from './views/TopUp.vue'
import api from '@/http/api/apiUser'
import { baseURL } from '@/http/http'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      filters: {
        pageNo: 1,
        pageSize: 10,
        pageVo: {
          criteria: "",
          userType: "",
          accountStatus: ""
        }
      },
      table: {
        list: [],
        total: 0
      },
      loading: {
        table: false,
        upload: false,
        download: false
      },
      fileList: [],
      userTypes: [],
      actionTopup: {
        row: {},
        visible: false
      }
    }
  },
  computed: {
    action() {
      return baseURL + process.env.VUE_APP_API_PREFIX + '/device-user/batch-create'
    },
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  components: {
    Pagination,
    TableAction,
    MyUpload,
    TopUp
  },
  created() {
    this.getUserTypeOption()
    this.onClickSearch()
  },
  methods: {
    onClickSearch() {
      this.filters.pageNo = 1
      this.getTableData()
    },
    getUserTypeOption() {
      api.getUserTypeOptions().then(res => {
        if (res.data) {
          this.userTypes = res.data
        }
      }).catch(err => {
        this.$message({
          message: error,
          type: 'error'
        })
      })
    },
    getTableData() {
      this.loading.table = true;
      api.pageAppUsers(this.filters).then(res => {
        if (res.data && res.total) {
          this.table.total = res.total;
          this.table.list = res.data;
        } else {
          this.table.total = 0;
          this.table.list = [];
        }
      }).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/add' })
    },
    handleCommand(cb, item) {
      this[cb](item)
    },
    showTopupModal(row, success) {
      if (row && row.userPk) {
        this.actionTopup.row = row;
        this.actionTopup.visible = true
      } else {
        this.actionTopup.id = "";
        this.actionTopup.visible = false;
        if (success) this.getTableData();
      }
    },
    toHistoryCharge(row) {
      this.$router.push("/user-management/charging-history/" + row.userPk)
    },
    toHistoryTopup(row) {
      this.$router.push("/user-management/topup-history/" + row.userPk)
    },
    onEditUser(row) {
      this.$router.push({
        path: "/user-management/update/" + row.userPk
      })
    },
    onDeleteUser(row) {
      this.$confirm('Are you sure you want to delete this user?', 'Delete', {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(res => {
        this.deleteUser(row.userPk);
      })
    },
    deleteUser(id) {
      this.loading.table = true;
      api.deleteAppUser(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>
  @import '../../styles/variables.scss';
  .filter-input {
    min-width: 100px;
    max-width: 300px;
  }
  .filter-select {
    min-width: 100px;
    max-width: 180px;
  }
  .status-Pending {
    color: $yellow;
  }
  .status-Pass {
    color: $green;
  }
  .status-Reject {
    color: $red;
  }
</style>