<template>
  <el-row>
    <!-- 表格头部 -->
    <el-row class="mb-20">
      <span class="list-title">
        用户管理
        <Lookicon v-if="filterButton('userManage_lookicon')" ref="Lookicon" :look-status="searchParams.lookStatus" @changeLook="changeLook" />
      </span>
      <el-button v-if="filterButton('userManage_add')" type="primary" :loading="global.loading" @click="$emit('rowOperation', {}, -1, 'add')">新增</el-button>
      <!-- <el-button v-if="filterButton('export')" :loading="global.loading" @click="exportExcel">导出</el-button> -->
    </el-row>
    <!-- 表格内容 -->
    <TableElement
      :table-data="list"
      :colum-obj="columObj"
      :page-obj="pageObj"
      :loading="global.loading"
      @rowOperation="rowOperation"
      @selectionChange="selectionChange"
      @getList="getList()"
    />
  </el-row>
</template>
<script>
import TableElement from '@/components/ElmTable/index.vue'
import request from '@/utils/request'
import { deepClone } from '@/utils'

export default {
  components: { TableElement },
  inject: ['global'],
  props: {
    treeIds: { // 侧边栏
      type: String,
      default: ''
    },
    searchParams: { // 搜索栏
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      openExport: false,
      list: [], // 数据
      selectedList: [], // 选中的数据
      pageObj: { // 分页配置
        current: 1,
        size: 10,
        total: 0,
        pages: 0
      },
      columObj: {
        lazy: 'true',
        columnData: [
          { text: true, prop: 'username', label: '账号', minwidth: '90' },
          { ownDefined: true, prop: 'nickname', label: '姓名', minwidth: '90', ownDefinedReturn: row => row.nickname || '--' },
          { ownDefined: true, prop: 'mobile', label: '手机号', minwidth: '100', ownDefinedReturn: row => row.mobile || '--' },
          { ownDefined: true, prop: 'deptName', label: '所属组织', minwidth: '180', ownDefinedReturn: row => row.deptName || '--' },
          // { ownDefined: true, prop: 'roleIds', label: '分配角色', minwidth: '100', ownDefinedReturn: row => row.roleNames.toString() || '--' },
          { ownDefined: true, prop: 'status', label: '状态', minwidth: '60', ownDefinedReturn: row => this.global.dict.status[row.status], ownClassName: row => row.status == 0 ? 'disabled' : '' },
          { ownDefined: true, prop: 'loginTime', label: '最后一次登录时间', sortable: true, sortType: 'date', minwidth: '160', ownDefinedReturn: row => row.loginTime },
          { ownDefined: true, prop: 'remark', label: '备注', minwidth: '160', ownDefinedReturn: row => row.remark || '--' },
          {
            isOperation: true, prop: 'operation', label: '操作', minwidth: '160', fixed: 'right', tooltip: false,
            operation: [
              { operation: 'seeDetail', type: 'text', label: '查看', isShow: () => this.filterButton('userManage_view') || this.isAdmin },
              { operation: 'edit', type: 'text', label: '编辑', isShow: () => (this.filterButton('userManage_edit') || this.isAdmin) },
              { operation: 'resetPassword', type: 'text', label: '重置密码', isShow: (row) => this.filterButton('userManage_resetPassword') && (row.id !== JSON.parse(localStorage.getItem('manager-userLogin')).id || this.isAdmin) },
              { operation: 'toggleStatus', type: 'text', label: '启用', labelRow: row => row.status === 0 ? '停用' : '启用',
                isShow: (row) => (this.filterButton('userManage_disable') || this.isAdmin) },
              { operation: 'delete', type: 'text', label: '删除',
                isShow: (row) => (row.isDefault == 0 && this.filterButton('userManage_delete') || this.isAdmin) }
            ]
          }
        ]
      }
    }
  },
  methods: {
    async getList(params) { // 表格数据 - 获取
      this.global.loading = true
      if (params != null) this.searchParams = params
      try {
        // TODO: 获取数据
        // const { data } = { data: { records: [{ name: 'test' }], pages: 1, total: 1 }}
        const { data } = await request('/sys/user/page', { params: this.genQuery() })
        // const { data } = await getInvitationPage(this.genQuery())
        const { records, pages, total } = data
        this.list = this.filterTabledata(records)
        Object.assign(this.pageObj, { pages, total })
      } finally {
        this.global.loading = false
      }
    },
    filterTabledata(list) { // 表格数据 - 过滤
      return list.map(item => ({
        ...item
        // TODO: 表格数据展示是否要转换（看情况）
      }))
    },
    async exportExcel() { // 导出
      this.global.loading = true
      try {
        // TODO: 导出接口
        const res = await request('/tuserlists/userExport', { params: this.genQuery() })
        // const res = await exportExchangeOrder(this.genQuery())
        this.downloadExcel(res)
      } finally {
        this.global.loading = false
      }
    },
    genQuery() { // 产生最终参数
      const { current, size } = this.pageObj
      const query = Object.assign({ current, size }, this.filterSearchParams()) // 分页 & 查询
      return query
    },
    filterSearchParams() { // 查询字段过滤（请求数据过滤查询不影响原数据）
      // 复制一份
      const params = deepClone(this.searchParams)
      // 自定义部分
      // TODO: 搜索数据过滤
      // if (this.searchParams.timerange?.length) {
      //   params['starttime'] = this.searchParams.timerange[0]
      //   params['endtime'] = this.searchParams.timerange[1]
      //   delete params.timerange
      // }
      // 过滤空数据
      Object.entries(params).forEach(([key, val]) => {
        if (val == null || val === '') delete params[key]
      })
      return params
    },
    rowOperation(row, idx, actionName) { // 行操作
      console.log(actionName, row)
      this.$emit('rowOperation', row, idx, actionName)
    },
    selectionChange(list) { // 行选择
      this.selectedList = list
    },
    changeLook(e) {
      this.searchParams.lookStatus = e
      this.getList()
    }
  }
}
</script>

<style scoped>

</style>

