import React, { useState, useRef, useEffect, useContext } from 'react';
import { Input, Select, DatePicker, Tooltip, Button, Table, Dropdown, Menu, Modal } from 'antd';
import Lottie from 'react-lottie';
import TeacherSelect from '@/modules/common/TeacherSelect';
import { Route, withRouter } from 'react-router-dom';
import Service from '@/common/js/service';
import moment from 'moment';
import { PageControl, XMTable } from '@/components';
import AddExam from './AddExam';
import User from '@/common/js/user';
import { XMContext } from '@/store/context';
import ExamShareModal from './ExamShareModal';
import DataAnalysic from './DataAnalysic';
import PreviewModal from './PreviewModal';
import * as nodata from '../../lottie/nodata/data.json';
import './index.less';
const { RangePicker } = DatePicker;
const { Search } = Input;
const { Option } = Select;

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

interface fixType {
  left: boolean | 'right' | 'left' | undefined;
  right: 'right' | 'left';
}

const fixStr: fixType = {
  left: 'left',
  right: 'right',
};

function ExaminationManager(props: any) {
  const queryInit: any = {
    examName: '',
    current: 1,
    size: 10,
    order: 'EXAM_START_TIME_DESC',
  };

  const sortStatus: sortType = {
    type: undefined,
  };

  const sortEnum = {};
  const { match } = props;
  const sortState: any = false;
  const ctx: any = useContext(XMContext);
  const [query, setQuery] = useState(queryInit);
  const [expandFilter, setExpandFilter] = useState(false);
  const [total, setTotal] = useState(0);
  const [list, setList] = useState([]);
  const [field, setfield] = useState('');
  const [order, setOrder] = useState(sortStatus.type);
  const [modal, setModal] = useState(null);
  const [questionCntSort, setQuestionCntSort] = useState(sortState);
  const [openPreviewModal, setOpenPreviewModal] = useState(false);
  const [info, setInfo] = useState({ examDuration: 0 });
  const queryRef = useRef({});

  const orderEnum = {
    userCnt: {
      ascend: 'USER_CNT_ASC',
      descend: 'USER_CNT_DESC',
    },
    passCnt: {
      ascend: 'PASS_CNT_ASC',
      descend: 'PASS_CNT_DESC',
    },
    examCreateTime: {
      ascend: 'CREATED_ASC',
      descend: 'CREATED_DESC',
    },
  };

  const columns = [
    {
      title: '考试',
      // fixed:fixStr.left,
      width: 320,
      dataIndex: 'examName',
      render: (text: any, record: any) => {
        var _text = '未开始',
          _color = 'rgba(255, 183, 20, 1)';
        if (moment().valueOf() > record.examEndTime) {
          _text = '已结束';
          _color = 'rgba(153, 153, 153, 1)';
        } else if (moment().valueOf() > record.examStartTime) {
          _text = '进行中';
          _color = 'rgba(59, 189, 170, 1)';
        }

        return (
          <div style={{ width: 320 }}>
            <div className='oneLineText' style={{ width: 320, color: '#333', fontWeight: 'bold' }}>
              {text}
            </div>
            <div>
              {' '}
              <span>
                {moment(record.examStartTime).format('YYYY-MM-DD HH:mm')}~{moment(record.examEndTime).format('YYYY-MM-DD HH:mm')}{' '}
              </span>{' '}
              <div className='status' style={{ border: `1px solid  ${_color}`, borderRadius: 2, color: _color }}>
                {_text}
              </div>
            </div>
            <div>创建人:{record.examCreator}</div>
          </div>
        );
      },
    },
    {
      title: '考试时长',
      dataIndex: 'examDuration',
      render: (text: any) => <span>{(text || 0) / 60 / 1000}分钟</span>,
    },
    {
      title: '及格分/总分',
      dataIndex: 'totalScore',
      render: (text: any, record: any) => <span>{`${record.passScore || 0}/${record.totalScore || 0}`}</span>,
    },
    {
      title: '题目数量',
      align: fixStr.right,
      dataIndex: 'questionCnt',
    },
    {
      title: '参与人数',
      dataIndex: 'userCnt',
      align: fixStr.right,
      sorter: true,
      sortOrder: field === 'userCnt' ? order : sortStatus.type,
    },
    {
      title: '及格数',
      dataIndex: 'passCnt',
      align: fixStr.right,
      sorter: true,
      sortOrder: field === 'passCnt' ? order : sortStatus.type,
    },
    {
      title: '创建时间',
      dataIndex: 'examCreateTime',
      align: fixStr.right,
      sorter: true,
      sortOrder: field === 'examCreateTime' ? order : sortStatus.type,
      render: (text: any, record: any) => <span>{moment(text).format('YYYY-MM-DD HH:mm')}</span>,
    },
    {
      title: '操作',
      fixed: fixStr.right,
      dataIndex: 'operate',
      width: 150,
      render: (text: any, record: any) => (
        <div className='table_operate'>
          {ctx.xmState?.userPermission?.SeeExamData() && [
            <div
              key='data'
              className='operate__item'
              onClick={() => {
                props.history.push({
                  pathname: `${match.url}/analysic/${record.examId}`,
                });
              }}>
              数据
            </div>,
            <span className='operate__item split'> | </span>,
          ]}

          <div
            key='share'
            className='operate__item'
            onClick={() => {
              shareModal(record);
            }}>
            分享
          </div>
          <span className='operate__item split'> | </span>
          <Dropdown overlay={getOpe(record)}>
            <span className='more'>更多</span>
          </Dropdown>
        </div>
      ),
    },
  ];

  function queryExamDetail(examId: string) {
    Service.Hades('public/hades/queryExamDetail', {
      examId,
      tenantId: User.getStoreId(),
      userId: User.getStoreUserId(),
      source: 0,
    }).then((res) => {
      setInfo(res.result);
      setOpenPreviewModal(true);
    });
  }

  function shareModal(record: any) {
    const modal = (
      <ExamShareModal
        data={record}
        close={() => {
          setModal(null);
        }}
      />
    );
    setModal(modal as any);
  }

  function getOpe(item: any) {
    return (
      <Menu>
        <Menu.Item
          key='1'
          onClick={() => {
            queryExamDetail(item.examId);
          }}>
          预览
        </Menu.Item>
        {ctx.xmState?.userPermission?.AddExam() && moment().valueOf() < item.examStartTime && (
          <Menu.Item key='2'>
            <span
              onClick={() => {
                if (moment().valueOf() + 5 * 60 * 1000 > item.examStartTime) {
                  Modal.info({
                    title: '无法编辑',
                    content: '离考试开始时间小于5分钟，为保证答题数据的准确性，不能再进行编辑了',
                  });
                } else {
                  props.history.push({
                    pathname: `${match.url}/edit/${item.examId}`,
                  });
                }
              }}>
              编辑
            </span>
          </Menu.Item>
        )}

        {ctx.xmState?.userPermission?.AddExam() && (
          <Menu.Item key='3' onClick={() => props.history.push(`${match.url}/copy/${item.examId}`)}>
            复制
          </Menu.Item>
        )}
        {ctx.xmState?.userPermission?.DelExam() && (moment().valueOf() + 30 * 60 * 1000 < item.examStartTime || moment().valueOf() > item.examEndTime) && (
          <Menu.Item key='4'>
            <span
              onClick={() => {
                deleteExam(item);
              }}>
              删除
            </span>
          </Menu.Item>
        )}
      </Menu>
    );
  }

  function deleteExam(item: any) {
    Modal.confirm({
      title: '删除考试',
      content: '确定删除该考试吗？',
      okText: '删除',
      cancelText: '取消',
      icon: <span className='icon iconfont default-confirm-icon'>&#xe6f4;</span>,
      onOk: () => {
        Service.Hades('public/hades/deleteExam', {
          examId: item.examId,
          userId: User.getStoreUserId(),
          tenantId: User.getStoreId(),
          source: 0,
        }).then(() => {
          getList();
        });
      },
    });
  }

  function getList() {
    const _query = { ...queryRef.current };
    // if(_query.examCreator){
    //     _query.examCreator =parseInt(_query.examCreator)
    // }

    Service.Hades('public/hades/queryExamPageList', {
      ..._query,
      userId: User.getStoreUserId(),
      tenantId: User.getStoreId(),
      source: 0,
    }).then((res) => {
      setList(res.result?.records || []);
      setTotal(parseInt(res.result.total));
    });
  }

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

  function onShowSizeChange(current: any, size: any) {
    (queryRef.current as any).size = size;
  }

  function onChange(pagination: any, filters: any, sorter: any, extra: any) {
    setfield(sorter.field);
    setOrder(sorter.order);
    let _query: any = { ...queryRef.current };
    _query.order = (orderEnum as any)[sorter.field][sorter.order] || 'EXAM_START_TIME_DESC';
    setQuery(_query);
  }

  const defaultOptions = {
    loop: true,
    autoplay: true,
    animationData: nodata,
    rendererSettings: {
      preserveAspectRatio: 'xMidYMid slice',
    },
  };
  return (
    <div className='page examination-manager'>
      <div className='content-header'>考试</div>
      <div className='box content-body'>
        <div className='xm-search-filter'>
          <div style={{ display: 'flex' }}>
            <div className='search-condition'>
              <div className='search-condition__item'>
                <span className='search-name'>考试名称：</span>
                <Search
                  value={query.examName}
                  className='search-input'
                  placeholder='搜索考试名称'
                  onChange={(e) => {
                    const _query = { ...query };
                    _query.examName = e.target.value;
                    _query.current = 1;
                    setQuery(_query);
                  }}
                  onSearch={() => {}}
                  enterButton={<span className='icon iconfont'>&#xe832;</span>}
                />
              </div>

              <TeacherSelect
                val={query.examCreator}
                onChange={(examCreator: any) => {
                  const _query = { ...query };
                  _query.examCreator = examCreator;
                  _query.current = 1;
                  setQuery(_query);
                }}
                roleCodes={['CloudManager', 'StoreManager']}></TeacherSelect>

              <div className='search-condition__item'>
                <span className='search-name'>考试时间：</span>
                <RangePicker
                  className='search-input'
                  value={[query.examStartTime ? moment(Number(query.examStartTime)) : null, query.examStartTime ? moment(Number(query.examEndTime)) : null]}
                  onChange={(date: any) => {
                    const _query = { ...query };
                    _query.examStartTime = date && date[0]?.startOf('day').valueOf();
                    _query.examEndTime = date && date[1]?.endOf('day').valueOf();
                    _query.current = 1;
                    setQuery(_query);
                  }}
                />
              </div>
              {!!expandFilter && (
                <div className='search-condition__item'>
                  <span className='search-name'>创建时间：</span>
                  <RangePicker
                    className='search-input'
                    value={[
                      query.createStartTime ? moment(Number(query.createStartTime)) : null,
                      query.createStartTime ? moment(Number(query.createEndTime)) : null,
                    ]}
                    onChange={(date: any) => {
                      const _query = { ...query };
                      _query.createStartTime = date && date[0]?.startOf('day').valueOf();
                      _query.createEndTime = date && date[1]?.endOf('day').valueOf();
                      _query.current = 1;
                      setQuery(_query);
                    }}
                  />
                </div>
              )}
            </div>
            <div className='reset-fold-area'>
              <Tooltip title='清空筛选'>
                <span
                  className='resetBtn iconfont icon'
                  onClick={() => {
                    setfield('');
                    setQuery({ current: 1, size: 10, order: 'EXAM_START_TIME_DESC' });
                  }}>
                  &#xe61b;{' '}
                </span>
              </Tooltip>
              <span
                style={{ cursor: 'pointer' }}
                className='fold-btn'
                onClick={() => {
                  setExpandFilter(!expandFilter);
                }}>
                {expandFilter ? (
                  <span>
                    <span>收起</span>
                    <span className='iconfont icon fold-icon'>&#xe82d; </span>{' '}
                  </span>
                ) : (
                  <span>
                    展开<span className='iconfont icon fold-icon'>&#xe835; </span>
                  </span>
                )}
              </span>
            </div>
          </div>
        </div>
        {ctx.xmState?.userPermission?.AddExam() && (
          <Button
            type='primary'
            onClick={() => {
              props.history.push({
                pathname: `${match.url}/add`,
              });
            }}
            style={{ margin: '4px 0 16px' }}>
            新建考试
          </Button>
        )}

        <div className='content'>
          <XMTable
            bordered
            size='small'
            columns={columns}
            dataSource={list}
            scroll={{ x: 1150 }}
            onChange={onChange}
            pagination={false}
            style={{ margin: '0px 0 16px' }}
            renderEmpty={{
              image: (
                <div style={{ marginTop: 24 }}>
                  <Lottie options={defaultOptions} height={150} width={150} isStopped={false} isPaused={false} />
                </div>
              ),
              description: <span style={{ display: 'block', paddingBottom: 24 }}>暂无数据</span>,
            }}></XMTable>
          {total > 0 && (
            <PageControl
              size='small'
              current={query.current - 1}
              pageSize={query.size}
              total={total}
              onShowSizeChange={onShowSizeChange}
              toPage={(page: any) => {
                let _query: any = { ...queryRef.current };
                _query.current = page + 1;
                setQuery(_query);
              }}
            />
          )}
        </div>
      </div>
      {openPreviewModal && (
        <PreviewModal
          info={{ ...info, examDuration: (info.examDuration || 0) / 60000 }}
          onClose={() => {
            setOpenPreviewModal(false);
          }}
        />
      )}
      <Route
        path={`${match.url}/add`}
        render={() => {
          return (
            <AddExam
              type='add'
              freshList={() => {
                let _query: any = { ...queryRef.current };
                if (_query.current != 1) {
                  _query.current = 1;
                  setQuery(_query);
                } else {
                  getList();
                }
              }}
            />
          );
        }}
      />
      <Route
        path={`${match.url}/edit/:id`}
        render={() => {
          return (
            <AddExam
              type='edit'
              freshList={() => {
                getList();
              }}
            />
          );
        }}
      />
      <Route
        path={`${match.url}/copy/:id`}
        render={() => {
          return (
            <AddExam
              type='copy'
              freshList={() => {
                getList();
              }}
            />
          );
        }}
      />

      <Route
        path={`${match.url}/analysic/:id`}
        render={() => {
          return <DataAnalysic />;
        }}
      />
      {modal}
    </div>
  );
}

export default withRouter(ExaminationManager);
