import React, { useEffect, useRef, useState } from 'react';
import { Tag } from 'antd';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { getAppUserList } from '@/services/cms/appuser';
import { getDictValueEnum } from '@/services/system/dict';
import DictTag from '@/components/DictTag';

function AppUserList() {
  const actionRef = useRef<ActionType>();
  const [educationEnum, setEducationEnum] = useState<Record<string, any>>({});
  const [sexEnum, setSexEnum] = useState<Record<string, any>>({});
  const [areaEnum, setAreaEnum] = useState<Record<string, any>>({});
  const [politicalEnum, setPoliticalEnum] = useState<Record<string, any>>({});

  useEffect(() => {
    getDictValueEnum('education', true, true).then(setEducationEnum);
    getDictValueEnum('sys_user_sex', true).then(setSexEnum);
    getDictValueEnum('area', true, true).then(setAreaEnum);
    getDictValueEnum('political_affiliation', true, true).then(setPoliticalEnum);
  }, []);

  const columns: ProColumns<API.CmsAppUser.AppUserRow>[] = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      valueType: 'text',
      align: 'center',
      width: 80,
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      valueType: 'text',
      align: 'center',
      width: 120,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      valueType: 'text',
      align: 'center',
      width: 140,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      valueType: 'select',
      align: 'center',
      width: 80,
      valueEnum: sexEnum,
      render: (_, record) => <DictTag enums={sexEnum} value={record.sex} />,
    },
    {
      title: '年龄',
      dataIndex: 'age',
      valueType: 'text',
      align: 'center',
      width: 70,
      hideInSearch: true,
    },
    {
      title: '学历',
      dataIndex: 'education',
      valueType: 'select',
      align: 'center',
      width: 90,
      valueEnum: educationEnum,
      render: (_, record) => <DictTag enums={educationEnum} value={record.education} />,
    },
    {
      title: '地区',
      dataIndex: 'area',
      valueType: 'select',
      align: 'center',
      width: 100,
      valueEnum: areaEnum,
      render: (_, record) => <DictTag enums={areaEnum} value={record.area} />,
    },
    {
      title: '政治面貌',
      dataIndex: 'politicalAffiliation',
      valueType: 'select',
      align: 'center',
      width: 110,
      valueEnum: politicalEnum,
      render: (_, record) => <DictTag enums={politicalEnum} value={record.politicalAffiliation} />,
    },
    {
      title: '期望薪资',
      dataIndex: 'salaryRange',
      hideInSearch: true,
      align: 'center',
      width: 140,
      render: (_, record) => {
        if (!record.salaryMin && !record.salaryMax) return '-';
        return `${record.salaryMin ?? '-'} ~ ${record.salaryMax ?? '-'}`;
      },
    },
    {
      title: '身份证号',
      dataIndex: 'idCard',
      valueType: 'text',
      align: 'center',
      width: 170,
      render: (_, record) => {
        if (!record.idCard) return '-';
        const idCard = record.idCard.toString();
        if (idCard.length < 8) return idCard;
        return `${idCard.slice(0, 4)}${'*'.repeat(idCard.length - 8)}${idCard.slice(-4)}`;
      },
    },
    {
      title: '最后登录',
      dataIndex: 'loginDate',
      valueType: 'date',
      align: 'center',
      width: 110,
      hideInSearch: true,
      fieldProps: { format: 'YYYY-MM-DD' },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      align: 'center',
      hideInSearch: true,
      width: 160,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      align: 'center',
      hideInSearch: true,
      width: 160,
    },
  ];

  return (
    <div style={{ width: '100%' }}>
      <ProTable<API.CmsAppUser.AppUserRow>
        actionRef={actionRef}
        rowKey="userId"
        columns={columns}
        request={(params) => {
          const { current, pageSize, ...searchParams } = params;
          const filteredParams: Record<string, any> = {};
          Object.keys(searchParams).forEach((key) => {
            const val = searchParams[key];
            if (val !== undefined && val !== null && val !== '') {
              filteredParams[key] = val;
            }
          });
          return getAppUserList({
            pageNum: current,
            pageSize,
            ...filteredParams,
          }).then((res) => ({
            data: res.rows || [],
            total: res.total,
            success: true,
          }));
        }}
        search={{ labelWidth: 'auto' }}
        scroll={{ x: 'max-content' }}
        pagination={{ defaultPageSize: 10, showSizeChanger: true }}
        headerTitle="个人用户管理"
      />
    </div>
  );
}

export default AppUserList;
