import DeviceList, { DeviceInfo } from './components/VirtualCard';
import { useEffect, useState } from 'react';
import {
  getSchoolManClassApi,
  getSchoolManListApi,
  locateSoftToSchoolApi,
} from './api/virtualCard';
import { message, Modal } from 'antd';
import styles from './index.module.less';
import TopCategory, { RawCategoryData } from './components/TopCategory';
import { useNavigate } from 'react-router-dom';
import LocateSoftModal from './components/LocateSoftModal';

const DeviceListExample: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize] = useState<number>(8);
  const [total, setTotal] = useState<number>(0);
  const [deviceList, setDeviceList] = useState<DeviceInfo[]>([]);
  // 顶部搜索
  const [classId, setClassId] = useState<number | null>(null);
  const [categoryData, setCategoryData] = useState<RawCategoryData[]>([]);
  const [topSearchParams, setTopSearchParams] = useState<{
    softwareName?: string;
    softNo?: string;
    company?: string;
    type?: string;
  }>({});
  const [filterState, setFilterState] = useState({
    major: '全部',
    category: '全部',
  });

  // locateModal
  const [isLocateModalOpen, setIsLocateModalOpen] = useState<boolean>(false);
  const [locateSoftItemData, setLocateSoftItemData] = useState<DeviceInfo>();
  const [locateSoftItemId, setLocateSoftItemId] = useState<any>();

  const getSchoolManList = async (
    page: number,
    size: number,
    classId?: number | null,
    topSearchParams?: { softwareName?: string; softNo?: string; company?: string }
  ) => {
    // setLoading(true);
    let params = {
      page,
      size,
      classId,
      ...topSearchParams,
    };
    try {
      const res = (await getSchoolManListApi(params)) as any;
      setDeviceList(res?.data.records);
      setTotal(res.data.total || res.data.records.length || 0);
      setLoading(false);
    } catch (error) {
      console.error('获取设备列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getSchoolManList(currentPage, pageSize, classId, topSearchParams);
  }, [currentPage, pageSize, classId, topSearchParams]);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  const handleEdit = (device: DeviceInfo) => {
    console.log('编辑设备:', device);
    // 打开编辑模态框等操作
  };

  const handleToLocate = (device: DeviceInfo) => {
    setLocateSoftItemData(device);
    setLocateSoftItemId(device.id);
    setIsLocateModalOpen(true);
  };
  const handleConfirmLocate = async (data: any) => {
    try {
      const { softId, dep_ids, user_ids, group_ids } = data;
      const res = (await locateSoftToSchoolApi(softId, dep_ids, user_ids, group_ids)) as any;
      if (res.data) {
        message.success('分配学校成功');
      }
    } catch (err) {
      message.error('软件分配失败');
      console.log(err, '软件分配失败');
    } finally {
      // setLoading(false);
      setIsLocateModalOpen(false);
    }
  };

  const handleToDetail = (id: any) => {
    navigate(`/virtual/softwareCard/${id}`);
  };

  const getCategoryList = async () => {
    try {
      const res = await getSchoolManClassApi();
      // @ts-ignore
      if (res && res?.data) {
        // @ts-ignore
        setCategoryData(res.data);
      } else {
        message.error('获取分类信息失败');
      }
    } catch (e) {
      console.log(e);
      setCategoryData([]);
      message.error('获取分类信息失败');
    }
  };
  useEffect(() => {
    getCategoryList();
  }, []);

  const handleFilterChange = (major: string, category: string) => {
    setFilterState({ major, category });
    let idSelect = major === '全部' ? null : category === '全部' ? major : category;
    if (idSelect !== null) {
      setClassId(Number(idSelect));
    } else {
      setClassId(idSelect);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.title}>软件列表</div>
      <TopCategory
        //@ts-ignore
        rawData={categoryData}
        onSearch={setTopSearchParams}
        onFilterChange={handleFilterChange}
      />
      <DeviceList
        data={deviceList}
        loading={loading}
        pagination={{
          current: currentPage,
          pageSize,
          total,
          onChange: handlePageChange,
        }}
        onEdit={handleEdit}
        onLocate={handleToLocate}
        onDetail={handleToDetail}
      />
      {/*// 软件分配modal*/}
      {isLocateModalOpen && (
        <LocateSoftModal
          id={locateSoftItemId}
          isOpen={isLocateModalOpen}
          onOk={handleConfirmLocate}
          onCancel={() => {
            setIsLocateModalOpen(false);
          }}
          data={locateSoftItemData}
        ></LocateSoftModal>
      )}
    </div>
  );
};

export default DeviceListExample;
