<template>
  <div class="pa-3 white">
    <m-filter :option="filter" @search="handleSearch"></m-filter>
    <table-list
      class="mt-3"
      :headers="headers"
      :items="items"
      :total="total"
      :loading="loading"
      :show-select="false"
      :disable-sort="true"
      :canDelete="false"
      :isTools="false"
      :page-info="pageInfo"
      item-key="id"
      @pageHandleChange="pageHandleChange"
    >
      <template v-slot:navBtn>
        <v-btn class="elevation-5 buttons" color="primary" rounded @click="handleAdd"><v-icon left>mdi-plus</v-icon>新增</v-btn>
        <v-btn class="elevation-5 mx-2" color="primary" rounded @click="downloadTemplate"><v-icon left>mdi-download</v-icon>下载批量上传文件模板</v-btn>
        <Upload :is-upload="true" class="elevation-5" color="primary" :noClass="false" accept=".xls, .xlsx" :loading="uploadLoading" :disabled="uploadLoading" @click="batchImportUsers" @change="batchImportUsers">
          <v-icon left>mdi-upload</v-icon>
          批量导入用户
        </Upload>
      </template>
      <template #actions="{ item }">
        <td>
          <v-btn text color="primary" @click="handleEdit(item)">编辑</v-btn>
          <v-btn text color="warning" @click="handleReset(item)">重置密码</v-btn>
          <v-btn text color="error" @click="handleDelete(item.id)">删除</v-btn>
        </td>
      </template>
      <template #role="{ item }">
        <v-chip
          v-for="role in item.role"
          :key="role.id"
          small
          class="ma-2"
          color="info"
        >
          {{ role.roleName }}
        </v-chip>
      </template>
      <template v-slot:state="{ item }">
        <v-chip
          :color="item.state === 0 ? 'success' : 'error'"
          small
          outlined
        >
          {{ item.state === 0 ? '已启用' : '已冻结' }}
        </v-chip>
      </template>
      <template #createdTime="{ item }">
        {{ formatToTime(item.createdTime * 1000) }}
      </template>
    </table-list>

    <edit-dialog :visible.sync="show" :title="title"  @submit="handleSave" >
      <edit-user v-if="show" ref="user" :is-edit="isEdit" :item-data="itemData" style="padding-bottom: 150px;" />
    </edit-dialog>
    <edit-dialog :visible.sync="showReset" title="重置密码"  @submit="handleSaveReset" >
      <reset-password v-if="showReset" ref="password" />
    </edit-dialog>
  </div>
</template>

<script>
import MFilter from '@/components/Filter'
import TableList from '@/components/List/table.vue'
import EditDialog from '@/components/Dialog'
import EditUser from './components/editUser.vue'
import Upload from '@/components/UploadBtn'
import ResetPassword from './components/resetPassword.vue'
import util from '@/utils/base64ToFile'
import { getUserList, saveUser, deleteUser, resetPassword, downloadUserTemplate, userExcelExport } from '@/api/user'
import { getRoleList } from '@/api/menu'
import { currentTime } from '@/utils/date'
export default {
  name: 'user-list',
  components: { TableList, EditDialog, EditUser, ResetPassword, Upload, MFilter },
  data () {
    return {
      filter: {
        list: [
          {
            type: 'textField',
            key: 'searchKey',
            value: null,
            label: '用户名'
          }
        ]
      },
      query: {
        name: null,
        username: null
      },
      showReset: false,
      headers: [
        { text: '用户昵称', align: 'start', value: 'name' },
        { text: '账号', align: 'start', value: 'username' },
        { text: '人员编码', value: 'employeeCode' },
        { text: '电话', align: 'start', value: 'phone' },
        { text: '角色', align: 'start', value: 'role' },
        { text: '状态', align: 'start', value: 'state' },
        { text: '登陆时间', align: 'start', value: 'loginTime' },
        { text: '上次登录时间', align: 'start', value: 'lastLoginTime' },
        { text: '创建时间', align: 'start', value: 'createdTime' },
        { text: '操作', align: 'start', value: 'actions' }
      ],
      items: [],
      total: 0,
      pageInfo: {
        current: 1,
        size: 10
      },
      loading: false,
      isEdit: false,
      show: false,
      title: '新增',
      roleList: [],
      itemData: {},
      uploadLoading: false
    }
  },
  async created () {
    await this.initDice()
    await this.init()
  },
  methods: {
    formatToTime (str) {
      return currentTime(str)
    },
    async init () {
      try {
        this.loading = true
        const { data } = await getUserList({ ...this.pageInfo, ...this.query })
        this.items = data.records.map(e => {
          // e.roleName = e.role.map(_m => _m.roleName).toString()
          return e
        })
        this.total = data.total
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    },
    handleSearch (val) {
      // console.log(val)
      this.pageInfo.current = 1
      Object.assign(this.query, val)
      this.init()
    },
    async initDice () {
      try {
        const { data } = await getRoleList({ size: 999 })
        this.roleList = data.records
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    handleEdit (item) {
      this.title = '编辑用户'
      this.itemData = item
      this.isEdit = true
      this.show = true
    },
    handleAdd () {
      this.title = '新增用户'
      this.isEdit = false
      this.show = true
    },
    async handleSave () {
      if (!this.$refs.user.validate()) return
      const param = this.$refs.user.getValue()
      if (this.isEdit) param.id = this.itemData.id
      param.roleId = param.roleId.toString()
      try {
        await saveUser(param)
        this.$snackbar.success('保存成功')
        this.show = false
        this.init()
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    handleDelete (userId) {
      if (Array.isArray(userId)) return
      this.$confirm('提示', '是否确定删除该选项')
        .then(async () => {
          try {
            await deleteUser({ userId })
            this.$snackbar.success('删除成功')
            this.init()
          } catch (error) {
            this.$snackbar.error(error)
          }
        })
    },
    handleReset (item) {
      this.itemData = item
      this.showReset = true
    },
    async handleSaveReset () {
      if (!this.$refs.password.validate()) return
      const obj = this.$refs.password.getValue()
      const companyCode = this.itemData.companyInfo.companyCode
      const userId = this.itemData.id
      const param = {
        type: 1,
        userId,
        companyCode
      }
      Object.assign(param, obj)
      try {
        await resetPassword(param)
        this.showReset = false
        this.$snackbar.success('修改成功')
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    pageHandleChange (page) {
      this.pageInfo.current = page
      this.init()
    },
    // 下载批量上传文件模板
    async downloadTemplate () {
      try {
        const { data } = await downloadUserTemplate()
        util.downloadFileByByte(data, '批量上传文件模板.xls')
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // 批量上传用户
    async batchImportUsers (file) {
      const formData = new FormData()
      formData.append('file', file)
      this.uploadLoading = true
      try {
        await userExcelExport(formData)
        this.$snackbar.success('上传成功')
        this.init()
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.uploadLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
