import React, { useRef, useState, useEffect, useCallback } from 'react';
import * as storage from '@/utils/storage';
import { Card, Col, Row, Image, Modal, Button, message, Select, Checkbox } from 'antd';
import type { CheckboxProps } from 'antd';
import { CheckCard } from '@ant-design/pro-components';
import toZip from '@/utils/jszip';
import Webcam from 'react-webcam'
import Pointer from './images/Pointer.png';
import SixUp from './images/Six-Up.png';
import SixDown from './images/Six-Down.png';
import Open from './images/Open.png';
import Close from './images/Close.png';
import OK from './images/OK.png';

import { CameraOutlined, PlayCircleOutlined, PauseCircleOutlined, DeleteOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import './style.css'
const { Meta } = Card;
let timer = null as any;
let imageList = [] as any;
let maxLength = 1000 as any;
const gestureList = [{ label: 'Open', value: 'Open', image: Open }, { label: 'Close', value: 'Close', image: Close }, { label: 'Pointer', value: 'Pointer', image: Pointer }, { label: 'OK', value: 'OK', image: OK }, { label: 'Six-Up', value: 'Six-Up', image: SixUp }, { label: 'Six-Down', value: 'Six-Down', image: SixDown },]
const videoConstraints = {
  width: 1280,
  height: 720,
  facingMode: "user"
} as any;

const { Option } = Select
const CollectionPage = () => {
  const navigate = useNavigate();
  const webcamRef = useRef(null) as any;
  const [imageSrc, setImageSrc] = useState('') as any;
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [imageListState, setImageListState] = useState([]) as any;
  const [auto, setAtuo] = useState(false) as any;
  const [imgExample, setImgExample] = useState('Open') as any;
  const [number, setNumber] = useState(1) as any;
  const [phoneListVal, setPhoneListVal] = useState([]) as any;


  const [cameras, setCameras] = useState([]);
  const [selectedCamera, setSelectedCamera] = useState(null);


  useEffect(() => {
    const getCameras = async () => {
      try {
        const devices = await navigator.mediaDevices.enumerateDevices();
        const videoDevices = devices.filter(device => device.kind === 'videoinput') as any;
        setCameras(videoDevices);

        // 自动选择第一个摄像头，如果有的话
        if (videoDevices.length > 0) {
          setSelectedCamera(videoDevices[0].deviceId);
          startCamera(videoDevices[0].deviceId);
        }
      } catch (err) {
        console.error('Error enumerating devices:', err);
      }
    };

    getCameras()
  }, []);


  // 关闭摄像头的函数
  const stopCamera = () => {
    const stream = webcamRef?.current?.stream;
    if (stream) {
      console.log(stream);

      stream.getTracks().forEach((track: any) => {
        console.log(track);
        track.stop(); // 停止视频流
      });

      webcamRef.current.srcObject = null;

    }
  };


  const startCamera = (deviceId: any) => {
    if (navigator.mediaDevices.getUserMedia) {
      navigator.mediaDevices.getUserMedia({ video: { deviceId: { exact: deviceId } } })
        .then(stream => {
          console.log(stream);
          webcamRef.current.srcObject = stream;
        })
        .catch(err => {
          console.error('Error accessing the camera:', err);
        });
    }
  };

  const handleCameraChange = (event: any) => {

    const newDeviceId = event;
    setSelectedCamera(newDeviceId);
    console.log(newDeviceId);

    startCamera(newDeviceId);
  };


  const createTask = () => {
    navigate('/tasks/0/edit?isNew=true');
  };
  useEffect(() => {
    return () => {
      // 清空图库
      clearn()
      clearInterval(timer);
      stopCamera()  // 关闭摄像头的函数
    };
  }, []);


  useEffect(() => {
    console.log(auto);
    if (!auto) {
      clearInterval(timer);
    } else {
      autoPlay()
    }
  }, [auto]);

  // 下载图片库
  const downLoad = async () => {
    let downList = []
    for (let index = 0; index < phoneListVal.length; index++) {
      const element = phoneListVal[index];
      downList.push(imageList[element])
    }

    setNumber(number + 1)
    const username = storage.get('username');
    let title = '图片库' + '_学号：' + username + "_人脸" + imgExample + '_第' + number + '次采集'
    toZip(downList, title)
    // toZip(["https://os.alipayobjects.com/rmsportal/QBnOOoLaAfKPirc.png"], '图片库')
  }


  const capture = () => {

    const imageSrc = webcamRef.current.getScreenshot();
    imageList.push(imageSrc)
    console.log(imageList);
    if (imageList.length <= 1000) {
      setImageListState(JSON.parse(JSON.stringify(imageList)))
    } else {
      // 超出上限
      clearInterval(timer);
    }
    // 这里可以将imageSrc发送到服务器或进行其他处理
    // setImageSrc(imageSrc)
    // showModal()
  };


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

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

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

  const autoPlay = () => {
    timer = setInterval((item) => {
      capture()
    }, 300)
  };

  // 清空图库
  const clearn = () => {
    message.info('清空图库')
    imageList = []
    setImageListState([])
  };

  const handleChange = (value: string) => {
    setImgExample(value)
  };

  const CheckboxChange = (value: any) => {
    let tf = value?.target.checked
    if (tf) {
      let allData = []
      for (let index = 0; index < imageListState.length; index++) {
        const element = imageListState[index];
        allData.push(index)
      }

      setPhoneListVal(allData)
    } else {
      setPhoneListVal([])
    }

  };

  return (
    <>
      <div className="collection">
        <div style={{ marginBottom: 20 }}>
          <Checkbox style={{ display: imageListState.length > 0 ? 'flex' : 'none' }} indeterminate={phoneListVal.length > 0 && phoneListVal.length < imageListState.length} checked={phoneListVal.length === imageListState.length} onChange={(e) => { CheckboxChange(e) }}>全选</Checkbox>
          <div className='phoneList'>
            <CheckCard.Group multiple={true} value={phoneListVal} style={{ width: '100%' }}
              onChange={(e) => {
                setPhoneListVal(e)
              }} >
              <Row gutter={[16, 16]} justify="start" wrap={false}>
                {imageListState.map((item: any, i: any) => {
                  return <Col span={4} key={i} ><CheckCard
                    value={i}
                    cover={
                      <img
                        alt="example"
                        width={40}
                        src={item}
                      />
                    }
                  /></Col>
                })}
              </Row>
            </CheckCard.Group>
          </div>
          {/* <div className='phoneList'>
            <Row gutter={[16, 16]} justify="start" wrap={false}>
              {imageListState.map((item: any, i: any) => {
                return <Col span={4} key={i} > <Image width={'100%'} src={item} /></Col>
              })}
            </Row>
          </div> */}
          <div className='num' style={{ display: imageListState.length > 0 ? 'block' : 'none' }}>{imageListState.length}/{maxLength}</div>
        </div>
        <Row gutter={32} justify="space-evenly">
          <Col span={16}>
            <div className='video'>
              <div>
                <Select
                  style={{ width: 120 }}
                  onChange={handleCameraChange}
                  value={selectedCamera}
                  placeholder='请选择摄像头'
                >
                  {cameras.map((camera: any) => (
                    <Option key={camera.deviceId} value={camera.deviceId}>
                      {camera.label || `Camera ${camera.deviceId}`}
                    </Option >
                  ))}
                </Select>
              </div>
              {selectedCamera && (
                <div>
                  <Webcam
                    audio={false}
                    height={'100%'}
                    ref={webcamRef}
                    screenshotFormat="image/png"
                    width={'100%'}
                    videoConstraints={{ deviceId: selectedCamera }}
                  />
                </div>
              )}

            </div>
          </Col>
          <Col span={8}>
            <div className='phone'>
              <Button type="primary" icon={<CameraOutlined />} size={'middle'} onClick={() => { capture() }}>
                手动采集
              </Button>
              <Button style={{ background: auto ? '#f50' : '#0d53de' }} type="primary" icon={auto ? <PauseCircleOutlined /> : <PlayCircleOutlined />} size={'middle'} onClick={() => { setAtuo(!auto); }}>
                自动采集
              </Button>
            </div>
            <div className='phone'>
              <Button style={{ display: phoneListVal.length > 0 ? 'block' : 'none' }} type="primary" icon={<CameraOutlined />} size={'middle'} onClick={() => { downLoad() }}>
                保存图库
              </Button>
              <Button style={{ display: imageListState.length > 0 ? 'block' : 'none' }} type="primary" icon={<DeleteOutlined />} size={'middle'} onClick={() => { clearn() }}>
                清空图库
              </Button>
            </div>
          </Col>
        </Row>
      </div >
      <Modal title="是否保存图片" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Image
          width={400}
          src={imageSrc}
        />
      </Modal>
    </>
  );
};
export default CollectionPage;
