import React, { useEffect, useRef, useState } from 'react';
import { Route, withRouter } from "react-router-dom";
import { Row, Input, Select, Tooltip, Col } from 'antd';
import RangePicker from '@/modules/common/DateRangePicker';
import WWOpenDataCom from '@/components/WWOpenDataCom';
import { PageControl, XMTable } from '@/components';
import Service from '@/common/js/service';
import ENUM from '../../enum';
import User from '@/common/js/user';
import moment from 'moment';

const { Search } = Input;
const { Option } = Select;
declare var formatDate: any;

function StudyTable(props: any) {
    console.log(props, 'rtyjukl')
    const [query, setQuery] = useState<any>({
        size: 10,
        taskId: props.taskId,
        source: 0,
        storeId: User.getStoreId(),
        storeUserId: User.getStoreUserId(),
        userId: User.getStoreUserId(),
    });
    const [list, setList] = useState<any[]>([]);
    const [total, setTotal] = useState<any>(0);
    const [name, setName] = useState<any>('');
    const [current, setCurrent] = useState<any>(1);
    const [orderFiled, setOrderFiled] = useState<any>(null);
    const [sort, setSort] = useState<any>(null);
    const [sortedList, setSortedList] = useState<any[]>([]);
    const timer = useRef<any>(null);
    const sortNameMap: any = {
        learnPercentage: 'LEARN_NUM',
        latelyLearnTime: 'LATE_LEARN_TIME',
        startLearnTime: 'START_LEARN_TIME',
    }

    useEffect(() => {
        getList()
    }, [query])


    useEffect(() => {
        console.log(sort, orderFiled)
        if (sort && orderFiled) {
            const _list = [...list];
            _list.sort((pre: any, next: any) => {
                if (sort === 'ascend') {
                    return (pre[orderFiled] || 0) - (next[orderFiled] || 0)
                } else {
                    return (next[orderFiled] || 0) - (pre[orderFiled] || 0)
                }
            })

            setSortedList(_list)



        } else {
            setSortedList(list)
        }

    }, [list, sort, orderFiled])



    function getList() {
        Service.Hades('public/hades/getTaskCustomerRecordPage', query).then((res: any) => {
            res.result.map((item: any) => {
                item.department = item.departmentNameList?.map((_item: any) => {
                    if (_item == '1000') {
                        return '微信'
                    } else {
                        return <WWOpenDataCom type="departmentName" openid={_item} />
                    }
                })

            })
            setList(res.result)
            setTotal(res.result.length)
        })
    }

    const columns = [
        {
            title: '学员',
            key: 'storeCustomerName',
            dataIndex: 'storeCustomerName',
            width: "15%",
            render: (val: any, record: any) => {
                return <div>{val}
                    <span
                        className="tag"
                        style={{ color: record.sourceEnum === 'WORK_WE_CHAT' ? '#2966FF' : '#1DCC65' }}
                    >{record.sourceEnum === 'WORK_WE_CHAT' ? '@企业微信' : '@微信'}</span>
                </div>;
            },
        },
        {
            title: '部门',
            key: 'departmentNameList',
            dataIndex: 'departmentNameList',
            render: (val: any, record: any) => {
                return <div>
                    {
                        record.department?.map((item: any, index: number) => {
                            if ((index + 1) == record.department.length) {
                                return item
                            } else {
                                return [item, ';']
                            }

                        })
                    }</div>
            },

        },
        {
            title: '岗位',
            key: 'postNameList',
            dataIndex: 'postNameList',

        },
        {
            title: '学习状态',
            key: 'learnState',
            dataIndex: 'learnState',
            render: (val: any, record: any) => {

                return <div>{ENUM.learnState[val].text}</div>;
            },
        },
        {
            title: <div>学习进度  <Tooltip
                title={'已完成任务数/任务总数'}>
                <span
                    style={{ color: "rgba(191, 191, 191, 1)", fontWeight: 400 }}
                    className="iconfont"
                >&#xe61d;</span>
            </Tooltip></div>,
            key: 'learnPercentage',
            sorter: true,
            dataIndex: 'learnPercentage',
            sortOrder: (orderFiled == 'learnPercentage') ? sort : null,
            render: (val: any, record: any) => {
                return `${val}%`;
            },
        },

        {
            title: '最近学习时间',
            key: 'latelyLearnTime',
            dataIndex: 'latelyLearnTime',
            sorter: true,
            width: 240,
            sortOrder: (orderFiled == 'latelyLearnTime') ? sort : null,
            render: (val: any, record: any) => {
                return `${formatDate('YYYY-MM-DD H:i', parseInt(record.latelyLearnTime))}`;
            },
        },
        {
            title: '开始学习时间',
            key: 'startLearnTime',
            dataIndex: 'startLearnTime',
            width: 240,
            sorter: true,
            field: 'yuiooo',
            sortOrder: (orderFiled == 'startLearnTime') ? sort : null,
            render: (val: any, record: any) => {
                return <div>{formatDate('YYYY-MM-DD H:i', val)}</div>;
            },
        },

        {
            title: '操作',
            key: 'operate',
            dataIndex: 'operate',
            fixed: 'right',
            width: '8%',
            render: (val: any, record: any) => {
                return (
                    <div className='operate-area'>
                        <span
                            className='operate-item'
                            style={{ color: 'rgba(41, 102, 255, 1)', cursor: 'pointer' }}
                            onClick={() => {
                                props.history.push(`${props.match.url}/user-learning-data/${record.storeCustomerId}`);
                            }}>
                            查看数据
                        </span>
                    </div>
                );
            },
        },
    ];

    function onChange(pagination: any, filters: any, sorter: any, extra: any) {
        console.log(sorter)
        setOrderFiled(sorter.field || null)
        setSort(sorter.order)
        setCurrent(1)
    }



    return <div className="study_Table">
        <div className="filter">
            <Row>
                <Col span={7}>
                    <div className='xm_search_item'>
                        <span className='label'>学员：</span>
                        <div className="search">
                            <Search
                                value={name}
                                placeholder='搜索学员名称'
                                onChange={(e) => {
                                    setName(e.target.value);
                                    clearTimeout(timer.current)
                                    var name = e.target.value
                                    timer.current = setTimeout(() => {
                                        setQuery({
                                            ...query,
                                            customerName: name
                                        })
                                        setCurrent(1)
                                    }, 500)

                                }}
                                onSearch={() => {

                                }}
                                enterButton={<span className='icon iconfont'>&#xe832;</span>}
                            />
                        </div>

                    </div>
                </Col>
                <Col span={7}>
                    <div className='xm_search_item'>
                        <span className='label '>学习状态：</span>
                        <div className="search">
                            <Select
                                style={{ width: '100%' }}
                                placeholder='请选择当前状态'
                                allowClear={true}
                                value={query.learnState}
                                onChange={(value) => {
                                    setQuery({
                                        ...query,
                                        learnState: value
                                    })
                                    setCurrent(1)
                                }}
                                suffixIcon={
                                    <span className='icon iconfont' style={{ fontSize: '12px', color: '#BFBFBF' }}>
                                        &#xe835;
                                    </span>
                                }>
                                {
                                    Object.keys(ENUM.learnState).map((key: any) => {
                                        return <Option value={key}>{ENUM.learnState[key].text}</Option>
                                    })
                                }


                            </Select>
                        </div>

                    </div>
                </Col>
                <Col span={7}>
                    <div className='xm_search_item'>
                        <span className='label'>最近学习日期：</span>
                        <div className="search">
                            <RangePicker
                                style={{ width: '100%' }}
                                id='course_date_picker'
                                allowClear={false}
                                value={query.startTime ? [moment(query.startTime), moment(query.endTime)] : null}
                                format={'YYYY-MM-DD'}
                                onChange={(dates: any) => {
                                    setQuery({
                                        ...query,
                                        startTime: dates[0]?.startOf('day').valueOf(),
                                        endTime: dates[0]?.endOf('day').valueOf(),
                                    })
                                    setCurrent(1)
                                }}

                            />
                        </div>

                    </div>
                </Col>
                <Col offset={2} span={1} >
                    <Tooltip title='清空筛选'>
                        <span className='resetBtn iconfont icon' onClick={() => {
                            setName('');
                            setQuery({
                                size: 10,
                                taskId: props.taskId,
                                source: 0,
                                storeId: User.getStoreId(),
                                storeUserId: User.getStoreUserId(),
                                userId: User.getStoreUserId(),
                            })
                            setCurrent(1)
                            setSort('')
                        }}>
                            &#xe61b;{' '}
                        </span>
                    </Tooltip>
                </Col>
            </Row>

        </div>
        <div style={{ marginTop: 12 }}>
            <XMTable
                renderEmpty={{
                    type: 'college',
                    description: '暂无数据',
                }}
                rowKey={(record: any, index: any) => record.storeCustomerId + '_' + index}
                dataSource={sortedList.slice((current - 1) * query.size, current * query.size)}
                columns={columns}
                pagination={false}
                className='user-learning-table'
                onChange={onChange}
                showSorterTooltip={false}
                bordered
                scroll={{ x: 1400 }}
            />
            {list && list.length > 0 && (
                <div className='box-footer'>
                    <PageControl
                        current={current - 1}
                        pageSize={query.size}
                        total={total}
                        toPage={(page: any) => {
                            setCurrent(page + 1)

                        }}

                    />
                </div>
            )}
        </div>

    </div>
}

export default withRouter(StudyTable)