import React, { useState, useRef, useEffect, useContext } from 'react'
import { Input, Select, DatePicker, Tooltip, Button, Table, Dropdown, Menu, Modal } 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 ExamShareModal from './ExamShareModal'
import DataAnalysic from './DataAnalysic'
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 queryRef = useRef({});

    const orderEnum = {
        userCnt: {
            ascend: 'USER_CNT_ASC',
            descend: 'USER_CNT_DESC'
        },
        passCnt: {
            ascend: 'PASS_CNT_ASC',
            descend: 'PASS_CNT_DESC'
        },
        examCreateTime: {
            ascend: 'EXAM_START_TIME_ASC',
            descend: 'EXAM_START_TIME_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",
            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",
            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>

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



            </div>,
        },


    ];

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

    function getOpe(item: any) {
        return <Menu>
            {
                ctx.xmState?.userPermission?.AddExam() && (moment().valueOf() < item.examStartTime) && <Menu.Item key="0">
                    <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?.DelExam() && (moment().valueOf() + 30 * 60 * 1000 < item.examStartTime) && <Menu.Item key="1">
                    <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)
        console.log(sorter.field, sorter.order, (orderEnum as any)[sorter.field])
        let _query: any = { ...queryRef.current };
        _query.order = (orderEnum as any)[sorter.field][sorter.order] || 'EXAM_START_TIME_DESC'
        setQuery(_query)
    }

    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">
                <Table
                    bordered
                    size="small"
                    columns={columns}
                    dataSource={list}
                    scroll={{ x: 1150 }}
                    onChange={onChange}
                    pagination={false}
                    style={{ margin: '0px 0 16px' }}
                >
                </Table>
                {total > 0 &&
                    <PageControl
                        size="small"
                        current={query.current - 1}
                        pageSize={query.size}
                        total={total}
                        onShowSizeChange={onShowSizeChange}
                        toPage={(page: any) => {
                            console.log(page)
                            let _query: any = { ...queryRef.current };
                            _query.current = page + 1;
                            setQuery(_query)
                        }}
                    />
                }
            </div>
        </div>
        <Route path={`${match.url}/add`} render={() => {
            return <AddExam 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}/analysic/:id`} render={() => {
            return <DataAnalysic />;
        }} />
        {
            modal
        }

    </div>
}

export default withRouter(ExaminationManager);