import { AlignLeftOutlined, LaptopOutlined, NotificationOutlined, PlusOutlined, UserOutlined } from '@ant-design/icons';
import { useEffect, useState } from 'react';
import { Button, Card, Col, Layout, List, Menu, Progress, Row, Typography,Image } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { useParams, useRequest } from 'umi';
import { viewMyLearningSubject, listMyLearningChapterCourse } from './service';
import type { CardListItemDataType } from './data.d';
import styles from './style.less';
import SubMenu from 'antd/lib/menu/SubMenu';
const { Paragraph } = Typography;
import cookie from 'react-cookies';
import { history } from "@@/core/history";


const CardList = () => {
  const params = useParams();
  const ids = params.msg.split(',');

  const [currentCourse, SetCurrentCourse] = useState()
  const [selectedMenu, setSelectedMenu] = useState('')

  /** 获取主题下课程 */
  const { data } = useRequest(() => {
    return viewMyLearningSubject({
      identity_id: cookie.load('identity_id'),
      person_id: cookie.load('person_id'),
      data_id: ids[0],
      data_type: ids[1],
      subject_id: ids[2]

    });
  },{
    onSuccess:(result)=>{
      result.subject.startTime= result.subject.learning_start_time.split(' ')[0];
      result.subject.endTime= result.subject.learning_end_time.split(' ')[0];
      console.log('result9999',result);
      setSelectedMenu(result.chapter_list[0].chapter_id.toString())
    }
  });

  // const list = data?.list||[];
  const subject_data = data ? data.subject : [];
  const last_data = data ? data.last_learning_course : {};
  const chapter_list = data ? data.chapter_list : [];

  // console.log('last_data', last_data)

  /** 获取课程详情 */
  const { data: chapterCourse, run, loading } = useRequest((params: { subject_id: number, chapter_id: number }) => {
    return listMyLearningChapterCourse({
      identity_id: cookie.load('identity_id'),
      person_id: cookie.load('person_id'),
      subject_id: params?.subject_id,//chapter_list[0].subject_id
      chapter_id: params?.chapter_id,//chapter_list[0].chapter_id
    });
  });

  /** 首次页面 当data 变化 执行run， chapterCourse 变化 进行currentCourse赋值 */
  useEffect(() => {
    // console.log('chapterCourse首次页面...', chapterCourse)
    if (data !== undefined && data !== null && chapter_list.length !== 0) {
      run({ subject_id: data?.chapter_list[0]?.subject_id, chapter_id: data?.chapter_list[0]?.chapter_id })
      SetCurrentCourse(chapterCourse)
    }
    //setSelectedCourse({})
  }, [data]);

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

  const content = (
    <div className={styles.pageHeaderContent}>
      {
        subject_data.length!==0?
          <Card
            title={<a>{subject_data ? subject_data.subject_name : '--'}</a>}
            hoverable={false}
            className={styles.card}
            actions={[]}
            extra={<>
            <span style={{ padding: 10 }}>学习开始时间： {subject_data ? subject_data.startTime : '--'}</span>
            <span style={{ padding: 10 }}>距离结束时间：{subject_data ? subject_data.distance_end_time : '--'}</span>
            <span style={{padding:10}}>学习结束时间：{subject_data?subject_data.endTime:'--'}</span>
            <span style={{ padding: 10 }}>考核学时：{subject_data ? subject_data.total_course_hours : '--'}学时</span>
            </>}
          >
            <Card.Meta
              avatar={<Image preview={false} width={200} height={150} src={`/dsideal_yy/html/${subject_data.attachment_json.url}`} fallback="../fallback.svg" />}
              title={false}
              description={
                <>
                <Card.Grid hoverable={false} style={{ width: '100%', padding: 0, boxShadow: 'none' }}>
                  <Paragraph className={styles.item} ellipsis={{ rows: 4 }} style={{ paddingLeft: 10 }}>
                    {subject_data ?
                      <div dangerouslySetInnerHTML={{__html:subject_data.subject_describe}}/>
                      : '--'}

                  </Paragraph>
                  {
                    JSON.stringify(last_data)!=='{}'?
                      <>
                      <Row>
                        <Col span={16} style={{ display: 'inline-block', padding: 10 }}><span>学习进度：</span><span style={{ display: 'inline-block', width: '80%' }}>
                          <Progress percent={subject_data ? parseInt(subject_data.subject_learning_progress ) : 0}
                                    format={(percent) => percent === 100 ? '100%' : `${percent}%`}
                          />
                        </span></Col>
                      </Row>
                      <Row>
                        <Col span={10} style={{ padding: 10 }}><span>上次学习：</span><span>{last_data ? last_data.course_name : '--'}</span></Col>
                        <Col span={10} style={{ padding: 10 }}>主讲人：<span>{last_data ? last_data.lecture_teacher : '--'}</span></Col>
                        <Col span={4} style={{ padding: 10 }}>
                          <Button type="primary"
                                  onClick={() => {
                                    if (last_data) {
                                      const info = last_data.chapter_id + ',' + last_data.course_id + ',' + subject_data.subject_id;
                                      window.open(location.pathname+'#/course/detail/' + info)
                                    }

                                  }}
                          >去学习</Button>
                        </Col>
                      </Row>
                      </>:<div/>
                  }
                </Card.Grid>
                </>
              }
            />
          </Card>:<div/>
      }

    </div>
  );

  const nullData: Partial<CardListItemDataType> = {};
  return (
    <PageContainer content={content} extraContent={false}>
      <Row>
        <Col span={6} style={{ paddingRight: 24 }}>
          <Menu
            mode="inline"
            selectedKeys={[selectedMenu]}
            defaultOpenKeys={['sub1']}
            style={{ height: '100%', width: '100%' }}
          >
            <SubMenu key="sub1" icon={<AlignLeftOutlined />} title="章节目录">
              {
                chapter_list.length !== 0 ?
                  chapter_list.map((item) => {
                    return (
                      <Menu.Item
                        key={item.chapter_id}
                        onClick={() => {
                          setSelectedMenu(item.chapter_id.toString())
                          run({ subject_id: item.subject_id, chapter_id: item.chapter_id })
                        }}
                      >{item.chapter_name}</Menu.Item>
                    )

                  }) : ''
              }

            </SubMenu>
          </Menu>

        </Col>
        <Col span={18} style={{ background: '#ffffff', padding: 24, minHeight: '20rem' }}>
          {
            chapterCourse !== undefined && chapterCourse !== '' ?
              chapterCourse.map((item, index) => {
                return (
                  <div key={'chapterCourse' + index} >
                    <div style={{ marginBottom: '2rem', }}>
                      <div style={{ paddingRight: '1rem', width: '10%', display: 'inline-block' }}>第{item?.sort_no}讲</div>
                      <div title={item?.course_name} style={{ paddingRight: '1rem', width: '30%', display: 'inline-block', verticalAlign: 'middle', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item?.course_name}</div>
                      <div style={{ paddingRight: '1rem', width: '10%', display: 'inline-block' }}>{item?.course_minutes}分钟</div>
                      <div style={{ paddingRight: '1rem', width: '30%', display: 'inline-block' }}>
                        <Progress percent={item?parseInt(item.learning_progress):0}
                                  format={(percent) => percent === 100 ? '100%' : `${percent}%`}
                        />
                      </div>
                      <div style={{ paddingRight: '1rem', width: '20%', display: 'inline-block', textAlign: 'right' }}>
                        <Button type="primary" onClick={() => {
                          const info = item.chapter_id + ',' + item.course_id + ',' + item.subject_id;
                          window.open(location.pathname+'#/course/detail/' + info)
                          // history.push( '/course/detail/'+info);
                        }}>学习</Button>
                      </div>
                    </div>


                  </div>
                )
              })

              : <>暂无</>
          }


          {/*  <List<Partial<CardListItemDataType>>*/}
          {/*  rowKey="id"*/}
          {/*  // loading={loading}*/}
          {/*  grid={{*/}
          {/*    gutter: 1,*/}
          {/*    xs: 1,*/}
          {/*    sm: 2,*/}
          {/*    md: 1,*/}
          {/*    lg: 1,*/}
          {/*    xl: 1,*/}
          {/*    xxl: 1,*/}
          {/*  }}*/}
          {/*  dataSource={[nullData, chapterCourse]}*/}
          {/*  renderItem={(item) => {*/}
          {/*    if (item && item.id) {*/}
          {/*      return (*/}
          {/*        <List.Item key={item.id}>*/}
          {/*          <Card*/}
          {/*            hoverable={false}*/}
          {/*            className={styles.card}*/}
          {/*            actions={[]}*/}
          {/*            style={{background:'#f0f0f0'}}*/}
          {/*          >*/}
          {/*            <Card.Meta*/}
          {/*              avatar={false}*/}
          {/*              title={<a>{item.title}</a>}*/}
          {/*              description={*/}
          {/*                <Row>*/}
          {/*                  <Col span={4} style={{padding:10}}>*/}
          {/*                    第1讲*/}
          {/*                  </Col>*/}
          {/*                  <Col span={8} style={{padding:10}}>*/}
          {/*                    <Paragraph className={styles.item} ellipsis={{ rows: 3 }}>*/}
          {/*                      {item.description}*/}
          {/*                    </Paragraph>*/}
          {/*                  </Col>*/}
          {/*                  <Col span={4} style={{padding:10, textAlign:'center'}}>*/}
          {/*                    23分钟*/}
          {/*                  </Col>*/}
          {/*                  <Col span={4} style={{padding:10, textAlign:'center'}}>*/}
          {/*                    <Progress percent={30} />*/}
          {/*                  </Col>*/}
          {/*                  <Col span={4} style={{padding:10, textAlign:'center'}}>*/}
          {/*                    <Button type="primary">学习</Button>*/}
          {/*                  </Col>*/}
          {/*                </Row>*/}
          {/*              }*/}
          {/*            />*/}
          {/*          </Card>*/}
          {/*        </List.Item>*/}
          {/*      );*/}
          {/*    }*/}
          {/*  }}*/}
          {/*/>*/}
        </Col>
      </Row>

    </PageContainer>
  );
};

export default CardList;
