import React, { useState, useEffect } from 'react';
import { Card, Col, Row, Avatar, List, Progress, Modal, Button, message, InputNumber, Slider } from 'antd';
import { ForwardOutlined, PlayCircleOutlined, PauseCircleOutlined, DeleteOutlined } from '@ant-design/icons';
import { useLocation, useNavigate, useRouteLoaderData, useSearchParams } from 'react-router-dom';
import type { TaskListResponseWithStatics } from '@/api/types';
import { usePageSize } from '@/hooks/usePageSize';
import _ from 'lodash';
import { getFinshTrainPost, getFinshTrainPatch } from '@/api/services/task';
import queryClient from '@/api/queryClient';
import { sampleKey, taskKey } from '@/api/queryKeyFactories';
import './style.css'
let timer = null as any;


const mapData = [{ label: "学习率", id: 1 }, { label: "batch size", key: 2 }, { label: "epoch", key: 3 }, { label: "训练图片的尺寸", key: 4 }, { label: "是否数据增强", key: 5 }, { label: "损失函数", key: 6 }]

const SettingPage = () => {
  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 [inputValue, setInputValue] = useState({}) as any;
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [percent, setPercent] = useState(0) as any;


  const { state } = useLocation();

  // 开始训练
  const createTrain = () => {
    // 新增
    trainChangePost()
    initWebSocket(); // 初始化WS链接
  };


  useEffect(() => {
    console.log();

    return () => {
      clearInterval(timer);
    };
  }, []);

  useEffect(() => {
    return () => {
    };
  }, []);

  const onChange = (newValue: number, i: any) => {
    let val = JSON.parse(JSON.stringify(inputValue))
    val[i] = newValue
    setInputValue(val);
  };

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

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

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


  // 新增
  const trainChangePost = () => {
    getFinshTrainPost(
      {
        "name": "训练",
        "description": "训练内容",
        "learning_rate": "22",
        "batch_size": "1",
        "epoch": "2",
        "image_size": "3",
        "data_enhancement": true,
        "loss_function": "5",
        "status": "DRAFT",
        "task_id": state?.object?.id
      }
    ).then((item: any) => {
      console.log(item);
    });
  };


  // 更新
  const trainChangePatch = () => {
    getFinshTrainPatch(
      {
        "name": "训练",
        "description": "训练内容",
        "learning_rate": "22",
        "batch_size": "1",
        "epoch": "2",
        "image_size": "3",
        "data_enhancement": true,
        "loss_function": "5",
        "status": "FINISHED",
        "task_id": state?.object?.id
      }
    ).then((item: any) => {
      console.log(item);
    });
  };

  // 初始化WS链接
  const initWebSocket = () => {
    connection();
    // 断开重连机制,尝试发送消息,捕获异常发生时重连
    timer = setInterval(() => {
      try {
        // that.stompClient.send("test");
      } catch (err) {
        console.log("断线了: " + err);
        connection();
      }
    }, 5000);
  }
  //连接 后台
  const connection = () => {
    // 手势
    let distractions = new WebSocket("http://192.168.0.50:8888/" + "gesture/train/ws?" + "username=" + state?.object?.created_by?.username + "&taskId=" + state?.object?.id);

    distractions.onclose = () => {
      console.log('WebSocket连接关闭')
    }

    distractions.onopen = (event: any) => {
      console.log('已连接上socket')
    }

    // 手势
    distractions.onmessage = (event) => {
      setIsModalOpen(true)
      let data = parseFloat(event.data) / 1000 * 100
      let sum = data.toFixed(0) as any
      setPercent(sum)

      if (sum === 100) {
        console.log('完成');
        trainChangePatch()  // 更新
      }

    };

  }

  return (
    <>
      <div className="setting">
        <div className="numerical">
          <div>
            {mapData.map((item: any, i: any) => {
              return <Row key={i} gutter={[64, 64]} justify="space-evenly" align="top">
                <Col span={16}>
                  <b>{item.label}</b>
                  <Slider
                    min={1}
                    max={20}
                    onChange={(e) => { onChange(e, item.key) }}
                    value={inputValue[item.key] || 0}
                  />
                </Col>
                <Col span={8}>
                  <InputNumber
                    min={1}
                    max={20}
                    style={{ margin: '0 16px' }}
                    value={inputValue[item.key] || 0}
                    onChange={(e) => { onChange(e, item.key) }}
                  />
                </Col>
              </Row>
            })}
          </div>
          <Row gutter={[64, 64]} justify="end" align="top" >
            <Col span={6}>
              <Button type="primary" icon={<ForwardOutlined />} size={'large'} onClick={() => { createTrain() }}>
                开始训练
              </Button>
            </Col>
          </Row>
        </div>
        <Modal title="正在训练" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} bodyStyle={{ textAlign: 'center' }} >
          <Progress
            type="circle"
            strokeColor={{
              '0%': '#108ee9',
              '100%': '#87d068',
            }}
            percent={percent}
          />
        </Modal>
      </div >
    </>
  );
};
export default SettingPage;
