import React, { useEffect, useRef, useState } from 'react';
import style from '../../corpUserManage/index.less'
import { Button, Card, DatePicker, Form, Input, Modal, Pagination, Select, Table } from 'antd';
import { useSize } from 'ahooks';
import SearchBox from '@/pages/weComTask/components/searchBox';
import { getChatMessageListApi, GetChatMessageListProps } from '@/pages/weComTask/API/chatRecordManage';
import { SearchOutlined } from '@ant-design/icons';
import { api_corpUser_allOfUser } from '@/API/global';
import { useAjax } from '@/Hook/useAjax';
import { useForm } from 'antd/es/form/Form'
import moment from 'dayjs'
import tableConfig, { obj } from './tableConfig';
const { RangePicker } = DatePicker;

const ChatRecord: React.FC = () => {

    /*****************************************/
    const ref = useRef<HTMLDivElement>(null)
    const size = useSize(ref)
    const userIdStr = sessionStorage.getItem('userId');
    const chatRecordFilterValue = localStorage.getItem('chatRecordFilter')
    const [userId] = useState<number>(userIdStr ? Number(userIdStr) : undefined);
    const [activeCorp, setActiveCorp] = useState<any>()
    const [filterOpen, setFilterOpen] = useState<boolean>(false)
    const [filterForm] = useForm()

    const [queryForm, setQueryForm] = useState<GetChatMessageListProps>({ 
        pageNum: 1, 
        pageSize: 50, 
        messageTimeStart: moment().format('YYYY-MM-DD'), 
        messageTimeEnd: moment().format('YYYY-MM-DD'),
        ...(chatRecordFilterValue ? JSON.parse(chatRecordFilterValue) : {})
    })

    const corpUser_allOfUser = useAjax((params) => api_corpUser_allOfUser(params))
    const getChatMessageList = useAjax((params) => getChatMessageListApi(params))
    /*****************************************/

    useEffect(() => {
        if (chatRecordFilterValue && Object.keys(chatRecordFilterValue).length && filterOpen) {
            filterForm.setFieldsValue(JSON.parse(chatRecordFilterValue))
        }
    }, [chatRecordFilterValue, filterOpen])

    useEffect(() => {
        if (userId) {
            corpUser_allOfUser.run(userId)
        }
    }, [userId])

    useEffect(() => {
        getChatMessageList.run({ ...queryForm })
    }, [queryForm])

    //关闭弹窗存储
    const formSave = () => {
        let value = filterForm.getFieldsValue()
        setQueryForm({ ...queryForm, ...value })
        //存放到本地存储
        localStorage.setItem('chatRecordFilter', JSON.stringify(value))
        //关闭弹窗
        setFilterOpen(false)
    }

    return (
        <div className={style.corpUserManage}>
            <div className={style.corpUserManage_bottom} style={{ height: '100%' }}>
                <Card className={style.corpUserList} styles={{ body: { padding: 0, display: 'flex', flexDirection: 'column', height: '100%' } }}>
                    <SearchBox
                        bodyPadding={`16px 16px 12px`}
                        buttons={<>
                            <Button type="primary" onClick={() => getChatMessageList.refresh()} icon={<SearchOutlined />}>搜索</Button>
                            <Button onClick={() => { setFilterOpen(true) }} type="primary">过滤配置</Button>
                        </>}
                    >
                        <>
                            <Select
                                style={{ width: 180 }}
                                placeholder="选择企业"
                                value={queryForm?.corpId}
                                showSearch
                                maxTagCount={1}
                                allowClear
                                onChange={(e, option: any) => {
                                    setQueryForm({ ...queryForm, corpId: e, pageNum: 1 })
                                    setActiveCorp(option?.data)
                                }}
                                filterOption={(input: string, option?: { label: string; value: string }) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                                options={corpUser_allOfUser?.data?.data?.map((item: { t1: any }) => ({ label: item.t1?.corpName, value: item.t1?.corpId, data: item }))}
                            />
                            {activeCorp && <Select
                                style={{ minWidth: 125 }}
                                placeholder='企微号'
                                allowClear
                                autoClearSearchValue={false}
                                onChange={(e) => setQueryForm({ ...queryForm, corpUserId: e, pageNum: 1 })}
                                value={queryForm?.corpUserId}
                                filterOption={(input, option) =>
                                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                                }
                                options={activeCorp?.t2?.map((item: any) => ({ label: item.name, value: item.corpUserId }))}
                            />}

                            <Input placeholder='聊天内容模糊查询' allowClear value={queryForm?.messageContent} onChange={(e) => {
                                const value = e.target.value?.replace(/\s/ig, '')
                                setQueryForm({ ...queryForm, messageContent: value, pageNum: 1 })
                            }} />
                            <Input placeholder='群名称模糊查询' allowClear value={queryForm?.chatName} onChange={(e) => {
                                const value = e.target.value?.replace(/\s/ig, '')
                                setQueryForm({ ...queryForm, chatName: value, pageNum: 1 })
                            }} />
                            <Input placeholder='发送人昵称模糊查询' allowClear value={queryForm?.senderName} onChange={(e) => {
                                const value = e.target.value?.replace(/\s/ig, '')
                                setQueryForm({ ...queryForm, senderName: value, pageNum: 1 })
                            }} />
                            <Select
                                style={{ minWidth: 125 }}
                                placeholder='聊天类型'
                                allowClear
                                autoClearSearchValue={false}
                                onChange={(e) => { setQueryForm({ ...queryForm, chatType: e, pageNum: 1 }) }}
                                value={queryForm?.chatType}
                                filterOption={(input, option) =>
                                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                                }
                                options={[
                                    {
                                        label: '群聊',
                                        value: 1
                                    },
                                    {
                                        label: '单聊',
                                        value: 2
                                    }
                                ]}
                            />
                            <Select
                                style={{ minWidth: 125 }}
                                placeholder='消息类型'
                                allowClear
                                autoClearSearchValue={false}
                                mode='multiple'
                                maxTagCount={2}
                                onChange={(e) => { setQueryForm({ ...queryForm, msgType: e, pageNum: 1 }) }}
                                value={queryForm?.msgType}
                                filterOption={(input, option) =>
                                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                                }
                                options={Object.keys(obj).map((item) => ({ label: obj[item], value: item }))}
                            />
                            <Select
                                style={{ minWidth: 125 }}
                                placeholder='风险等级'
                                allowClear
                                autoClearSearchValue={false}
                                onChange={(e) => { setQueryForm({ ...queryForm, riskLevel: e }) }}
                                value={queryForm?.riskLevel}
                                filterOption={(input, option) =>
                                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                                }
                                options={[
                                    {
                                        label: '低',
                                        value: 1
                                    },
                                    {
                                        label: '中',
                                        value: 2
                                    },
                                    {
                                        label: '高',
                                        value: 3
                                    }
                                ]}
                            />
                            <RangePicker onChange={(date, dataString) => {
                                setQueryForm({ ...queryForm, messageTimeStart: dataString[0], messageTimeEnd: dataString[1] })
                            }} value={[queryForm.messageTimeStart ? moment(queryForm.messageTimeStart) : null, queryForm.messageTimeEnd ? moment(queryForm.messageTimeEnd) : null]} />
                        </>
                    </SearchBox>
                    <div className={style.corpUserList_table} ref={ref}>
                        <Table
                            style={{ marginBottom: 1 }}
                            dataSource={getChatMessageList?.data?.data?.records}
                            loading={getChatMessageList?.loading}
                            columns={tableConfig()}
                            scroll={{ x: "max-content", y: size?.height && ref.current ? size?.height - 32 : 300 }}
                            rowKey={(s) => {
                                return s.id
                            }}
                            bordered
                            size='small'
                            pagination={false}
                        />
                    </div>
                    <div className={style.corpUserList_footer}>
                        <Pagination
                            size="small"
                            total={getChatMessageList?.data?.data?.total || 0}
                            showSizeChanger
                            showQuickJumper
                            pageSize={getChatMessageList?.data?.data?.size || 20}
                            current={getChatMessageList?.data?.data?.current || 1}
                            onChange={(page: number, pageSize: number) => {
                                ref.current?.scrollTo({ top: 0 })
                                setQueryForm({ ...queryForm, pageNum: page, pageSize })
                            }}
                            showTotal={(total: number) => <span style={{ fontSize: 12 }}>共 {total} 条</span>}
                        />
                    </div>
                </Card>
            </div>
            {/* 过滤配置 */}
            <Modal
                title="过滤配置-会保存在浏览器本地"
                open={filterOpen}
                onCancel={() => {
                    formSave()
                }}
                footer={null}
            >
                <Form
                    labelCol={{ span: 5 }}
                    form={filterForm}
                >
                    <Form.Item label="排除包含的发送人" name="excludeSenderNames">
                        <Select
                            mode="tags"
                            style={{ width: '100%' }}
                            placeholder="输入内容按回车添加,可添加多个！"
                            onChange={(value: any) => { console.log(value) }}
                            options={[]}
                        />
                    </Form.Item>
                    <Form.Item label="排除包含的内容" name="excludeContents">
                        <Select
                            mode="tags"
                            style={{ width: '100%' }}
                            placeholder="输入内容按回车添加,可添加多个！"
                            onChange={(value: any) => { console.log(value) }}
                            options={[]}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default ChatRecord;