import React, { Fragment, useRef, useState, useEffect } from 'react';
import { useAccess } from '@umijs/max';
import { getCmsAppUserList } from '@/services/mobileusers/list';
import { getResumeDetail } from '@/services/resumeLibrary/resumeList'; // 简历库的简历详情接口
import { Button, FormInstance, message } from 'antd';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { EyeOutlined, UserOutlined } from '@ant-design/icons';
import { getDictValueEnum } from '@/services/system/dict';
import DictTag from '@/components/DictTag';
import ResumeDetail from '../components/detail';
import BehaviorLogList from '../components/logList'; 

function MobileUserList() {
  const access = useAccess();

  const formTableRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();

  const [currentRow, setCurrentRow] = useState<API.MobileUser.ListRow>();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  
  // 用户行为
  const [behaviorModalVisible, setBehaviorModalVisible] = useState<boolean>(false);
  const [selectedUserId, setSelectedUserId] = useState<string | number>('');
  const [selectedUserName, setSelectedUserName] = useState<string>('');

  // 字典枚举值
  const [sexEnum, setSexEnum] = useState<any>([]);
  const [educationEnum, setEducationEnum] = useState<any>([]);
  const [politicalEnum, setPoliticalEnum] = useState<any>([]);
  const [areaEnum, setAreaEnum] = useState<any>([]);


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

  // 查看简历详情
  const handleViewResume = async (userId: any) => {
    setLoading(true);
    try {
      const res = await getResumeDetail(userId);
      if (res.code === 200) {
        setCurrentRow(res.data);
        setModalVisible(true);
      } else {
        message.error(res.msg);
      }
    } catch (error) {
      message.error('获取简历详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 查看用户行为（
  const handleViewBehavior = (userId: any, userName: string) => {
    setSelectedUserId(userId);
    setSelectedUserName(userName || '未知用户');
    setBehaviorModalVisible(true);
  };

  const columns: ProColumns<API.MobileUser.ListRow>[] = [
    {
      title: '用户名',
      dataIndex: 'name',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '出生日期',
      dataIndex: 'birthDate',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '学历要求',
      dataIndex: 'education',
      valueType: 'select',
      align: 'center',
      valueEnum: educationEnum,
      render: (_, record) => {
        return <DictTag enums={educationEnum} value={record.education} />;
      },
    },
    {
      title: '区域',
      dataIndex: 'area',
      valueType: 'select',
      align: 'center',
      valueEnum: areaEnum,
      render: (_, record) => {
        return <DictTag enums={areaEnum} value={record.area} />;
      },
    },
    {
      title: '性别',
      dataIndex: 'sex',
      valueType: 'select',
      align: 'center',
      valueEnum: sexEnum,
      render: (_, record) => {
        return <DictTag enums={sexEnum} value={record.sex} />;
      },
    },
    {
      title: '政治面貌',
      dataIndex: 'politicalAffiliation',
      valueType: 'select',
      align: 'center',
      valueEnum: politicalEnum,
      render: (_, record) => {
        return <DictTag enums={politicalEnum} value={record.politicalAffiliation} />;
      },
    },
    {
      title: '期望薪资',
      dataIndex: 'minSalary',
      valueType: 'text',
      hideInSearch: true,
      align: 'center',
      render: (_, record) => (
        <span style={{ color: '#ff4d4f', fontWeight: 'bold' }}>
          {record.salaryMin || '面议'} - {record.salaryMax || '面议'}
        </span>
      ),
    },
    {
      title: '操作',
      hideInSearch: true,
      align: 'center',
      dataIndex: 'userId',
      width: 240,
      render: (userId, record) => (
        <div style={{ display: 'flex', justifyContent: 'center', gap: 8 }}>
          <Button
            type="primary"
            size="small"
            key="resume"
            icon={<EyeOutlined />}
            loading={loading && currentRow?.userId === userId}
            hidden={!access.hasPerms('mobileusers:list:viewResume')}
            onClick={() => handleViewResume(userId)}
          >
            用户简历
          </Button>
          <Button
            type="default"
            size="small"
            key="behavior"
            icon={<UserOutlined />}
            hidden={!access.hasPerms('mobileusers:list:viewBehavior')}
            onClick={() => handleViewBehavior(userId, record.name)}
          >
            用户行为
          </Button>
        </div>
      ),
    },
  ];

  return (
    <Fragment>
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.MobileUser.ListRow>
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="userId"
          key="mobileUserIndex"
          columns={columns}
          search={{
            labelWidth: 120,
          }}
          request={async (
            params: API.MobileUser.ListParams & {
              pageSize?: number;
              current?: number;
            },
          ) => {
            const res = await getCmsAppUserList({ ...params } as API.MobileUser.ListParams);
            return {
              data: res.rows,
              total: res.total,
              success: true,
            };
          }}
        />
      </div>
      
      {/* 简历详情弹窗 */}
      <ResumeDetail
        open={modalVisible}
        values={currentRow}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
      />
      
      {/* 用户行为记录弹窗 */}
      <BehaviorLogList
        userId={selectedUserId}
        userName={selectedUserName}
        open={behaviorModalVisible}
        onCancel={() => {
          setBehaviorModalVisible(false);
          setSelectedUserId('');
          setSelectedUserName('');
        }}
      />
    </Fragment>
  );
}

export default MobileUserList;