import { AlignLeftOutlined, LaptopOutlined, NotificationOutlined, PlusOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Card, Col, Layout, List, Menu, Progress, Row, Typography } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import {useParams, useRequest} from 'umi';
import {useEffect, useState} from 'react';
import { queryFakeList } from './service';
import type { CardListItemDataType } from './data';
import styles from './style.less';
import { Content } from 'antd/lib/layout/layout';
import Sider from 'antd/lib/layout/Sider';
import SubMenu from 'antd/lib/menu/SubMenu';

import React,{ useRef } from 'react';
import {listMyLearningChapterCourse1, viewCourseGetMyLearning,saveMyLearning} from  './service';
import cookie from 'react-cookies';
import { VideoJS } from '../components/VideoJS';
const { Paragraph } = Typography;
let num=0;
const CardList = () => {

  const params = useParams();
  const ids = params.msg.split(',');//chapter_id,course_id,subject_id
  const [currentLearning, SetCurrentLearning] = useState();
  const [courseId, SetCourseId] = useState(ids[1]);
  const [video, setVideo] = useState({});
  const [nums,setNums]=useState(0);
  let timer=useRef();
  let video_second=0;
  // const videoRef = useRef<HTMLVideoElement>(null);
  const playerRef = React.useRef<any>(null); // 播放器引用
  console.log('courseIdcourseIdcourseIdcourseId',courseId)
  /** 获取课节 */
  const { data } = useRequest(() => {
    return listMyLearningChapterCourse1({
      chapter_id: ids[0],
      identity_id:cookie.load('identity_id'),
      person_id:cookie.load('person_id'),
      subject_id: ids[2],
    });
  });

  /** 获取视频 */
  const {data: learning, run, loading } = useRequest((params:{course_id:number}) => {
    // SetCourseId(ids[1]);
    return viewCourseGetMyLearning({
      identity_id:cookie.load('identity_id'),
      person_id:cookie.load('person_id'),
      subject_id: ids[2],//chapter_list[0].subject_id
      chapter_id: ids[0],//chapter_list[0].chapter_id
      course_id:params?.course_id,
    });
  },{
    onSuccess:(result)=>{
      console.log('result9999',result);
      let info={img:'',url:''};
      if(JSON.stringify(result.course.attachment_json.url)!=='{}'){
        info.url= '/dsideal_yy/html/'+result.course.attachment_json.url;
        info.img=result.course.attachment_json.img;
      }
      setVideo(info);

    }
  });

  console.log('video',video)
  //保存进度
  // const saveProcess = async((params:{time:number,num:number}) => {
  //   console.log('num保存是',num)
  //   // return saveMyLearning({
  //   //   chapter_id:learning?.learning.chapter_id,//章节id
    //   //   course_id:courseId?courseId:ids[1],//课程id
    //   //   identity_id:cookie.load('identity_id'),
    //   //   learning_id:learning?.learning.learning_id,//学习记录id
    //   //   learning_second:num,//距离上次提交持续学习秒数(非必填)
    //   //   person_id:cookie.load('person_id'),
    //   //   play_second:params?.time,//当前播放时间点（秒数)
    //   //   subject_id:learning?.learning.subject_id,//主题id
    //   //   video_second:video_second,//视频总长度
    //   // });
    // });


    const saveProcess = async (info)=>{
      console.log('num保存是',info)
      await saveMyLearning({
         chapter_id:learning?.learning.chapter_id,//章节id
          course_id:courseId?courseId:ids[1],//课程id
          identity_id:cookie.load('identity_id'),
          learning_id:learning?.learning.learning_id,//学习记录id
          learning_second:info.num,//距离上次提交持续学习秒数(非必填)
          person_id:cookie.load('person_id'),
          play_second:info.time,//当前播放时间点（秒数)
          subject_id:learning?.learning.subject_id,//主题id
          video_second:video_second,//视频总长度
      })
  }

  /** 首次页面 当data 变化 执行run， chapterCourse 变化 进行currentCourse赋值 */
  useEffect(() => {
    if(data !== undefined && data !== null){
      run({course_id:ids[1]});
      SetCurrentLearning(learning)
    }
    //setSelectedCourse({})
  },[data]);

  /** run后 chapterCourse 变化 进行currentCourse赋值 */
  useEffect(() => {
    if(data !== undefined){
      SetCurrentLearning(learning)
    }
    //setSelectedCourse({})
  },[learning]);


  //
  const content = (
    <div className={styles.pageHeaderContent}>
      <Card
        title={<a>{'生涯规划师初级认证培训课程你收到了 14 份新周报'}</a>}
        hoverable={false}
        className={styles.card}
        actions={[]}
        extra={<><span style={{padding:10}}>开始学习时间: 2020-4-9</span><span style={{padding:10}}>距离结束时间：300天</span><span style={{padding:10}}>考核学时：36学时</span></>}
      >
        <Card.Meta
          avatar={<img alt="" className={styles.cardAvatar} src={'https://gw.alipayobjects.com/zos/rmsportal/uMfMFlvUuceEyPpotzlq.png'} style={{width:'270px', height:'150px', borderRadius:'10px'}} />}
          title={false}
          description={
            <>
              <Card.Grid hoverable={false} style={{width:'100%',padding:0, boxShadow:'none'}}>
                <Paragraph className={styles.item} ellipsis={{ rows: 4 }} style={{paddingLeft:10}}>
                  {'请大家在规定时间内完成本培训任务安排，逾期本培训任务将自动关闭。祝大家学习愉快！请大家在规定时间内完成本培训任务安排，逾期本培训任务将自动关闭。祝大家学习愉快！这种模板用于提醒谁与你发生了互动，左侧放『谁』的头像'}
                </Paragraph>
                <Row>
                  <Col span={16} style={{display:'inline-block', padding:10}}><span>学习进度：</span><span style={{display:'inline-block', width:'80%'}}><Progress percent={75} /></span></Col>
                </Row>
                <Row>
                  <Col span={10} style={{padding:10}}><span>上次学习：</span><span>生涯规划之升学路径知多少</span></Col> <Col span={10} style={{padding:10}}>主讲人：<span>盖笑松</span></Col> <Col span={4} style={{padding:10}}><Button type="primary">去学习</Button></Col>
                </Row>
              </Card.Grid>
            </>
          }
        />
      </Card>
    </div>
  );
  //const videoInfo = {url:'http://cctvalih5ca.v.myalicdn.com/live/cctv1_2/index.m3u8', img:''}
  //const videoInfo = {url:'https://media.w3.org/2010/05/sintel/trailer_hd.mp4', img:''}
  const videoInfo = {url:'http://10.10.14.199/dsideal_yy/html/down/M3u8/2D/2D99BF1D-2F37-47FB-8A24-45112A236B8F.m3u8', img:''}//有视频
    // const videoInfo=learning?.course.attachment_json;isg
  const nullData: Partial<CardListItemDataType> = {};


  // const saveLearning=useEffect(() => {
  //   console.log('保存进队');
  //     saveProgress({time:time})
  // },[time]);
  return (
    <PageContainer
      // content={content}
      extraContent={false}>
      <Row>
        <Col span={6} style={{paddingRight:24}}>
          <Menu
            mode="inline"
            // selectedKeys={[ids[1].toString()]}
            selectedKeys={[courseId.toString()]}
            defaultOpenKeys={['sub1']}
            style={{ height: '100%', width:'100%' }}
          >
            <SubMenu key="sub1" icon={<AlignLeftOutlined />} title="课节目录">
              {
                data!==undefined?
                  data.map((item)=>{
                    return(
                      <Menu.Item key={item.course_id} onClick={()=>{
                        SetCourseId(item.course_id);
                        run({course_id:item.course_id})
                      }}>{item.course_name}</Menu.Item>
                    )
                  }):''

              }

            </SubMenu>
          </Menu>
        </Col>
        <Col span={18} style={{background:'#ffffff', padding:24}}>
          {
            video?.url&&(
            <VideoJS
            style={{width:640,height:480}}
            width='100%'
            height='480px'
            options={{
            controls: true,
            playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
            autoplay: false, // 如果true,浏览器准备好时开始回放。
            muted: false, // 默认情况下将会消除任何音频。
            loop: false, // 导致视频一结束就重新开始。
            preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
            language: 'zh-CN',
            aspectRatio: '4:3', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
            fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
            sources: [
              {
                src:  JSON.stringify(video)!=='{}'?video.url:'',  // 测试地址后续请删除
                // src: '/dsideal_yy/html/down/Syzx/6e/6e4e88a3-0c71-4298-ba5b-ac1c3f52d587.mp4' ,  // 测试地址后续请删除
                //type: 'application/x-mpegURL'
              }
            ],
            poster: JSON.stringify(video)!=='{}'?video.img:'', // 你的封面地址
            width: document.documentElement.clientWidth,
            notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
            controlBar: {
              timeDivider: true,
              durationDisplay: true,
              remainingTimeDisplay: true,
              fullscreenToggle: true // 全屏按钮
            }
          }}
            onReady={(play: any) => {
            //console.log('play====', play);
            playerRef.current = play
            // play.play();
            play.on('play',function (event) {
              console.log('播放-------------------------------')
              num=0;
              timer.current=setInterval(()=>{;
                // console.log('timer-----------',timer)
                num++
              },1000)
            })
            play.on("timeupdate", function (event) {
              //const _timeCurrent = Date.parse(new Date().toString()) / 1000; // 当前时间
              //setTimeUpdateState(_timeCurrent); //timeUpdateState
              if(play.currentTime()===this.duration()){
                console.log('播放完了',num)
                clearInterval(timer.current)
                saveProcess({time:play.currentTime(),num:num})

              }
              // console.log('playcurrentTime--', play.currentTime())
              // console.log('play-%-', parseInt(play.currentTime()) % 30)
              if (parseInt(play.currentTime())>0&&parseInt(play.currentTime()) % 30 === 0) { // 每15秒更新进度
                console.log(1)
                saveProcess({time:play.currentTime(),num:30})
              }
              //var currentTime = parseInt(this.currentTime()); //当前时间
              video_second = this.duration(); //视频时常
              // console.log('duration',duration)
              //var percent = (currentTime / duration * 100).toFixed(0) + "%";
              //console.log('event',event);
              //$("#current").text(this.currentTime());
              //$("#duration").text(duration);
            })
          }}
            />
            )

          }

        </Col>
      </Row>

      {/*<a onClick={()=>{*/}
        {/*const data = videoRef?.current?.currentTime();*/}
        {/*console.log('getData', data)*/}
        {/*}}>videoRef get</a>*/}

      {/*<a onClick={()=>{*/}
        {/*const data = videoRef?.current?.currentTime(300);*/}
        {/*console.log('setData', data)*/}
        {/*}}>videoRef set</a>*/}


    </PageContainer>
  );
};

export default CardList;
