import { api_corpUser_allOfUser } from '@/API/global';
import { useAjax } from '@/Hook/useAjax';
import React, { useEffect, useRef, useState } from 'react';
import { getCorpPhoneMsgAlarmListApi, GetCorpPhoneMsgAlarmListProps, updateCorpPhoneMsgAlarmApi } from '../../API/alarmGl';
import { SearchOutlined } from '@ant-design/icons';
import style from '../corpUserManage/index.less'
import { App, Button, Card, DatePicker, Pagination, Popconfirm, Select, Table } from 'antd';
import SearchBox from '../../components/searchBox';
import { TableConfig } from './tableConfig';
import { useSize } from 'ahooks';

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

    /**************************************/
    const { message } = App.useApp()
    const ref = useRef<HTMLDivElement>(null)
    const size = useSize(ref)
    const userIdStr = sessionStorage.getItem('userId');
    const [userId, setUserId] = useState<number>(userIdStr ? Number(userIdStr) : undefined);
    const [queryForm, setQueryForm] = useState<GetCorpPhoneMsgAlarmListProps>({ pageNum: 1, pageSize: 20 })
    const [activeCorp, setActiveCorp] = useState<any>()
    const [editSelectedRow, setEditSelectedRow] = useState<any[]>([])

    const corpUser_allOfUser = useAjax((params) => api_corpUser_allOfUser(params))
    const getCorpPhoneMsgAlarmList = useAjax((params) => getCorpPhoneMsgAlarmListApi(params))
    const updateCorpPhoneMsgAlarm = useAjax((params) => updateCorpPhoneMsgAlarmApi(params))
    /**************************************/

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

    useEffect(() => {
        getCorpPhoneMsgAlarmList.run({ ...queryForm, sysUserId: userId })
    }, [queryForm, userId])

    const handleMsg = (ids: number[]) => {
        updateCorpPhoneMsgAlarm.run(ids).then(res => {
            if (res) {
                message.success('处理成功')
                getCorpPhoneMsgAlarmList.refresh()
                setEditSelectedRow([])
            }
        })
    }

    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={() => { }} icon={<SearchOutlined />}>搜索</Button>
                            <Popconfirm
                                title="确定处理告警？"
                                onConfirm={() => { handleMsg(editSelectedRow.map(item => item.id)) }}
                                disabled={editSelectedRow.length === 0}
                            >
                                <Button type='primary' danger disabled={editSelectedRow.length === 0}>处理告警</Button>
                            </Popconfirm>
                        </>}
                    >
                        <>
                            <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 }))}
                            />}

                            <DatePicker.RangePicker allowClear onChange={(dates, dateStrings) => {
                                setQueryForm({ ...queryForm, beginTime: dateStrings[0], endTime: dateStrings[1], pageNum: 1 })
                            }} />
                        </>
                    </SearchBox>

                    <div className={style.corpUserList_table} ref={ref}>
                        <Table
                            style={{ marginBottom: 1 }}
                            dataSource={getCorpPhoneMsgAlarmList?.data?.data?.records}
                            loading={getCorpPhoneMsgAlarmList?.loading}
                            columns={TableConfig(handleMsg)}
                            scroll={{ y: size?.height && ref.current ? size?.height - 30 : 300 }}
                            rowKey={(s) => {
                                return s.id
                            }}
                            bordered
                            size='small'
                            pagination={false}
                            rowSelection={{
                                type: 'checkbox',
                                selectedRowKeys: editSelectedRow?.map(item => item.id),
                                getCheckboxProps: (record: any) => {
                                    return {
                                        disabled: record?.status
                                    }
                                },
                                onSelect: (record: { id: any; }, selected: any) => {
                                    if (selected) {
                                        setEditSelectedRow([...editSelectedRow, record])
                                    } else {
                                        setEditSelectedRow(editSelectedRow?.filter(item => item.id !== record.id))
                                    }
                                },
                                onSelectAll: (selected: any, rows: any, changeRows: any[]) => {
                                    if (selected) {
                                        setEditSelectedRow([...editSelectedRow, ...changeRows])
                                    } else {
                                        let newArr = editSelectedRow?.filter(item => changeRows.every(i => i?.id !== item?.id))
                                        setEditSelectedRow(newArr)
                                    }
                                }
                            }}
                        />
                    </div>
                    <div className={style.corpUserList_footer}>
                        <Pagination
                            size="small"
                            total={getCorpPhoneMsgAlarmList?.data?.data?.total || 0}
                            showSizeChanger
                            showQuickJumper
                            pageSize={getCorpPhoneMsgAlarmList?.data?.data?.size || 20}
                            current={getCorpPhoneMsgAlarmList?.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>
        </div>
    );
};

export default AlarmGl;