import React, { useState, useEffect, useRef, Children } from 'react';
import { Card, Col, Row, Avatar, List, Drawer, Modal, Empty, message, Carousel } from 'antd';
import { CheckCard } from '@ant-design/pro-components';
import { Link, useNavigate, useRouteLoaderData, useSearchParams } from 'react-router-dom';
import type { TaskListResponseWithStatics } from '@/api/types';
import { usePageSize } from '@/hooks/usePageSize';
import _ from 'lodash';
import { getFinshTaskList, getFinshTrainList } from '@/api/services/task';
import * as storage from '@/utils/storage';

import './style.css'
const { Meta } = Card;

import images1 from './images/人脸.png'
import images2 from './images/手势.png'
import images3 from './images/疲劳.png'
import images4 from './images/语音.png'
import images5 from './images/分类.png'
import images6 from './images/导航.png'
import images7 from './images/学生管理.png'
import images8 from './images/标注考试.png'
import images9 from './images/训练管理.png'
import images10 from './images/成绩查询.png'

const studentData = [
  {
    id: 4,
    name: '语音识别',
    icon: images4,
    children: [
      {
        id: 1,
        path: "/classify/voice",
        name: '模型体验',
      },
      {
        id: 2,
        name: '语音采集',
        path: "/classify/voiceCollection",
      },
      {
        id: 3,
        path: "",
        name: '语音标注',
        children: [
          {
            id: 1,
            path: `/tasks/${15}/samples/128?model=voice`,
            name: '标注练习',
          },
          {
            id: 3,
            path: "/tasks/0/edit?isNew=true",
            name: '自制库训练',
          },
        ]
      },
      {
        id: 4,
        path: "",
        name: '语音训练',
        children: [
          {
            id: 1,
            path: "/classify/voicesetting",
            name: '快速训练',
          },
          {
            id: 2,
            path: "/classify/voicesetting",
            name: '模型训练',
          },
        ]
      },

    ]
  },
  {
    id: 2,
    name: '手势识别',
    icon: images2,
    children: [
      {
        id: 1,
        path: "/classify/gesturevalidation",
        name: '模型体验',
      },
      {
        id: 2,
        name: '手势采集',
        path: "/classify/gesturecollection",
      },
      {
        id: 3,
        path: "",
        name: '手势标注',
        children: [
          {
            id: 1,
            path: `/tasks/${12}/samples/${123}?type=scoring&model=gesture`,
            name: '标注练习',
          },
          {
            id: 2,
            path: `/tasks/${12}/samples/${123}?type=scoring&model=gesture`,
            name: '标注考试',
          },
          {
            id: 3,
            path: "/tasks/0/edit?isNew=true",
            name: '自制库训练',
          },
        ]
      },
      {
        id: 4,
        path: "",
        name: '手势训练',
        children: [
          {
            id: 1,
            path: "/classify/gesturesetting",
            name: '快速训练'
          },
          {
            id: 2,
            path: "/classify/gesturesetting",
            name: '模型训练',
            select: true
          },
        ]
      },

    ]
  },
  {
    id: 1,
    name: '人脸识别',
    icon: images1,
    children: [
      {
        id: 1,
        path: "/classify/facevalidation",
        name: '模型体验',
      },
      {
        id: 2,
        name: '人脸采集',
        path: "/classify/facecollection",
      },
      {
        id: 3,
        path: "",
        name: '人脸标注',
        children: [
          {
            id: 1,
            path: `/tasks/${18}/samples/${131}?type=scoring&model=face`,
            name: '标注练习',
          },
          {
            id: 2,
            path: `/tasks/${18}/samples/${131}?type=scoring&model=face`,
            name: '标注考试',
          },
          {
            id: 3,
            path: "/tasks/0/edit?isNew=true",
            name: '自制库训练',
          },
        ]
      },
      {
        id: 4,
        path: "",
        name: '人脸训练',
        children: [
          {
            id: 1,
            path: "/classify/facesetting",
            name: '快速训练',
          },
          {
            id: 2,
            path: "/classify/facesetting",
            name: '模型训练',
          },
        ]
      },

    ]
  },
]

const teacherData = [
  {
    id: 1,
    name: '学生管理',
    icon: images7,
    children: [
      {
        id: 1,
        path: "/validation",
        name: '班级管理',
      },
      {
        id: 2,
        name: '学生管理',
        path: "/collection",
      },
    ]
  },
  {
    id: 2,
    name: '标注考试',
    icon: images8,
    path: "/validation",
  },
  {
    id: 3,
    name: '训练管理',
    icon: images9,
    path: "/validation",
  },
  {
    id: 4,
    name: '成绩查询',
    icon: images10,
    path: "/validation",
  },
]
const ClassifyPage = () => {

  const carouselRef = useRef(null) as any;
  const navigate = useNavigate();
  const routerLoaderData = useRouteLoaderData('classify') as TaskListResponseWithStatics;
  const tasks = _.get(routerLoaderData, 'data');
  const meta_data = _.get(routerLoaderData, 'meta_data');
  const pageSize = usePageSize();

  const [listData, setListData] = useState([]) as any;
  const [listChildData, setListChildData] = useState([]) as any;
  const [dataImg, setDataImg] = useState(null) as any;
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [taskListData, setTaskListData] = useState([]);
  const [trainListData, setTrainListData] = useState([]);

  const [pathUrl, setPathUrl] = useState('');
  const [pathObject, setPathObject] = useState({});
  const [currentSlide, setCurrentSlide] = useState(0);
  const [cardData, setCardData] = useState([]) as any;

  const role = storage.get('role');
  const username = storage.get('username');

  useEffect(() => {
    queryTaskListData() // 获取已完成标注列表(手势训练)
    queryTrainListData() // 获取训练列表(模型验证)
    judgingRoles(role) // 判断角色

    return () => { };

  }, []);

  // 判断角色

  const judgingRoles = (role: any) => {
    switch (role) {
      case 'student':
        setCardData(studentData)
        break;
      case 'teacher':
        setCardData(teacherData)
        break;
      default:
        setCardData(studentData)
        break;
    }
  }

  // 获取已完成标注列表(手势训练)
  const queryTaskListData = () => {
    getFinshTaskList({}).then((item: any) => {
      console.log(item);
      setTaskListData(item?.data)
    });
  }

  // 获取训练列表 获取训练列表(模型验证)
  const queryTrainListData = () => {
    getFinshTrainList({}).then((item: any) => {
      console.log(item);
      setTrainListData(item?.data)
    });
  }
  const goToPath = () => {

    if (pathUrl && pathObject && JSON.stringify(pathObject) !== '{}') {
      navigate(pathUrl, { state: { object: pathObject } });
    } else {
      message.info('请先选择一条数据');
    }
  };

  const showDrawer = (item: any) => {
    carouselRef.current.next()
    setListData(item?.children || [])
    setDataImg(item?.icon)
  };

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
    goToPath()
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const onAfterChange = (currentSlide: number) => {
    setCurrentSlide(currentSlide)
  };

  return (
    <>
      <div className="classify">
        <div className='carousel'>
          <div className='back' style={{ display: currentSlide > 0 ? 'block' : 'none' }} onClick={() => { carouselRef.current.prev(); }}></div>
          <Carousel afterChange={onAfterChange} arrows={false} autoplay={false} dots={false} ref={carouselRef}  >
            <div>
              <Row gutter={[64, 64]} justify="space-evenly">
                {cardData.map((item: any) => {
                  return <Col span={10} key={`a-${item.id}`}>
                    <Card
                      onClick={() => {
                        if (item.children) {
                          showDrawer(item)
                        } else {
                          navigate(item.path);
                        }
                      }}
                      className="classifyCard"
                    >
                      <Meta
                        avatar={<Avatar src={item.icon} />}
                        title={item.name}
                        description={item.name}
                      />
                    </Card>
                  </Col>
                })}
              </Row>
            </div>
            <div>
              <Row gutter={[64, 64]} justify="space-evenly">
                {listData.map((item: any) => {
                  return <Col span={10} key={`a-${item.id}`}>
                    <Card
                      onClick={() => {
                        if (item.children) {
                          setListChildData(item.children);
                          carouselRef.current.next();
                        } else {
                          if (item.select) {
                            setPathUrl(item.path);
                            showModal();
                          } else {
                            navigate(item.path);
                          }
                        }
                      }}
                      className="classifyCard"
                    >
                      <Meta
                        avatar={<Avatar src={images5} />}
                        title={item.name}
                        description={item.name}
                      />
                    </Card>
                  </Col>
                })}
              </Row>
            </div>
            <div>
              <Row gutter={[64, 64]} justify="space-evenly">
                {listChildData.map((item: any) => {
                  return <Col span={10} key={`a-${item.id}`}>
                    <Card
                      onClick={() => {
                        if (item.select) {
                          setPathUrl(item.path);
                          showModal();
                        } else {
                          navigate(item.path);
                        }
                      }}
                      className="classifyCard"
                    >
                      <Meta
                        avatar={<Avatar src={images6} />}
                        title={item.name}
                        description={item.name}
                      />
                    </Card>
                  </Col>
                })}
              </Row>
            </div>
          </Carousel>
        </div>
      </div>
      {/* <Modal title="请选择" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} zIndex={999999}>
        <CheckCard.Group
          onChange={(item: any) => {
            setPathObject(item)
          }}
        >
          {taskListData && taskListData?.length > 0 ? (
            taskListData.map((item: any, i) => {
              return <CheckCard key={i} avatar={dataImg} title={item?.name} description={item?.created_by?.username} extra={item?.created_at} value={item} />
            })
          ) : (
            <Empty />
          )}
        </CheckCard.Group>
      </Modal> */}
      <Modal title="请选择" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} zIndex={999999}>
        <CheckCard.Group
          onChange={(item: any) => {
            setPathObject(item)
          }}
        >
          <div style={{ display: pathUrl === '/validation' ? 'block' : 'none' }}>
            {trainListData && trainListData?.length > 0 ? (
              trainListData.map((item: any, i) => {
                return <CheckCard key={i} avatar={dataImg} title={item?.name} description={item?.created_by?.username} extra={item?.created_at} value={item} />
              })
            ) : (
              <Empty />
            )}
          </div>
          <div style={{ display: pathUrl === '/setting' ? 'block' : 'none' }}>
            {taskListData && taskListData?.length > 0 ? (
              taskListData.map((item: any, i) => {
                return <CheckCard key={i} avatar={dataImg} title={item?.name} description={item?.created_by?.username} extra={item?.created_at} value={item} />
              })
            ) : (
              <Empty />
            )}
          </div>
        </CheckCard.Group>
      </Modal>
    </>
  );
};
export default ClassifyPage;
