import type { FC } from 'react';
import { useEffect,useState } from 'react';
import {message, Avatar, Card, Col, List, Skeleton, Row, Statistic, Descriptions, Progress, Table, Button, Image } from 'antd';
import { Line, Radar } from '@ant-design/charts';
import { Link, history, useRequest } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import moment from 'moment';
import EditableLinkGroup from './components/EditableLinkGroup';
import styles from './style.less';
import ProTable from '@ant-design/pro-table';
import {getPersonPaperId,getExaminationById, personLastLearning, personLearningDayStatistics, getPersonExaminationList, getExaminationList,getPersonAnswerTime } from './service';
import cookie from 'react-cookies';
import OfflineData from './components/OfflineData';


const examinations = [
  {
    key: '1',
    name: '生涯规划师初级认证培训1',
    appyTime: '2021/12/25-2021/12/26',
    examTime: '2021/12/27',
    status: 0
  },
  {
    key: '2',
    name: '生涯规划师初级认证培训2',
    appyTime: '2021/12/25-2021/12/26',
    examTime: '2021/12/27',
    status: -1
  },
  {
    key: '3',
    name: '生涯规划师初级认证培训3',
    appyTime: '2021/12/25-2021/12/26',
    examTime: '2021/12/27',
    status: 0
  },
  {
    key: '4',
    name: '生涯规划师初级认证培训4',
    appyTime: '2021/12/25-2021/12/26',
    examTime: '2021/12/27',
    status: 0
  },
  {
    key: '5',
    name: '生涯规划师初级认证培训5',
    appyTime: '2021/12/25-2021/12/26',
    examTime: '2021/12/27',
    status: 0
  },
];


/** 证书字段 */
const certificateColumns = [
  {
    title: '考试名称',
    dataIndex: 'examination_name',
    key: 'name',
  },
  {
    title: '考试时间',
    dataIndex: 'examTime',
    key: 'examTime',
    render: (dom, entity) => {
      return <div>开始时间：{entity.examination_start_time}<br />结束时间：{entity.examination_end_time}</div>

    },
  },
  {
    title: '通过情况',
    dataIndex: 'is_pass',
    key: 'statusExam',
    render: (dom, entity) => {
      return entity.is_pass = 1 ? "通过" : "未通过"
    }
  },
  {
    title: '证书情况',
    dataIndex: 'accreditation_status',
    key: 'statusCertificate',
    render: (dom, entity) => {
      return entity.is_pass = 1 ? "已制证" : "未制证"
    }
  },
];

const certificates = [
  {
    key: '1',
    name: '生涯规划师初级认证',
    examTime: '2021/12/27',
    statusExam: 'ok',
    statusCertificate: 'yes'
  },
  {
    key: '2',
    name: '生涯规划师初级认证2',
    examTime: '2021/12/27',
    statusExam: 'ok',
    statusCertificate: 'yes'
  },
  {
    key: '3',
    name: '生涯规划师初级认证3',
    examTime: '2021/12/27',
    statusExam: 'ok',
    statusCertificate: 'yes'
  },
  {
    key: '4',
    name: '生涯规划师初级认证4',
    examTime: '2021/12/27',
    statusExam: 'ok',
    statusCertificate: 'yes'
  },
  {
    key: '5',
    name: '生涯规划师初级认证5',
    examTime: '2021/12/27',
    statusExam: 'ok',
    statusCertificate: 'yes'
  },
];

const Workplace: FC = () => {
  const [examInfo, setExamInfo] = useState({});
  /** 考试字段 */
  const examinationColumns = [
    {
      title: '考试名称',
      dataIndex: 'examination_name',
      key: 'name',
    },
    {
      title: '报名时间',
      dataIndex: 'appyTime',
      key: 'appyTime',
      render: (dom, entity) => {
        return <div>开始时间：{entity.apply_start_time}<br />结束时间：{entity.apply_end_time}</div>

      },
    },
    {
      title: '考试时间',
      dataIndex: 'examTime',
      key: 'examTime',
      render: (dom, entity) => {
        return <div>开始时间：{entity.examination_start_time}<br />结束时间：{entity.examination_end_time}</div>
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      key: 'option',
      render: (_, record, index, action) => {
        console.log('record',record)
        // return record?.status === 0 ? <Button type="primary" onClick={() => { history.push('/registration' + record.examination_id) }}>去报名</Button> : <Button type="primary" onClick={() => { history.push('/examination/paper') }}> 参加考试</Button >
        switch (record.status_type) {
          case 0://待报名
            return <Button disabled>去报名</Button>
            break;
          case 1://报名中
            return <Button type={"primary"} disabled={record.is_apply} onClick={() => { history.push('/registration/' + record.examination_id) }}>去报名</Button>//判断
            break;
          case 2://待考试
            return <Button disabled>去考试</Button>
            break;
          case 3://考试中
            return <Button disabled={!record.is_apply}
                           type={"primary"}
                           onClick={async() => {
                             console.log(111111)
                             try {
                               const info=await getPersonAnswerTime({
                                 examination_id:record.examination_id,
                                 person_id:cookie.load('person_id')
                               });
                               setExamInfo(info.bean)
                               if(info.bean===''){
                                 history.push('/dashboard/qualification/' + record.examination_id)
                               }else {

                                 if(!info.bean.is_finish){
                                   const time1 = info.bean.curr_time.replace(/\-/g, "/");
                                   const time2 = info.bean.failure_time.replace(/\-/g, "/");
                                   const startTime=new Date(time1).getTime()
                                   const endTime=new Date(time2).getTime()
                                   const time_diff=(endTime-startTime)/1000;
                                   console.log('time_diff',time_diff)

                                   getExamInfo(record.examination_id,time_diff)
                                 }else {
                                   getParperId(record.examination_id)
                                 }

                                 // history.push(`/dashboard/qualification/examAnswer/${record.examination_id}/${examinationInfo.rules_id}/${examinationInfo.examination_name}/${time}`)
                               }
                               console.log('info',info)
                             }catch (error) {
                               if(error.response){
                                 message.error(error.response.info);
                                 }else {
                               }
                             }


                           }}>
              去考试</Button>
            break;
          case 4:
            return "考试完成"
            break;
          default:
            break;
        }

      },
    },
  ];
  const getExamInfo=async (id,time)=>{
    try {
      const info=await getExaminationById({examination_id:id});
      console.log('info--------------------',info)
      console.log('time',time)

      history.push(`/dashboard/qualification/examAnswer/${id}/${info.bean.rules_id}/${info.bean.examination_name}/${time}`)

    }catch (error) {
      if(error.response){
        message.error(error.response.info);
      }
    }
  }
  const getParperId=async (id)=>{
    try {
      const info=await getPersonPaperId({
        examination_id:id,
        person_id:cookie.load('person_id')
      });
      console.log('info--------------------',info)
      if(info.paper_id===''){
        message.warning('考试失败！')
      }else {
        history.push('/dashboard/qualification/' + id)
      }

    }catch (error) {
      if(error.response){
        message.error(error.response.info);
      }
    }
  }

  // 当前学习
  const { loading: lastLearningLoading, data: lastLearningList = [] } = useRequest(
    () => personLastLearning(
      {
        identity_id: cookie.load('identity_id'),
        person_id: cookie.load('person_id')
      }));

  // 资质考试列表
  const { loading: lastexaminationLoading, data: examinationList } = useRequest(
    () => getExaminationList(
      {
        person_id: cookie.load('person_id'),
        b_use: 1,
        page_size: 999
      }), {
    formatResult: (result) => {
      return result.table_List;
    }
  });

  // 学习概况
  const { loading: activitiesLoading, data: learningDayStatistics = [] } = useRequest(
    () => personLearningDayStatistics(
      {
        identity_id: cookie.load('identity_id'),
        person_id: cookie.load('person_id')
      }));


  // 证书查询
  const { loading: personExaminationLoading, data: personExaminationList = [] } = useRequest(
    () => getPersonExaminationList(
      {
        identity_id: cookie.load('identity_id'),
        person_id: cookie.load('person_id'),
      }), {
    formatResult: (result) => {
      return result.table_List;
    }
  });




  useEffect(() => {
    console.log('lastLearningList', personExaminationList)

  })
  return (
    <>
      <Row gutter={24}>
        <Col xl={10} lg={10} md={10} sm={10} xs={10}>
          <Card
            className={styles.projectList}
            style={{ marginBottom: 24 }}
            title="学习概况"
            bordered={false}
            extra={false}
            loading={activitiesLoading}
            bodyStyle={{ padding: 24 }}
          >
            <div className={styles.extraContent}>
              <div className={styles.statItem}>
                <Statistic title="今日学习" value={learningDayStatistics?.today?.learning_minutes} suffix=" 分钟" />
              </div>

            </div>
            <div style={{ width: '100%', padding: 24 }}>
              <Line
                color={'#1859ff'}
                forceFit
                height={400}
                data={learningDayStatistics?.statistics_list}
                //responsive
                xField="learning_date"
                yField="learning_minutes"
                //seriesField="type"
                legend={{
                  position: 'top-center',
                }}
                point={{ size: 5 }}
                tooltip={{
                  customContent: (title: any, items: any): any => {
                    console.log('title', title);
                    console.log('items', items);
                    return (
                      <div style={{ padding: '12px 14px', fontSize: '12px', width: '180px', height: '68px', lineHeight: '20px' }}>
                        <div>{title}</div>
                        <div>学习时长：{items[0] ? items[0].data.learning_minutes : ''}</div>

                      </div>

                    )
                  }
                }}
              />
            </div>
          </Card>
          {
            JSON.stringify(lastLearningList) !== '{}' ?
              <Card
                bodyStyle={{ padding: 15 }}
                bordered={false}
                className={styles.studyCard}
                title="当前学习"
                loading={activitiesLoading}
                // cover={<img alt="example" src={lastLearningList?.course_attachment_json?.img} />}
                cover={<Image preview={false} width={200} height={150} src={`/dsideal_yy/html/${lastLearningList?.subject_attachment_json?.url}`} fallback="../fallback.svg" />}
              >
                <Descriptions title={lastLearningList?.course_name} layout='horizontal' column={1} >
                  <Descriptions.Item label="主讲人">{lastLearningList?.lecture_teacher}</Descriptions.Item>
                  <Descriptions.Item label="章节">{lastLearningList?.chapter_name}</Descriptions.Item>
                  <Descriptions.Item label="主题">{lastLearningList?.subject_name}</Descriptions.Item>
                  <Descriptions.Item label="时长">{lastLearningList?.total_course_minutes}分钟</Descriptions.Item>
                </Descriptions>
                <Progress percent={lastLearningList?.learning_progress} />
              </Card>
              : <Card
                bodyStyle={{ padding: 15 }}
                bordered={false}
                className={styles.studyCard}
                title="当前学习"
              ><div style={{ minHeight: '5rem', textAlign: 'right', paddingTop: '1rem', fontSize: '15px' }}>暂无数据</div></Card>
          }
        </Col>
        <Col xl={14} lg={14} md={14} sm={14} xs={14}>
          <Card
            style={{ marginBottom: 24 }}
            title="资质考试"
            bordered={false}
            bodyStyle={{ padding: 0 }}
          >
            <div className={styles.chart} style={{ height: 300, overflowY: "scroll" }}><Table dataSource={examinationList} columns={examinationColumns} pagination={false} /></div>

          </Card>
          <Card
            style={{ marginBottom: 24 }}
            bordered={false}
            title="证书查询"
          // loading={data?.radarData?.length === 0}
          >
            <div className={styles.chart}>
              <ProTable
                style={{ marginBottom: 24 }}
                pagination={true}
                search={false}
                // loading={loading}
                options={false}
                toolBarRender={false}
                request={async (value) => {
                  const { create_time } = value;
                  if (create_time) {
                    value.start_time = create_time[0]
                    value.end_time = create_time[1]
                  }
                  console.log('form _data', value)
                  delete value.create_time
                  const _data = await getPersonExaminationList(
                    {
                      ...value,
                      identity_id: cookie.load('identity_id'),
                      person_id: cookie.load('person_id'),
                    });
                  return {
                    current: _data?.pageNumber,
                    data: _data?.table_List,
                    pageSize: _data?.pageSize,
                    total: _data?.totalRow || 0,
                  };
                }}
                columns={certificateColumns}
                rowKey="id"
              />
              {/* <Table dataSource={personExaminationList} columns={certificateColumns} pagination={true} /> */}
            </div>
          </Card>
        </Col>
      </Row>
    </>
  );
};

export default Workplace;
