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, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { useParams, useRequest, history } from 'umi';
import { viewMyLearningSubject, getCourseExaminationProgressList, getErrorQuestionList } 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";

// let chapterCourse = [];
const total_process = 0;
const CardList = () => {
  const params = useParams();
  const [selectedMenu, setSelectedMenu] = useState('')
  const [currentCourse, SetCurrentCourse] = useState()


  const [courseQuestionProcess, setCourseQuestionProcess] = useState(0)
  const [chapterCourse, setChapterCourse] = useState([])
  /** 获取主题下课程 */
  const { data } = useRequest(() => {
    return viewMyLearningSubject({
      identity_id: cookie.load('identity_id'),
      person_id: cookie.load('person_id'),
      data_id: params?.data_id,
      data_type: params?.data_type,
      subject_id: params?.subject_id

    });
  }, {
    onSuccess: (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 : [];


  /** 获取课程详情 */
  const { chapterCourseData, run, loading } = useRequest((params: { subject_id: number, chapter_id: number }) => {
    return getCourseExaminationProgressList({
      identity_id: cookie.load('identity_id'),
      person_id: cookie.load('person_id'),
      subject_id: params?.subject_id,
      chapter_id: params?.chapter_id,

      // r_list[0].chapter_id
    });
  }, {
    manual: true,
    formatResult: (result) => {

      if (result.list.length !== 0) {
        let total_finish_count = 0;
        let total_question_count = 0;

        result.list.forEach((item) => {
          total_finish_count += item.finish_count;
          total_question_count += item.question_count;
          if (item.finish_count !== 0) {
            let num = 0;
            num = item.finish_count / item.question_count;
            item.process = parseFloat(num).toFixed(2)
          } else {
            item.process = 0;
          }
        });

        let total_process = 0

        if (total_finish_count !== 0) {
          const total_num = total_finish_count / total_question_count;
          total_process = parseFloat(total_num).toFixed(2)
          setCourseQuestionProcess(total_process)
        } else {
          total_process = 0;
          setCourseQuestionProcess(0)
        }
      } else {
        setCourseQuestionProcess(0)
      }

      setChapterCourse(result.list)
      // chapterCourse = result.list;

    }
  });

  /** 首次页面 当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={[]}
          >
            <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>

                  </Card.Grid>
                  <Card.Grid hoverable={false} style={{ width: '25%', textAlign: 'center', boxShadow: 'none' }}>
                    <Button type="primary"
                      style={{ width: '10rem', height: '5rem' }}
                      onClick={async () => {
                        const info = subject_data.subject_id + "," + cookie.load('person_id')


                        const _data1 = await getErrorQuestionList({
                          subject_id: params.subject_id,
                          person_id: cookie.load('person_id'),
                        });
                        let num = 0
                        if (_data1.success) {
                          _data1.list.map((e, i) => {
                            num += e.question_list.length
                          })

                        }
                        if (num > 0) {
                          history.push(`/mockExamination/chapterExamination/chapterList/chapterErrorListPaper/${info}`)
                        } else {
                          message.error("暂无错题");
                        }

                      }}
                    >错题练习</Button>
                  </Card.Grid>
                  <Card.Grid hoverable={false} style={{ width: '50%', textAlign: 'center', boxShadow: 'none' }}>
                    <span style={{ display: 'inline-block', width: '100%' }}>
                      <Progress width={50}
                        type="circle"
                        percent={parseInt(courseQuestionProcess * 100)}
                        format={(percent) => percent === 100 ? '100%' : `${percent}%`}
                      />
                    </span>
                    <span>章节模拟考试进度</span>
                  </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' }}>
          {console.log(chapterCourse, 'chapterCourse')}
          {
            chapterCourse.length > 0 ?
              chapterCourse?.map((item, index) => {
                return (
                  <div key={'chapterCourse' + index} >
                    <div style={{ marginBottom: '2rem', }}>
                      <div style={{ paddingRight: '1rem', width: '10%', display: 'inline-block' }}>第{index + 1}讲</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?.finish_count}题/{item?.question_count}题</div>
                      <div style={{ paddingRight: '1rem', width: '30%', display: 'inline-block' }}>
                        <Progress percent={item ? parseInt(item.process * 100) : 0} format={(percent) => percent === 100 ? '100%' : `${percent}%`} />
                      </div>
                      <div style={{ paddingRight: '1rem', width: '20%', display: 'inline-block', textAlign: 'right' }}>
                        <Button
                          type="primary"
                          disabled={item.question_count > 0 ? false : true}
                          onClick={() => {
                            const info = cookie.load('identity_id') + ',' + item.chapter_id + ',' + item.course_id + ',' + item.finish_count + ',' + cookie.load('person_id') + ',' + item.subject_id;

                            history.push(`/mockExamination/chapterExamination/chapterList/chapterListPaper/${info}`)

                          }}>开始考试</Button>
                      </div>
                    </div>


                  </div>
                )
              })

              : <div>暂无试题</div>
          }
        </Col>
      </Row>

    </PageContainer >
  );
};

export default CardList;
