import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import type { ExamClient, ExamModalTab } from '../data/mockData';
import { EXAM_TAGS } from '../data/mockData';
import { ExamSection } from '../components/exam/ExamSection';
import { ExamModal } from '../components/exam/ExamModal';
import { getPhysicalExamCustomerList, getUserOwnedMenus } from '../api';

const APP_ID = 'b2b49e91d21446aeb14579930f732985';

export const ExamPage = () => {
  const [searchValue, setSearchValue] = useState<string>('');
  const [clients, setClients] = useState<ExamClient[]>([]);
  const [examSelectedId, setExamSelectedId] = useState<string>('');
  const [examPanelTab, setExamPanelTab] = useState<ExamModalTab>('detail');
  const [examModalOpen, setExamModalOpen] = useState(false);
  const [examFilterTags, setExamFilterTags] = useState<Set<(typeof EXAM_TAGS)[number]>>(new Set(['全部']));
  const [loading, setLoading] = useState(false);
  const [refreshSeq, setRefreshSeq] = useState(0);
  const navigate = useNavigate();

  // 进入页面时获取用户菜单权限
  useEffect(() => {
    const token = localStorage.getItem('accessToken');
    if (!token) {
      // 跳转登录
      navigate('/home');
      return;
    }
    getUserOwnedMenus({ app_id: APP_ID })
      .then((res) => {
        console.log('获取用户菜单权限返回内容:', res);
        let authCode: string[] = [];
        // 存储authCode
        for (const child of res.Data?.menus?.[0]?.children || []) {
          if (child.authCode) {
            authCode.push(child.authCode);
          }
        }
        localStorage.setItem('authCode', authCode.join(','));
      })
      .catch((err) => {
        console.error('获取用户菜单权限失败', err);
      });
  }, []);

  // 处理筛选标签切换（支持多选）
  const handleFilterChange = (tag: (typeof EXAM_TAGS)[number]) => {
    setExamFilterTags((prev) => {
      const next = new Set(prev);
      if (tag === '全部') {
        // 点击"全部"时，清空其他选择，只保留"全部"
        return new Set(['全部']);
      } else {
        // 点击其他标签时，移除"全部"，添加/移除当前标签
        next.delete('全部');
        if (next.has(tag)) {
          next.delete(tag);
          // 如果所有标签都被取消，则默认选择"全部"
          if (next.size === 0) {
            return new Set(['全部']);
          }
        } else {
          next.add(tag);
        }
      }
      return next;
    });
  };

  // 构建接口请求参数
  const getRequestPayload = useMemo(() => {
    const trimmed = searchValue.trim();
    const query_text = trimmed || null;

    // 根据选中的筛选标签设置标志位（支持多选）
    const is_all = examFilterTags.has('全部') ? 1 : 0;
    const is_morning = examFilterTags.has('上午') ? 1 : 0;
    const is_afternoon = examFilterTags.has('下午') ? 1 : 0;
    const is_high_customer = examFilterTags.has('高客') ? 1 : 0;
    const is_general_customer = examFilterTags.has('普客') ? 1 : 0;
    const is_registered = examFilterTags.has('已签到') ? 1 : 0;
    const is_not_registered = examFilterTags.has('未签到') ? 1 : 0;
    const is_individual_customer = examFilterTags.has('散客') ? 1 : 0;
    const is_group_customer = examFilterTags.has('团客') ? 1 : 0;

    return {
      query_text,
      is_all,
      is_morning,
      is_afternoon,
      is_high_customer,
      is_general_customer,
      is_registered,
      is_not_registered,
      is_individual_customer,
      is_group_customer,
    };
  }, [searchValue, examFilterTags]);

  // 从接口拉取体检客户列表
  useEffect(() => {
    setLoading(true);
    getPhysicalExamCustomerList(getRequestPayload)
      .then((res) => {
        const list = res.Data || [];
        const mapped: ExamClient[] = list.map((item) => {
          // 状态映射到联合类型
          const status: ExamClient['status'] =
            item.is_sign_in === 1
              ? '已签到'
              : (item.physical_exam_status_name ?? '').includes('餐')
                ? '用餐'
                : '体检中';

          const signStatus: ExamClient['signStatus'] = item.is_register === 1 ? '已签到' : '未签到';
          const customerType: ExamClient['customerType'] = item.customer_type === 1 ? '团客' : '散客';
          const vipType: ExamClient['vipType'] = item.is_vip === 1 ? '高客' : '普客';

          // 直接使用接口返回的耗时
          const elapsed = item.time_spent || '00:00';

          return {
            id: String(item.physical_exam_id ?? ''),
            name: item.customer_name || '未知客户',
            gender: '男', // 后端未提供，默认填充
            age: 0,
            level: item.member_level || (item.is_vip === 1 ? 'VIP' : '普通'),
            packageName: item.package_name || '未提供套餐',
            status,
            elapsed,
            checkedItems: [],
            pendingItems: [],
            channel: item.channel || '',
            vipType,
            signStatus,
            customerType,
            familyDoctorName: item.family_doctor_name || '',
            guidePrinted: item.is_print === 1,
            addonCount: item.add_item_count ?? 0,
            appointmentRemarks: item.appointment_remarks || null,
            physical_exam_status_name: item.physical_exam_status_name || null,
            is_sign_in: item.is_sign_in ?? 0,
          };
        });
        setClients(mapped);
        if (mapped.length && !examSelectedId) {
          setExamSelectedId(mapped[0].id);
        } else if (mapped.length === 0) {
          setExamSelectedId('');
        }
      })
      .catch((err) => {
        console.error('获取体检客户列表失败', err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [getRequestPayload, examSelectedId, refreshSeq]);

  const selectedExamClient: ExamClient | undefined = useMemo(
    () => clients.find((c) => c.id === examSelectedId) || clients[0],
    [clients, examSelectedId],
  );

  const handleOpenModal = (id: string, tab: ExamModalTab) => {
    setExamSelectedId(id);
    setExamPanelTab(tab);
    setExamModalOpen(true);
  };

  return (
    <>
      <ExamSection
        filteredClients={clients}
        selectedExamClient={selectedExamClient}
        examFilterTags={examFilterTags}
        onFilterChange={handleFilterChange}
        onOpenModal={handleOpenModal}
        searchValue={searchValue}
        onSearchChange={setSearchValue}
        loading={loading}
      />

      {examModalOpen && selectedExamClient && (
        <ExamModal
          client={selectedExamClient}
          tab={examPanelTab}
          onTabChange={(tab) => {
            setExamPanelTab(tab);
            setRefreshSeq((v) => v + 1);
          }}
          onClose={() => {
            setExamModalOpen(false);
            setRefreshSeq((v) => v + 1);
          }}
        />
      )}
    </>
  );
};


