<template>
    <div class='table-box' ref='popupBaseView'>
      <ProTable
        ref='proTable'
        :columns='columns'
        :request-api="getTableList"
      >
      <!-- :data='userData' -->
        <!-- 表格 header 按钮 -->
        <template #tableHeader='scope'>
          <el-button  v-auth.user="'add'" type='primary' :icon='CirclePlus' @click="openDialog('add')">新增</el-button>
          <el-button  v-auth.user="'delete'" type='danger' :icon='Delete' plain :disabled='!scope.isSelected'
                     @click='batchDelete(scope.selectedListIds)'>
          删除
          </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation='scope'>
          <el-button v-auth.user="'edit'" type='primary' link :icon='EditPen' @click="openDialog('edit', scope.row)">编辑</el-button>
          <el-button v-auth.user="'delete'" type='primary' link :icon='Delete' @click='handleDelete(scope.row)'>删除</el-button>
          <el-button v-auth.user="'editPassWord'" type='primary' link :icon='Delete' @click='EditPassWord(scope.row)'>修改密码</el-button>
          </template>

      </ProTable>
    </div>
    <UserPopup :refresh-table='proTable?.getTableList' ref='userPopup' />

    <PassWordPopup :refresh-table='proTable?.getTableList' ref='passWordPopup' />

    </template>

  <script setup lang='tsx' name='useRole'>
  import TimeControl from '@/components/TimeControl/index.vue'
  import { type User } from '@/api/user/interface/user'
  import { useHandleData } from '@/hooks/useHandleData'
  import ProTable from '@/components/ProTable/index.vue'
  import UserPopup from './components/userPopup.vue'
  import PassWordPopup from './components/passWordPopup.vue'
  import ImportExcel from '@/components/ImportExcel/index.vue'
  import { type ProTableInstance, type ColumnProps } from '@/components/ProTable/interface'
  import { CirclePlus, Delete, EditPen} from '@element-plus/icons-vue'
  import { useDictStore } from '@/stores/modules/dict'
  import {getUserList, deleteUser,getRoleList} from '@/api/user/user'
  import { onMounted, reactive, ref } from 'vue'
  import { type Role } from '@/api/user/interface/role'
  const roleList = ref<Role.RoleBO[]>([])
  const dictStore = useDictStore()
  const userPopup = ref()
  const passWordPopup = ref()
  // ProTable 实例
  const proTable = ref<ProTableInstance>()


  // 初始化时获取角色列表
  onMounted(async () => {
    const response = await getRoleList()
    roleList.value = response.data as unknown as Role.RoleBO[]
  })

  // 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
  // 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
  const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params))
  newParams.searchEndTime = endDate.value
  newParams.searchBeginTime = startDate.value
  return getUserList(newParams)
}

  // 表格配置项
  const columns = reactive<ColumnProps<User.ResUser>[]>([
    { type: 'selection', fixed: 'left', width: 70 },
    { type: 'index', fixed: 'left', width: 70, label: '序号' },
    {
      prop: 'name',
      label: '用户名',
      search: { el: 'input' },
      minWidth: 150,
    },
    {
      prop: 'loginName',
      label: '登录名',
      minWidth: 150,
    },
    {
      prop: 'roleNames',
      label: '角色',
      minWidth: 250,
      render: (scope) => {
      const roleNames = scope.row.roleNames;
      const roleArray = Array.isArray(roleNames) ? roleNames : [roleNames];
      if (roleArray.length > 1) {
        return roleArray.join(', ');
      }
      return roleArray[0] || ''; // 添加默认值
    },
  },
    {
      prop: 'phone',
      label: '手机号',
      minWidth: 150,
    },
    {
      prop: 'email',
      label: '邮箱',
      minWidth: 150,
    },
    {
      prop: 'loginTime',
      label: '最后一次登录时间',
      minWidth: 180,
      search: {
      render: () => {
        return (
            <div class='flx-flex-start'>
              <TimeControl
                  include={['日', '周', '月', '自定义']}
                  default={'月'}
                  onUpdate-dates={handleDateChange}
              />
            </div>
        )
      },
    },
    },
    {
      prop: 'state',
      label: '状态',
      minWidth: 100,
      enum: dictStore.getDictData('state'),
      fieldNames: { label: 'label', value: 'code' },
      render: (scope: { row: { state: any } }) => {
      const { tagType, tagText } = getTagTypeAndText(scope.row.state);
      return (<el-tag type={tagType}>{tagText}</el-tag>);
    }
    },
    { prop: 'operation', label: '操作', fixed: 'right', width: 250 },
  ])


  // 提取出生成 tag 的逻辑
  const getTagTypeAndText = (state: number) => {
  let tagType = 'danger'; // 默认标签类型为 'danger'
  let tagText = '';

  switch(state) {
    case 1:
      tagType = 'success'; // 正常
      tagText = '正常';
      break;
    case 2:
      tagType = 'warning'; // 锁定
      tagText = '锁定';
      break;
    case 3:
      tagType = 'info'; // 待审核
      tagText = '待审核';
      break;
    case 4:
      tagType = 'default'; // 休眠
      tagText = '休眠';
      break;
    case 5:
      tagType = 'warning'; // 密码过期
      tagText = '密码过期';
      break;
    case 0:
    default:
      tagType = 'danger'; // 删除
      tagText = '删除';
      break;
  }

  return { tagType, tagText };
}

  // 处理日期变化的回调函数
const startDate = ref('')
const endDate = ref('')
const handleDateChange = (startDateTemp: string, endDateTemp: string) => {
  startDate.value = startDateTemp
  endDate.value = endDateTemp
}

// 打开 drawer(新增、编辑)
const openDialog = (titleType: string, row: Partial<User.ResUser> = {}) => {
 userPopup.value?.open(titleType, row,roleList.value)

}

  // 删除用户信息
  const handleDelete = async (params: User.ResUser) => {
    await useHandleData(deleteUser,  [params.id] , `删除【${params.name}】用户`)
    proTable.value?.getTableList()
  }

  // 批量删除用户信息
  const batchDelete = async (id: string[]) => {
    await useHandleData(deleteUser, id , '删除所选用户信息')
    proTable.value?.clearSelection()
    proTable.value?.getTableList()
  }


  // 修改密码
  const EditPassWord = async (row: User.ResPassWordUser) => {
    passWordPopup.value?.open(row)

  }


  </script>
  