<template>
  <div class="pa-3 white">
    <m-search :items="searchItems" v-model="searchValues" class="mb-3" @search="search"></m-search>
    <MTable
      v-loading="loading"
      :items="items"
      :headers="headers"
      :page-size="pageInfo.size"
      :page-current="pageInfo.current"
      :total="total"
      @page-change="handlePageChange"
    >
      <template #card-tools>
        <m-button type="orange" size="small" icon="el-icon-plus" @click="onAdd">新增</m-button>
      </template>
      <template #createdTime="scope">
        {{ dateFormat(scope.row.createdTime) }}
      </template>
      <template #state="scope">
        <el-tag size="small" :type="scope.row.state ? 'default' : 'success'">{{ scope.row.state ? '未启用' : '已启用' }}</el-tag>
      </template>
      <template #role="scope">
        <template v-if="scope.row.companyInfo?.homeUserId === scope.row.id">
          <el-tag size="small" type="danger">超级管理员</el-tag>
        </template>
        <template v-if="scope.row.role && scope.row.role.length">
          <el-tag
            v-for="item in scope.row.role"
            :key="item.id"
            size="small"
          >{{ item.roleName }}</el-tag>
        </template>
      </template>
      <template #actions="scope">
        <template v-if="scope.row.companyInfo?.homeUserId !== scope.row.id">
          <m-button type="primary" class="pa-0" text @click="onEdit(scope.row)">编辑</m-button>
          <m-button type="primary" class="pa-0" text @click="onSetRole(scope.row)">角色分配</m-button>
          <m-button type="warning" class="pa-0" text @click="onReset(scope.row)">重置密码</m-button>
          <m-button
            :type="scope.row.state ? 'success' : 'danger'"
            class="pa-0"
            text
            @click="onStatus(scope.row)"
          >
            {{ scope.row.state ? '启用' : '禁用' }}
          </m-button>
          <m-button type="danger" class="pa-0" text @click="onDelete(scope.row)">删除</m-button>
        </template>
      </template>
    </MTable>
    <UserEdit ref="dialog" @refresh="init"></UserEdit>
    <UserRole ref="userRefs" @refresh="init"></UserRole>
    <UserReset ref="userReset" @refresh="init"></UserReset>
  </div>
</template>

<script>
import UserEdit from './userEdit.vue'
import UserRole from './userRole.vue'
import UserReset from './userReset'
import util from '@/utils/base64ToFile'
import {
  getUserList,
  deleteUser,
  downloadUserTemplate,
  userExcelExport,
  blockUser
} from '@/api/user'
import { dateFormat } from '@/utils/date'
export default {
  name: 'user-list',
  components: {
    UserEdit,
    UserRole,
    UserReset
  },
  data () {
    return {
      searchItems: [
        {
          label: '用户查找',
          options: {
            placeholder: '请输入用户昵称 / 账号'
          },
          prop: 'searchKey',
          type: 'input'
        }
      ],
      searchValues: {
        searchKey: null
      },
      headers: [
        { label: '用户昵称', prop: 'name', width: 200 },
        { label: '账号', prop: 'username', width: 200 },
        { label: '人员编码', prop: 'employeeCode' },
        { label: '角色', prop: 'role' },
        { label: '状态', prop: 'state' },
        { label: '上次登录时间', prop: 'lastLoginTime', width: 150 },
        { label: '创建时间', prop: 'createdTime', width: 200 },
        { label: '操作', prop: 'actions', fixed: 'right', width: 300 }
      ],
      items: [],
      total: 0,
      pageInfo: {
        current: 1,
        size: 10
      },
      loading: false,
      showReset: false,
      show: false,
      uploadLoading: false
    }
  },
  async created () {
    await this.init()
  },
  methods: {
    dateFormat (str) {
      const date = new Date(+str * 1000)
      return dateFormat('YYYY-mm-dd HH:MM:SS', date)
    },
    async init () {
      try {
        this.loading = true
        const { data } = await getUserList({ ...this.pageInfo, ...this.searchValues })
        this.items = data.records
        this.total = data.total
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    },
    search (val) {
      this.pageInfo.current = 1
      this.init()
    },
    async onStatus (item) {
      const state = item.state ? 1 : 0
      try {
        await blockUser({
          userId: item.id,
          state: 1 ^ state
        })
        this.$message.success('保存成功')
        this.init()
      } catch (error) {
        this.$message.error(error)
      }
    },
    onEdit (item) {
      this.$refs.dialog.open(item)
    },
    onAdd () {
      this.$refs.dialog.open()
    },
    onSetRole (item) {
      this.$refs.userRefs.open(item)
    },
    onReset (item) {
      this.$refs.userReset.open(item)
    },
    onDelete (item) {
      this.$confirm('是否确定删除该选项', '提示')
        .then(async () => {
          try {
            await deleteUser({ userId: item.id })
            this.$message.success('删除成功')
            this.init()
          } catch (error) {
            this.$message.error(error)
          }
        })
        .catch(_ => {})
    },

    handlePageChange (page) {
      this.pageInfo.current = page
      this.init()
    },
    // 下载批量上传文件模板
    async downloadTemplate () {
      try {
        const { data } = await downloadUserTemplate()
        util.downloadFileByByte(data, '批量上传文件模板.xls')
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 批量上传用户
    async batchImportUsers (file) {
      const formData = new FormData()
      formData.append('file', file)
      this.uploadLoading = true
      try {
        await userExcelExport(formData)
        this.$message.success('上传成功')
        this.init()
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.uploadLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
