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

interface sortType {
    type: "ascend" | "descend" | null | undefined
}


function DataAnalysic(props: any) {
    const sortStatus: sortType = {
        type: undefined
    }

    const useDataInit: any = {};
    const queryInit: any = { current: 1, size: 10, };
    const [useData, setUserData] = useState(useDataInit);
    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 userTypeEnum = {
        WORK_WE_CHAT: '企业微信',
        WE_CHAT: '微信'
    }

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

    const ExamPassColorEnum = {
        EXAM_FAIL: 'rgba(255, 79, 79, 1)',
        EXAM_PASS: 'rgba(59, 189, 170, 1)',

    }

    const ExamPassEnum = {
        EXAM_FAIL: '不及格',
        EXAM_PASS: '及格',
    }

    const userExamStateColorEnum = {
        EXAM: 'rgba(35, 143, 255, 1)',
        LACK_EXAM: 'rgba(204, 204, 204, 1)',
        FINISH_EXAM: 'rgba(47, 200, 60, 1)'
    }


    const orderEnum = {
        score: {
            ascend: 'EXAM_SCORE_ASC',
            descend: 'EXAM_SCORE_DESC'
        },
        userDuration: {
            ascend: 'USER_DURATION_ASC',
            descend: 'USER_DURATION_DESC'
        },

    }


    const queryRef = useRef({});

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

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

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

        })
    }


    function queryExamUserDataList() {
        Service.Hades('public/hades/queryExamUserDataList', {
            ...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: "userName",
            render: (text: any, record: any) => <span>{text}<span style={{ color: record.userSource === 'WORK_WE_CHAT' ? 'rgba(255, 157, 20, 1)' : 'rgba(29, 204, 101, 1)' }} >@{(userTypeEnum as any)[record.userSource]}</span></span>,
        },
        {
            title: "手机号",
            dataIndex: "phone",
        },
        {
            title: "考试状态",
            dataIndex: "userExamState",
            render: (text: any) => <span> <span className='exstatus' style={{ background: (userExamStateColorEnum as any)[text] }}></span> {(userExamStateEnum as any)[text]}</span>,

        },
        {
            title: "考试成绩",
            dataIndex: "score",
            sorter: true,
            sortOrder: field === "score" ? order : sortStatus.type,
            render: (text: any, record: any) => <span> {text} <span style={{ border: `1px solid ${(ExamPassColorEnum as any)[record.examPass]}`, fontSize: 12, color: (ExamPassColorEnum as any)[record.examPass], display: 'inline-block', padding: '0px 2px' }}>{(ExamPassEnum as any)[record.examPass]}</span></span>,

        },
        {
            title: "进入考试时间",
            dataIndex: "examStartTime",
            render: (text: any) => <span>{moment(text).format("YYYY-MM-DD HH:mm")}</span>,

        },
        {
            title: "考试用时",
            dataIndex: "userDuration",
            sorter: true,
            sortOrder: field === "userDuration" ? order : sortStatus.type,
            render: (text: any,record:any) => <span>{ record.userExamState==='FINISH_EXAM' ? window.formatHourTime(text):'-'}  </span>,
        },


    ];

    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]
        setQuery(_query)
    }

    function download() {
        Service.Hades('public/hades/exportExamData', {
            // ...query,
            examId: props.examId,
            exportDataType: 'EXAM_USER_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
            target="_blank"
            download
            id="load-play-back-excel"
            style={{ position: "absolute", left: "-10000px" }}
        >
            111
        </a>
        <div className="dataPanal">
            <div className="item">
                <div className="num">{useData.joinCnt || 0}</div>
                <div className="percent"></div>
                <div className="subTitle">参与人数</div>
            </div>
            <div className="item">
                <div className="num">{useData.finishCnt || 0}</div>
                <div className="percent">占比{parseInt(((useData.finishCnt || 0) / (useData.joinCnt || 1)) * 100 + '')}%</div>
                <div className="subTitle">完成考试数 (人)</div>
            </div>
            <div className="item">
                <div className="num">{useData.passCnt || 0}</div>
                <div className="percent">占比{parseInt(((useData.passCnt || 0) / (useData.finishCnt || 1)) * 100 + '')}%</div>
                <div className="subTitle">及格数 (人)</div>
            </div>
            <div className="item">
                <div className="num">{useData.averageScore || 0}</div>
                <div className="percent">总分{props.examDetail?.examPaper?.totalScore}</div>
                <div className="subTitle">平均分</div>
            </div>
            <div className="item">
                <div className="num">  {window.formatHourTime(useData.averageDuration || 0)} </div>
                <div className="percent"></div>
                <div className="subTitle">平均用时</div>
            </div>
        </div>

        <div className="xm-search-filter" style={{ marginTop: 12 }}>
            <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.searchKey = e.target.value
                                setQuery(_query);
                            }}
                            onSearch={() => { }}
                            enterButton={<span className="icon iconfont">&#xe832;</span>}
                        />
                    </div>

                    <div className="search-condition__item">
                        <span className="search-name">用户类型:</span>
                        <Select value={query.userSource} placeholder="请选择用户类型" onChange={(val) => {
                            const _query = { ...query }
                            _query.userSource = val
                            setQuery(_query);
                        }} className='search-input' allowClear>
                            {
                                Object.keys(userTypeEnum).map((key: any) => {
                                    return <Option value={key}>{(userTypeEnum as any)[key]}</Option>
                                })
                            }


                        </Select>
                    </div>

                    <div className="search-condition__item">
                        <span className="search-name">考试状态:</span>
                        <Select value={query.userExamState} placeholder="请选择考试状态" onChange={(val) => {
                            const _query = { ...query }
                            _query.userExamState = val
                            setQuery(_query);
                        }} className='search-input' allowClear>
                            {
                                Object.keys(userExamStateEnum).map((key: any) => {
                                    return <Option value={key}>{(userExamStateEnum as any)[key]}</Option>
                                })
                            }


                        </Select>
                    </div>

                </div>
                <div className="reset-fold-area">
                    <Tooltip title="清空筛选"><span className="resetBtn iconfont icon" onClick={() => {
                        setfield('')
                        setQuery({ current: 1, size: 10 });
                    }}>&#xe61b; </span></Tooltip>

                </div>
            </div>
        </div>
        {
            !!allData && <Button style={{ marginBottom: 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 DataAnalysic;