import React, { useState, useRef, useEffect, useContext } from 'react';
import Service from '@/common/js/service';
import { PageControl } from '@/components';
import { Input, Select, Tooltip, Button, Table } from 'antd';
import User from '@/common/js/user';
import moment from 'moment';
import './userData.less';
const { Search } = Input;
const { Option } = Select;

interface sortType {
  type: 'ascend' | 'descend' | null | undefined;
}

function ExamData(props: any) {
  const sortStatus: sortType = {
    type: undefined,
  };

  const examDataInit: any = {};
  const queryInit: any = { current: 1, size: 10, order: 'SORT_ASC' };
  const [examData, setUserData] = useState(examDataInit);
  const [list, setList] = useState([]);
  const [query, setQuery] = useState(queryInit);
  const [total, setTotal] = useState(0);
  const [field, setfield] = useState('');
  const [allData, setAllData] = useState(0);
  const [order, setOrder] = useState(sortStatus.type);
  const questionTypeList = {
    SINGLE_CHOICE: '单选题',
    MULTI_CHOICE: '多选题',
    JUDGE: '判断题',
    GAP_FILLING: '填空题',
    INDEFINITE_CHOICE: '不定项选择题',
  };

  const userTypeEnum = {
    WORK_WE_CHAT: '企业微信',
    WE_CHAT: '微信',
  };

  const userExamStateEnum = {
    EXAM: '进行中',
    LACK_EXAM: '缺考',
    FINISH_EXAM: '已考试',
  };

  const orderEnum = {
    currentAccuracy: {
      ascend: 'ACCURACY_ASC',
      descend: 'ACCURACY_DESC',
    },
  };

  const queryRef = useRef({});

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

  useEffect(() => {
    queryRef.current = query;
    queryExamUserDataList();
  }, [query]);

  function queryExamUserData() {
    Service.Hades('public/hades/queryExamQuestionData', {
      examId: props.examId,
      tenantId: User.getStoreId(),
      userId: User.getStoreUserId(),
      source: 0,
    }).then((res) => {
      setUserData(res.result);
    });
  }

  function queryExamUserDataList() {
    Service.Hades('public/hades/queryExamQuestionDataList', {
      ...query,
      examId: props.examId,
      tenantId: User.getStoreId(),
      userId: User.getStoreUserId(),
      source: 0,
    }).then((res) => {
      setList(res.result.records);
      setTotal(parseInt(res.result.total));
      if (!allData) {
        setAllData(parseInt(res.result.total));
      }
    });
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'sort',
      width: 60,
      render: (text: any, record: any, index: any) => <span>{index + 1}</span>,
    },
    {
      title: '题目',
      dataIndex: 'questionStem',
      ellipsis: true,
      width: 350,
      render: (val: any) => {
        var handleVal = val;
        handleVal = handleVal.replace(/<(?!img|input).*?>/g, '');
        handleVal = handleVal.replace(/<\s?input[^>]*>/gi, '_、');
        handleVal = handleVal.replace(/\&nbsp\;/gi, ' ');
        return (
          <Tooltip
            overlayClassName='aid-tool-list'
            title={<div style={{ maxWidth: 700, width: 'auto' }}>{handleVal}</div>}
            placement='topLeft'
            overlayStyle={{ maxWidth: 700 }}>
            {handleVal}
          </Tooltip>
        );
      },
    },
    {
      title: '题型',
      dataIndex: 'questionType',
      render: (text: any) => <span>{(questionTypeList as any)[text]}</span>,
      filters: Object.keys(questionTypeList).map((key) => {
        return {
          text: (questionTypeList as any)[key],
          value: key,
        };
      }),
    },
    {
      title: '本次正确率',
      dataIndex: 'currentAccuracy',
      sorter: true,
      sortOrder: field === 'currentAccuracy' ? order : sortStatus.type,
      render: (text: any) => <span>{parseInt((text * 100) as any)}%</span>,
    },
    {
      title: (
        <div>
          历史正确率{' '}
          <Tooltip overlayClassName='tool-list' title='包含本次考试正确率' placement='top' overlayStyle={{ maxWidth: 700 }}>
            {' '}
            <span style={{ color: 'rgba(191, 191, 191, 1)' }} className='icon iconfont'>
              &#xe61d;
            </span>
          </Tooltip>
        </div>
      ),
      dataIndex: 'totalAccuracy',
      render: (text: any) => <span>{parseInt((text * 100) as any)}%</span>,
    },
  ];

  function onChange(pagination: any, filters: any, sorter: any, extra: any) {
    console.log(filters, sorter);

    setfield(sorter.field);
    setOrder(sorter.order);
    console.log(sorter.field, sorter.order, (orderEnum as any)[sorter.field]);
    let _query: any = { ...queryRef.current };
    console.log(filters.questionType);
    if (filters.questionType) {
      console.log(233232);
      _query.questionType = filters.questionType;
      _query.current = 1;
    } else {
      delete _query.questionType;
    }

    _query.order = (orderEnum as any)[sorter.field][sorter.order];
    setQuery(_query);
  }

  function download() {
    Service.Hades('public/hades/exportExamData', {
      // ...query,
      examId: props.examId,
      exportDataType: 'EXAM_QUESTION_DATA',
      tenantId: User.getStoreId(),
      userId: User.getStoreUserId(),
      source: 0,
    }).then((res) => {
      const dom = (document as any).getElementById('load-play-back-excel');
      dom.setAttribute('href', res.result);
      dom.click();
    });
  }

  return (
    <div className='rr'>
      <a download id='load-play-back-excel' style={{ position: 'absolute', left: '-10000px' }}></a>
      <div className='dataPanal'>
        {!!examData.singleChoiceCnt && (
          <div className='item'>
            <div className='num'>{Math.round((examData.singleChoiceAccuracy || 0) * 100)}%</div>
            <div className='percent'>正确率</div>
            <div className='subTitle'>
              <div className='type'>
                <span className='icon iconfont'>&#xe7fa;</span>单选题 <span>(共{examData.singleChoiceCnt}题)</span>
              </div>
            </div>
          </div>
        )}

        {!!examData.multiChoiceCnt && (
          <div className='item'>
            <div className='num'>{Math.round((examData.multiChoiceAccuracy || 0) * 100)}%</div>
            <div className='percent'>正确率</div>
            <div className='subTitle'>
              <div className='type'>
                <span className='icon iconfont'>&#xe7fb;</span>多选题<span>(共{examData.multiChoiceCnt}题)</span>
              </div>
            </div>
          </div>
        )}

        {!!examData.judgeCnt && (
          <div className='item'>
            <div className='num'>{Math.round((examData.judgeAccuracy || 0) * 100)}%</div>
            <div className='percent'>正确率</div>
            <div className='subTitle'>
              <div className='type'>
                <span className='icon iconfont'>&#xe7fc;</span>判断题<span>(共{examData.judgeCnt}题)</span>
              </div>
            </div>
          </div>
        )}

        {!!examData.gapFillingCnt && (
          <div className='item'>
            <div className='num'>{Math.round((examData.gapFillingAccuracy || 0) * 100)}%</div>
            <div className='percent'>正确率</div>
            <div className='subTitle'>
              <div className='type'>
                <span className='icon iconfont'>&#xe7fd;</span>填空题<span>(共{examData.gapFillingCnt}题)</span>
              </div>
            </div>
          </div>
        )}
        {!!examData.indefiniteChoiceCnt && (
          <div className='item'>
            <div className='num'>{Math.round((examData.indefiniteChoiceAccuracy || 0) * 100)}%</div>
            <div className='percent'>正确率</div>
            <div className='subTitle'>
              <div className='type'>
                <span className='icon iconfont'>&#xe7fe;</span>不定项选择题 <span>(共{examData.indefiniteChoiceCnt}题)</span>
              </div>
            </div>
          </div>
        )}
      </div>
      {!!allData && (
        <Button style={{ marginBottom: 12, marginTop: 12 }} onClick={download}>
          导出
        </Button>
      )}

      <div className='content'>
        <Table bordered size='small' columns={columns} dataSource={list} onChange={onChange} pagination={false}></Table>
        {total > 0 && (
          <PageControl
            size='small'
            current={query.current - 1}
            pageSize={query.size}
            total={total}
            toPage={(page: any) => {
              console.log(page);
              let _query: any = { ...queryRef.current };
              _query.current = page + 1;
              setQuery(_query);
            }}
          />
        )}
      </div>
    </div>
  );
}

export default ExamData;
