import React, { useState, useRef, useEffect, useContext } from 'react'
import { Row, Input, Select, DatePicker, Tooltip, Button, Table, Dropdown, Menu } from 'antd';
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 } from "@/components";
import AddExam from './AddExam';
import User from "@/common/js/user";
import { XMContext } from "@/store/context";
import StoreService from "@/domains/store-domain/storeService";
import './index.less'
const { RangePicker } = DatePicker;
const { Search } = Input;
const { Option } = Select;

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

    const examStatus = {
        EXAM_INIT: '未开始', EXAM_STARTED: '进行中', EXAM_FINISHED: '已结束'
    }
    const { match } = props;
    const sortState: any = false;
    const ctx: any = useContext(XMContext);
    console.log(ctx)
    const [query, setQuery] = useState(queryInit);
    const [expandFilter, setExpandFilter] = useState(false);
    const [total, setTotal] = useState(0);
    const [list, setList] = useState([]);
    const [questionCntSort, setQuestionCntSort] = useState(sortState)
    const queryRef = useRef(null);


    const columns = [
        {
            title: "考试",
            // fixed:'left',
            // width:350,
            dataIndex: "examName",
            render: (text: any, record: any) => <div style={{ width: 330 }}>
                <div className='oneLineText' style={{ width: 330 }} >{text}</div>
                <div>{moment(record.examStartTime).format("YYYY-MM-DD HH:mm")}~{moment(record.examEndTime).format("YYYY-MM-DD HH:mm")}  <div className="status">{(examStatus as any)[record.examState]}</div></div>
                <div>创建人:{record.examCreator}</div>
            </div>,
        },
        {
            title: "考试时长",
            dataIndex: "examDuration",
            render: (text: any) => <span>{text || 0}分</span>,
        },
        {
            title: "及格分/总分",
            dataIndex: "totalScore",
            render: (text: any, record: any) => <span>{`${record.passScore || 0}/${record.totalScore || 0}`}</span>,
        },
        {
            title: "题目数量",
            dataIndex: "questionCnt",

        },
        {
            title: "参与人数",
            dataIndex: "userCnt",
            sorter: true,
            // sortDirections: ['USER_CNT_DESC', 'USER_CNT_ASC'],
            sortOrder: null,

        },
        {
            title: "及格数",
            dataIndex: "userCnt",

        },
        {
            title: "创建时间",
            dataIndex: "examCreateTime",
            render: (text: any, record: any) => <span>{moment(text).format("YYYY-MM-DD HH:mm")}</span>,
        },
        {
            title: "操作",
            dataIndex: "operate",
            render: (text: any, record: any) => <div className="table_operate">
                {
                    ctx.xmState?.userPermission?.SeeExamData() && [<div
                        key="data"
                        className="operate__item"
                        onClick={() => { }}
                    >
                        数据
                      </div>,
                    <span className="operate__item split" > | </span>]
                }


                <div
                    key="share"
                    className="operate__item"
                    onClick={() => { }}
                >
                    分享
                      </div>

                {
                    (ctx.xmState?.userPermission?.AddExam() || ctx.xmState?.userPermission?.DelExam()) && [<span className="operate__item split" > | </span>, <Dropdown overlay={getOpe(record)}>
                        <span className='more'>更多</span>
                    </Dropdown>]
                }



            </div>,
        },


    ];

    function getOpe(item: any) {
        return <Menu>
            {
                ctx.xmState?.userPermission?.AddExam() && <Menu.Item key="0">
                    <span
                        onClick={() => {

                        }}
                    >
                        编辑
           </span>
                </Menu.Item>
            }

            {
                ctx.xmState?.userPermission?.DelExam() && <Menu.Item key="1">
                    <span
                        onClick={() => {

                        }}
                    >
                        删除
          </span>
                </Menu.Item>
            }


        </Menu>
    }


    function getList() {
        Service.Hades("public/hades/queryExamPageList", {
            ...query, userId: User.getStoreUserId(),
            tenantId: User.getStoreId(),
            source: 0
        }).then((res) => {
            setList(res.result?.records || [])
        })
    }

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

    function onShowSizeChange(current: any, size: any) {
        setQuery({ current: 1, size, order: 'PASS_CNT_DESC' })
    }

    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
                                    setQuery(_query);
                                }}
                                onSearch={() => { }}
                                enterButton={<span className="icon iconfont">&#xe832;</span>}
                            />
                        </div>

                        <TeacherSelect val={query.examCreator} onChange={(examCreator: any) => {

                            const _query = { ...query }
                            _query.examCreator = examCreator;
                            setQuery(_query);
                        }} ></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[0]?.endOf('day').valueOf();
                                    setQuery(_query);

                                }} />
                        </div>
                        <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[0]?.endOf('day').valueOf();
                                    setQuery(_query);

                                }} />
                        </div>
                    </div>
                    <div className="reset-fold-area">
                        <Tooltip title="清空筛选"><span className="resetBtn iconfont icon" onClick={() => {
                            setQuery({ current: 1, size: 10, order: 'PASS_CNT_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: '12px 0' }}>新建考试</Button>

            }


            <div className="content">
                <Table
                    bordered
                    size="small"
                    columns={columns}
                    dataSource={list}
                    onChange={() => { }}
                    scroll={{ x: 1100 }}
                    pagination={false}
                    style={{ margin: '16px 0' }}>
                </Table>
                {total > 0 &&
                    <PageControl
                        size="small"
                        current={query.current - 1}
                        pageSize={query.size}
                        total={total}
                        onShowSizeChange={onShowSizeChange}
                        toPage={(page: any) => {
                            let _query: any = { ...query.current };
                            _query.current = page;
                            setQuery(_query)
                        }}
                    />
                }
            </div>
        </div>
        <Route path={`${match.url}/add`} component={AddExam} />
    </div>
}

export default withRouter(ExaminationManager);