import { ModalForm, ProDescriptions } from '@ant-design/pro-components';
import { Image, Card, Divider, Row, Col, Tag, Timeline, Empty,Avatar } from 'antd';
import React, { useEffect, useState } from 'react';
import { getDictValueEnum } from '@/services/system/dict';
import DictTag from '@/components/DictTag';
import mockData from './preView.json';

export type ResumeDetailProps = {
  onCancel: (flag?: boolean, formVals?: unknown) => void;
  open: boolean;
  values?: any;
};

// 标签颜色
const TAG_COLORS = [
  'magenta',
  'red',
  'volcano',
  'orange',
  'gold',
  'lime',
  'green',
  'cyan',
  'blue',
  'geekblue',
  'purple',
  '#f50',
  '#2db7f5',
  '#87d068',
  '#108ee9',
];

// 标签颜色 基于文本hash
const getTagColor = (tag: string) => {
  let hash = 0;
  for (let i = 0; i < tag.length; i++) {
    hash = tag.charCodeAt(i) + ((hash << 5) - hash);
  }
  const index = Math.abs(hash) % TAG_COLORS.length;
  return TAG_COLORS[index];
};

const ResumeDetail: React.FC<ResumeDetailProps> = (props) => {
  const [sexEnum, setSexEnum] = useState<any>([]);
  const [educationEnum, setEducationEnum] = useState<any>([]);
  const [politicalEnum, setPoliticalEnum] = useState<any>([]);
  const [areaEnum, setAreaEnum] = useState<any>([]);
  const [experienceEnum, setExperienceEnum] = useState<any>([]);
  const [ageEnum, setAgeEnum] = 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);
    });
    getDictValueEnum('experience', true, true).then((data) => {
      setExperienceEnum(data);
    });
  }, []);

  const handleCancel = () => {
    props.onCancel();
  };

  const { values } = props;
  // const values = mockData;

  // 格式化时间显示
  const formatTimeRange = (start: string, end: string) => {
    if (!start && !end) return '';
    return `${start || ''} - ${end || '至今'}`;
  };

  // 渲染空状态
  const renderEmpty = (description: string) => (
    <Empty
      image={Empty.PRESENTED_IMAGE_SIMPLE}
      description={description}
      style={{ margin: '20px 0' }}
    />
  );

  // 渲染标签组
  const renderTags = () => {
    const tags = values?.indices || [];
    
    if (!tags || tags.length === 0) {
      return null;
    }

    return (
      <div 
        style={{ 
          marginTop: 2,
          padding: '8px 16px',
          borderRadius: 8,
          border: '1px dashed #eaeaeaff'
        }}
      >
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 , justifyContent:"center" }}>
          {tags.map((tag: string, index: number) => (
            <Tag
              key={index}
              color={getTagColor(tag)}
              style={{
                padding: '4px 12px',
                fontSize: '13px',
                fontWeight: 500,
                borderRadius: 12,
                boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                border: 'none',
                cursor: 'default',
              }}
            >
              {tag}
            </Tag>
          ))}
        </div>
      </div>
    );
  };

  return (
    <ModalForm
      title="人才信息详情"
      open={props.open}
      width={1000}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => handleCancel(),
        footer: null,
        width: 1200,
        styles: {
          body: { maxHeight: '80vh', overflowY: 'auto', padding: '16px', top: '50vh' },
        },
      }}
      submitter={false}
    >
      {/* 基本信息卡片 */}
      <Card
        title="基本信息"
        style={{ marginBottom: 16 }}
        size="small"
        styles={{
          header: { backgroundColor: '#fafafa' },
        }}
      >
        <Row gutter={16}>
          <Col span={6}>
            <div style={{ textAlign: 'center' }}>
               {values?.avatar ? (
                <Avatar
                  size={100}
                  src={values.avatar}
                  style={{
                    borderRadius: '50%',
                    border: '4px solid #e8f4fd',
                  }}
                />
              ) : (
                <Avatar
                  size={100}
                  style={{
                    backgroundColor: '#1890ff',
                    fontSize: 36,
                    borderRadius: '50%',
                    border: '4px solid #e8f4fd',
                  }}
                >
                  {values?.name?.charAt(0) || 'U'}
                </Avatar>
              )}
              <h3 style={{ margin: '8px 0 4px 0', color: '#1890ff' }}>
                {values?.name || '未填写'}
              </h3>
              <p style={{ margin: 0, color: '#666', fontSize: 12 }}>
                {values?.jobTitle?.join(' / ') || '暂无期望岗位'}
              </p>
            </div>
            
            {renderTags()}
          </Col>
          
          <Col span={18}  style={{display:'flex',alignItems:'center'}}>
            <ProDescriptions
              column={3}
              dataSource={values || {}}
              size="default"
              labelStyle={{ fontWeight: 'bold', color: '#333' }}
              contentStyle={{ color: '#666' }}
            >
              {/* <ProDescriptions.Item dataIndex="userId" label="用户ID" /> */}
              <ProDescriptions.Item
                dataIndex="sex"
                label="性别"
                render={(text) => <DictTag enums={sexEnum} value={text as string} />}
              />
              <ProDescriptions.Item dataIndex="age" label="年龄" />
              <ProDescriptions.Item
                dataIndex="education"
                label="学历"
                render={(text) => <DictTag enums={educationEnum} value={text as string} />}
              />
              <ProDescriptions.Item
                dataIndex="experience"
                label="工作经验"
                render={(text) => <DictTag enums={experienceEnum} value={text as string} />}
              />
              <ProDescriptions.Item dataIndex="workYears" label="工作年限" />
              <ProDescriptions.Item dataIndex="phone" label="手机号" />
              <ProDescriptions.Item
                dataIndex="politicalAffiliation"
                label="政治面貌"
                render={(text) => <DictTag enums={politicalEnum} value={text as string} />}
              />
              <ProDescriptions.Item dataIndex="birthDate" label="出生日期" />
              <ProDescriptions.Item dataIndex="idNumber" label="身份证号" />
              <ProDescriptions.Item dataIndex="contactEmail" label="邮箱" />

              <ProDescriptions.Item
                dataIndex="area"
                label="期望工作地"
                render={(text) => <DictTag enums={areaEnum} value={text as string} />}
              />

              <ProDescriptions.Item
                dataIndex="salaryMin"
                label="期望薪资"
                render={(text, record) => (
                  <span style={{ color: '#ff4d4f', fontWeight: 'bold' }}>
                    {record.salaryMin || '面议'} - {record.salaryMax || '面议'} 元/月
                  </span>
                )}
              />
            </ProDescriptions>
          </Col>
        </Row>

        {/* 附加信息 */}
        <Divider style={{ margin: '12px 0' }} />
        <Row gutter={16}>
          <Col span={12}>
            <div>
              <strong>毕业院校：</strong>
              {values?.graduationSchool || '未填写'}
            </div>
          </Col>
          <Col span={12}>
            <div>
              <strong>就读专业：</strong>
              {values?.major || '未填写'}
            </div>
          </Col>
          <Col span={24} style={{ marginTop: 8 }}>
            <div>
              <strong>居住地址：</strong>
              {values?.residenceAddress || '未填写'}
            </div>
          </Col>
        </Row>
      </Card>

 {/* 个人介绍与求职意向 */}
      <Card
        title="个人介绍与求职意向"
        style={{ marginBottom: 16 }}
        size="small"
        styles={{
          header: { backgroundColor: '#fafafa' },
        }}
      >
        <Row gutter={16}>
          <Col span={24} style={{ marginBottom: 12 }}>
            <div>
              <strong style={{ color: '#1890ff' }}>个人简要介绍：</strong>
              <div
                style={{
                  marginTop: 8,
                  color: '#666',
                  lineHeight: 1.6,
                  padding: 12,
                  backgroundColor: '#f8f9fa',
                  borderRadius: 4,
                }}
              >
                {values?.introduction || '暂无个人介绍'}
              </div>
            </div>
          </Col>
          <Col span={24} style={{ marginBottom: 12 }}>
            <div>
              <strong style={{ color: '#1890ff' }}>求职意向岗位：</strong>
              <div
                style={{
                  marginTop: 8,
                  color: '#666',
                  lineHeight: 1.6,
                  padding: 12,
                  backgroundColor: '#f8f9fa',
                  borderRadius: 4,
                }}
              >
                {values?.jobIntention || '暂无求职意向'}
              </div>
            </div>
          </Col>
          <Col span={24}>
            <div>
              <strong style={{ color: '#1890ff' }}>自我评价：</strong>
              <div
                style={{
                  marginTop: 8,
                  color: '#666',
                  lineHeight: 1.6,
                  padding: 12,
                  backgroundColor: '#f8f9fa',
                  borderRadius: 4,
                }}
              >
                {values?.selfEvaluation || '暂无自我评价'}
              </div>
            </div>
          </Col>
        </Row>
      </Card>

      {/* 教育经历 */}
      <Card
        title={`教育经历 (${values?.educationExp?.length || 0})`}
        style={{ marginBottom: 16 }}
        size="small"
        styles={{
          header: { backgroundColor: '#fafafa' },
        }}
      >
        {values?.educationExp?.length > 0 ? (
          <Timeline>
            {values.educationExp.map((edu: any, index: number) => (
              <Timeline.Item key={index} color="green">
                <div style={{ padding: '8px 0' }}>
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'flex-start',
                    }}
                  >
                    <div>
                      <strong style={{ fontSize: 14, color: '#1890ff' }}>
                        {edu.school || '未填写学校'}
                      </strong>
                      <div style={{ color: '#666', marginTop: 4, display: 'flex' }}>
                        {edu.major || '未填写专业'} | {edu.degree || '未填写学位'} |
                        <div style={{ marginLeft: 5 }}>
                          <DictTag enums={educationEnum} value={edu.education} />
                        </div>{' '}
                      </div>
                    </div>
                    <div style={{ color: '#999', fontSize: 12, textAlign: 'right' }}>
                      {formatTimeRange(edu.startTime, edu.endTime)}
                    </div>
                  </div>
                  {(edu.degreeDate || edu.graduation) && (
                    <div style={{ color: '#999', fontSize: 12, marginTop: 4 }}>
                      {edu.degreeDate && `学位授予: ${edu.degreeDate}`}
                      {edu.graduation && ` 毕业日期: ${edu.graduation}`}
                    </div>
                  )}
                </div>
              </Timeline.Item>
            ))}
          </Timeline>
        ) : (
          renderEmpty('暂无教育经历')
        )}
      </Card>

      {/* 工作经历 */}
      <Card
        title={`工作经历 (${values?.workExp?.length || 0})`}
        style={{ marginBottom: 16 }}
        size="small"
        styles={{
          header: { backgroundColor: '#fafafa' },
        }}
      >
        {values?.workExp?.length > 0 ? (
          <Timeline>
            {values.workExp.map((work: any, index: number) => (
              <Timeline.Item key={index} color="blue">
                <div style={{ padding: '8px 0' }}>
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'flex-start',
                    }}
                  >
                    <div>
                      <strong style={{ fontSize: 14, color: '#1890ff' }}>
                        {work.company || '未填写公司'}
                      </strong>
                      <div style={{ color: '#666', marginTop: 4 }}>
                        {work.position || '未填写职位'} | {work.department || '未填写部门'}
                        {work.isFullTime !== null && (
                          <Tag
                            color={work.isFullTime ? 'blue' : 'orange'}
                            style={{ marginLeft: 8 }}
                          >
                            {work.isFullTime ? '全职' : '兼职'}
                          </Tag>
                        )}
                      </div>
                    </div>
                    <div style={{ color: '#999', fontSize: 12, textAlign: 'right' }}>
                      {formatTimeRange(work.startTime, work.endTime)}
                    </div>
                  </div>
                  {work.duty && (
                    <div
                      style={{
                        color: '#666',
                        marginTop: 8,
                        lineHeight: 1.6,
                        fontSize: 13,
                        padding: 8,
                        backgroundColor: '#f8f9fa',
                        borderRadius: 4,
                      }}
                    >
                      {work.duty}
                    </div>
                  )}
                  {work.salary && (
                    <div style={{ color: '#ff4d4f', fontSize: 12, marginTop: 4 }}>
                      薪资: {work.salary}
                    </div>
                  )}
                </div>
              </Timeline.Item>
            ))}
          </Timeline>
        ) : (
          renderEmpty('暂无工作经历')
        )}
      </Card>

      {/* 项目经历 */}
      <Card
        title={`项目经历 (${values?.projectExp?.length || 0})`}
        style={{ marginBottom: 16 }}
        size="small"
        styles={{
          header: { backgroundColor: '#fafafa' },
        }}
      >
        {values?.projectExp?.length > 0 ? (
          <Timeline>
            {values.projectExp.map((project: any, index: number) => (
              <Timeline.Item key={index} color="purple">
                <div style={{ padding: '8px 0' }}>
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'flex-start',
                    }}
                  >
                    <div>
                      <strong style={{ fontSize: 14, color: '#1890ff' }}>
                        {project.name || '未填写项目名称'}
                      </strong>
                      <div style={{ color: '#666', marginTop: 4 }}>
                        {project.role || '未填写角色'} | {project.position || '未填写岗位'}
                      </div>
                    </div>
                    <div style={{ color: '#999', fontSize: 12, textAlign: 'right' }}>
                      {formatTimeRange(project.startTime, project.endTime)}
                    </div>
                  </div>
                  {project.tasks && (
                    <div
                      style={{
                        color: '#666',
                        marginTop: 8,
                        lineHeight: 1.6,
                        fontSize: 13,
                        padding: 8,
                        backgroundColor: '#f8f9fa',
                        borderRadius: 4,
                      }}
                    >
                      {project.tasks}
                    </div>
                  )}
                </div>
              </Timeline.Item>
            ))}
          </Timeline>
        ) : (
          renderEmpty('暂无项目经历')
        )}
      </Card>

      {/* 技能特长 */}
      <Card
        title={`技能特长 (${values?.skillList?.length || 0})`}
        style={{ marginBottom: 16 }}
        size="small"
        styles={{
          header: { backgroundColor: '#fafafa' },
        }}
      >
        {values?.skillList?.length > 0 ? (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
            {values.skillList.map((skill: any, index: number) => (
              <Card.Grid
                key={index}
                style={{
                  width: 'calc(50% - 6px)',
                  boxShadow: 'none',
                  border: '1px solid #f0f0f0',
                  borderRadius: 6,
                }}
              >
                <div>
                  <Tag color="blue" style={{ marginBottom: 8, fontSize: 12 }}>
                    {skill.skill}
                  </Tag>
                  {skill.proficiency && (
                    <div style={{ color: '#666', fontSize: 12, lineHeight: 1.5 }}>
                      {skill.proficiency}
                    </div>
                  )}
                </div>
              </Card.Grid>
            ))}
          </div>
        ) : (
          renderEmpty('暂无技能特长')
        )}
      </Card>

      {/* 证书资质 */}
      <Card
        title={`证书资质 (${values?.certificateList?.length || 0})`}
        style={{ marginBottom: 16 }}
        size="small"
        styles={{
          header: { backgroundColor: '#fafafa' },
        }}
      >
        {values?.certificateList?.length > 0 ? (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {values.certificateList.map((cert: any, index: number) => (
              <Card.Grid
                key={index}
                style={{
                  width: 'calc(33.33% - 6px)',
                  boxShadow: 'none',
                  border: '1px solid #f0f0f0',
                  borderRadius: 6,
                }}
              >
                <div>
                  <div style={{ fontWeight: 'bold', color: '#1890ff', fontSize: 13 }}>
                    {cert.name}
                  </div>
                  <div style={{ color: '#666', fontSize: 11, marginTop: 4 }}>
                    颁发单位: {cert.grantUnit || '未填写'}
                  </div>
                  <div style={{ color: '#999', fontSize: 10, marginTop: 2 }}>
                    {cert.issueTime && `颁发时间: ${cert.issueTime}`}
                    {cert.managementPeriod && ` | 有效期: ${cert.managementPeriod}`}
                  </div>
                </div>
              </Card.Grid>
            ))}
          </div>
        ) : (
          renderEmpty('暂无证书资质')
        )}
      </Card>

      {/* 专业技术职务 */}
      <Card
        title={`专业技术职务 (${values?.professionalTechnicalPostList?.length || 0})`}
        size="small"
        styles={{
          header: { backgroundColor: '#fafafa' },
        }}
      >
        {values?.professionalTechnicalPostList?.length > 0 ? (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {values.professionalTechnicalPostList.map((post: any, index: number) => (
              <Card.Grid
                key={index}
                style={{
                  width: 'calc(50% - 4px)',
                  boxShadow: 'none',
                  border: '1px solid #f0f0f0',
                  borderRadius: 6,
                }}
              >
                <div>
                  <div style={{ fontWeight: 'bold', color: '#1890ff', fontSize: 13 }}>
                    {post.seriesLevelName} - {post.postSeriesName}
                  </div>
                  <div style={{ color: '#666', fontSize: 11, marginTop: 4 }}>
                    聘任单位: {post.appointmentUnit || '未填写'}
                  </div>
                  <div style={{ color: '#999', fontSize: 10, marginTop: 2 }}>
                    {post.appointmentTime && `聘任时间: ${post.appointmentTime}`}
                    {post.fullTimeOrPartTime && ` | ${post.fullTimeOrPartTime}`}
                  </div>
                  {post.mainPost && (
                    <div style={{ color: '#666', fontSize: 11, marginTop: 4 }}>
                      主要职务: {post.mainPost}
                    </div>
                  )}
                </div>
              </Card.Grid>
            ))}
          </div>
        ) : (
          renderEmpty('暂无专业技术职务')
        )}
      </Card>
    </ModalForm>
  );
};

export default ResumeDetail;