import React, { useCallback, useEffect, useRef, useState } from 'react';
import style from '../../corpUserManage/index.less'
import { App, Button, Card, DatePicker, Drawer, Input, Pagination, Popconfirm, Select, Space, Table, Tabs, Tag, Typography } from 'antd';
import { MenuUnfoldOutlined, MenuFoldOutlined, SearchOutlined } from '@ant-design/icons';
import { useAjax } from '@/Hook/useAjax';
import { api_corpUser_allOfUser, getAdAccountAllOfMember } from '@/API/global';
import TeamMembers from '@/components/Team/teamMembers';
import SearchBox from '@/pages/weComTask/components/searchBox';
import { ApiParamsChatListProps, disbandChatApi, getGroupChatCountApi, getGroupChatListApi } from '@/pages/weComTask/API/global';
import { useSize } from 'ahooks';
import { TableConfig } from './tableConfig';
import UserContent from './userContent';
import RemarkSet from './remarkSet';
import DisbandChatLog from './disbandChatLog';
import ZpMp from './zpMp';
import ChatLog from './chatLog';
import { getBindMpListApi } from '@/pages/weComTask/API/corpUserAssign';
const { Title } = Typography;

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

    /************************************/
    const { message } = App.useApp()
    const ref = useRef<HTMLDivElement>(null)
    const size = useSize(ref)
    const [activeKey, setActiveKey] = useState<string>('1')
    const [showLeft, setShowLeft] = useState<boolean>(false)
    const userIdStr = sessionStorage.getItem('userId');
    const [userId, setUserId] = useState<number>(userIdStr ? Number(userIdStr) : undefined);
    const [listData, setListData] = useState<ApiParamsChatListProps>({
        pageNum: 1,
        pageSize: 20
    })
    const [userQuerys, setUserQuerys] = useState<{
        numArr: Array<number | undefined>,
        value: number | null,
        options: { value: number, label: string }[]
    }>({
        numArr: [0, 100],
        value: null,
        options: []
    })
    const [open, setOpen] = useState(false)
    const [activeCorp, setActiveCorp] = useState<any>()
    const [editSelectedRow, setEditSelectedRow] = useState<any[]>([])
    const [userData, setUserData] = useState<any>()
    const [remarkVisible, setRemarkVisible] = useState<boolean>(false)
    const [zpVisible, setZpVisible] = useState<boolean>(false)
    const [chatLogData, setChatLogData] = useState<{ visible: boolean, chatData: any }>();

    const corpUser_allOfUser = useAjax((params) => api_corpUser_allOfUser(params))
    const getGroupChatList = useAjax((params) => getGroupChatListApi(params))
    const getGroupChatCount = useAjax((params) => getGroupChatCountApi(params))
    const allOfMember = useAjax(() => getAdAccountAllOfMember())
    const disbandChat = useAjax((params) => disbandChatApi(params))
    const getBindMpList = useAjax(() => getBindMpListApi())
    /************************************/

    useEffect(() => {
        allOfMember.run()
        getBindMpList.run()
    }, [])

    useEffect(() => {
        if (userId) {
            corpUser_allOfUser.run(userId).then(res => {
                setActiveCorp(res?.data?.[0])
                setListData({ ...listData, corpId: res?.data?.[0]?.t1?.corpId, pageNum: 1 })
            })
        }
    }, [userId])

    // 初始请求
    useEffect(() => {
        if (listData.corpId) {
            getList()
        } else if (getGroupChatList?.data) {
            getGroupChatList.mutate({ data: { records: [], size: 20, total: 0, pages: 0, current: 1 } })
            getGroupChatCount.mutate({ data: {} })
        }
    }, [listData])

    //搜索事件
    const getList = () => {
        getGroupChatList.run({ ...listData })
        getGroupChatCount.run({ ...listData })
    }


    // 人数输入确定
    const setNum = useCallback(() => {
        let options = [
            { value: 1, label: `最小${userQuerys.numArr[0]}人` + '~' + `最大${userQuerys.numArr[1]}人` }
        ]
        setUserQuerys({
            ...userQuerys,
            value: 1,
            options
        })
        setListData({ ...listData, userCountMin: userQuerys.numArr[0], userCountMax: userQuerys.numArr[1], })
        setOpen(false)
    }, [userQuerys, listData])


    //查看客户
    const lockUsers = (data: any) => {
        setUserData(data)
    }

    // 解散群聊
    const disbandChatHandle = () => {
        disbandChat.run({ chatIdList: editSelectedRow.map(item => item.chatId), corpId: listData.corpId }).then(res => {
            if (res?.data) {
                message.success('任务提交成功')
                getGroupChatList.refresh()
            }
        })
    }

    const handleChatLog = (d: any) => {
        setChatLogData({ visible: true, chatData: d });
    }

    return <div className={style.corpUserManage}>
        <Tabs
            tabBarStyle={{ marginBottom: 1 }}
            activeKey={activeKey}
            type="card"
            onChange={(activeKey) => {
                if (activeKey !== 'contract') {
                    if (activeKey === '1') {
                        setUserId(Number(userIdStr));
                    }
                    setActiveKey(activeKey)
                } else {
                    setShowLeft(!showLeft)
                }
            }}
            items={[{ label: '我的', key: '1' }, { label: '组员', key: '2' }, { label: showLeft ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />, key: 'contract' }]}
        />
        <div className={style.corpUserManage_bottom}>
            {!showLeft && activeKey === '2' && <TeamMembers
                allOfMember={allOfMember}
                onChange={(putUserId) => {
                    setUserId(putUserId);
                }}
                value={userId}
            />}

            <Card className={style.corpUserList} styles={{ body: { padding: 0, display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' } }}>
                <SearchBox
                    bodyPadding={`16px 16px 12px`}
                    buttons={<>
                        <Button type="primary" onClick={() => getList()} icon={<SearchOutlined />}>搜索</Button>
                        <Button onClick={() => setRemarkVisible(true)} disabled={editSelectedRow.length === 0} type="primary">添加备注</Button>
                        <Popconfirm
                            title="确定解散群聊？"
                            onConfirm={disbandChatHandle}
                            disabled={editSelectedRow.length === 0}
                        >
                            <Button disabled={editSelectedRow.length === 0} loading={disbandChat.loading} danger type="primary">解散群聊</Button>
                        </Popconfirm>
                        <DisbandChatLog corpId={listData.corpId} />
                        <Button onClick={() => setZpVisible(true)} disabled={editSelectedRow.length === 0} type="primary">指派公众号</Button>
                    </>}
                >
                    <>
                        <Select
                            style={{ width: 180 }}
                            placeholder="选择企业"
                            value={listData?.corpId}
                            showSearch
                            maxTagCount={1}
                            onChange={(e, option: any) => {
                                setListData({ ...listData, 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 }))}
                        />
                        <Input placeholder="群名称"
                            allowClear
                            style={{ maxWidth: 150 }}
                            onChange={(e) => {
                                let v = e.target.value
                                setListData({ ...listData, chatName: v })
                            }}
                        />
                        <Select
                            style={{ minWidth: 150 }}
                            placeholder="选择群主"
                            value={listData?.corpUserId}
                            showSearch
                            allowClear
                            mode="multiple"
                            maxTagCount={1}
                            onChange={(e) => {
                                setListData({ ...listData, corpUserId: e, pageNum: 1 })
                            }}
                            filterOption={(input: string, option?: { label: string; value: string }) =>
                                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                            options={activeCorp?.t2?.map((item: { name: any; corpUserId: any }) => ({ label: item.name, value: item.corpUserId }))}
                        />
                        <DatePicker.RangePicker placeholder={['建群开始日期', '建群结束日期']} allowClear onChange={(dates, dateStrings) => {
                            console.log(dateStrings)
                            setListData({ ...listData, createTimeStart: dateStrings[0], createTimeEnd: dateStrings[1] })
                        }} />
                        <Select
                            style={{ width: 200 }}
                            placeholder='群人数'
                            value={userQuerys.value}
                            options={userQuerys.options}
                            allowClear
                            onChange={(value) => {
                                if (!value) {
                                    setUserQuerys({
                                        numArr: [0, 100],
                                        value: null,
                                        options: []
                                    })
                                    let { userCountMin, userCountMax, ...newObj } = listData
                                    setListData(newObj)
                                }
                                console.log(value)
                            }}
                            open={open}
                            onDropdownVisibleChange={(open) => {
                                setOpen(open)
                            }}
                            dropdownRender={() => {
                                return <div >
                                    <div style={{ display: 'flex', flexFlow: 'row', alignItems: 'center' }}>
                                        <Input placeholder="最小人数" allowClear value={userQuerys.numArr[0]} onChange={(e) => {
                                            let value = e.target.value
                                            if (!isNaN(Number(value)) && !value.includes('.')) {
                                                console.log(11111)
                                                let newArr = userQuerys.numArr
                                                newArr[0] = Number(value)
                                                setUserQuerys({ ...userQuerys, numArr: newArr })
                                            }
                                        }} />~<Input placeholder="最大人数" allowClear value={userQuerys.numArr[1]} onChange={(e) => {
                                            let value = e.target.value
                                            if (!isNaN(Number(value)) && !value.includes('.')) {
                                                let newArr = userQuerys.numArr
                                                newArr[1] = Number(value)
                                                setUserQuerys({ ...userQuerys, numArr: newArr })
                                            }
                                        }} />
                                    </div>
                                    <Button style={{ width: '100%', marginTop: 5 }} type='primary' onClick={setNum}>确定</Button>
                                </div>
                            }}
                        />
                        <Input placeholder="群备注"
                            allowClear
                            style={{ maxWidth: 150 }}
                            onChange={(e) => {
                                let v = e.target.value
                                setListData({ ...listData, remark: v })
                            }}
                        />
                        <Select
                            style={{ width: 180 }}
                            placeholder="公众号绑定状态查询"
                            value={listData?.mpAccountIdIsNull}
                            showSearch
                            allowClear
                            disabled={!!listData?.mpAccountId}
                            onChange={(e) => {
                                setListData({ ...listData, mpAccountIdIsNull: e, mpAccountId: undefined, pageNum: 1 })
                            }}
                            filterOption={(input: string, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                            options={[{ label: '查询所有群聊', value: false }, { label: '查询没有绑定公众号群聊', value: true }]}
                        />
                        <Select
                            style={{ width: 180 }}
                            placeholder="公众号"
                            value={listData?.mpAccountId}
                            showSearch
                            allowClear
                            disabled={(listData?.mpAccountIdIsNull === false || listData?.mpAccountIdIsNull === true)}
                            onChange={(e) => {
                                setListData({ ...listData, mpAccountId: e, mpAccountIdIsNull: undefined, pageNum: 1 })
                            }}
                            filterOption={(input: string, option: any) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                            options={getBindMpList?.data?.data?.map((item: any) => ({ label: item.name, value: item.id }))}
                        />
                        <Select
                            style={{ width: 200 }}
                            placeholder="是否新企微运营系统创建的群聊"
                            value={listData?.newCorpGroupChat}
                            showSearch
                            allowClear
                            onChange={(e) => {
                                setListData({ ...listData, newCorpGroupChat: e, pageNum: 1 })
                            }}
                            filterOption={(input: string, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                            options={[{ label: '否', value: false }, { label: '是', value: true }]}
                        />
                    </>
                </SearchBox>
                <div className={style.corpUserList_table} ref={ref}>
                    <Table
                        style={{ marginBottom: 1 }}
                        dataSource={getGroupChatList?.data?.data?.records}
                        loading={getGroupChatList?.loading}
                        columns={TableConfig(lockUsers, handleChatLog)}
                        scroll={{ y: size?.height && ref.current ? size?.height - ref.current.querySelector('.ant-table-thead').clientHeight : 300 }}
                        rowKey={'id'}
                        bordered
                        pagination={false}
                        size='small'
                        rowSelection={{
                            type: 'checkbox',
                            selectedRowKeys: editSelectedRow?.map(item => item.id),
                            getCheckboxProps: (record: any) => ({
                                name: record.name,
                            }),
                            onSelect: (record, selected) => {
                                if (selected) {
                                    setEditSelectedRow([...editSelectedRow, record])
                                } else {
                                    setEditSelectedRow(editSelectedRow?.filter(item => item.id !== record.id))
                                }
                            },
                            onSelectAll: (selected, rows, changeRows) => {
                                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}>
                    <Space size={40}>
                        <Title level={4} style={{ margin: 0 }}>群总数：{getGroupChatCount.data?.data?.groupChatCount || 0}</Title>
                        <Title level={4} style={{ margin: 0 }}>群成员总数：{getGroupChatCount.data?.data?.groupChatUserCount || 0}</Title>
                    </Space>
                </div>
                <div className={style.corpUserList_footer}>
                    <Pagination
                        size="small"
                        total={getGroupChatList?.data?.data?.total || 0}
                        showSizeChanger
                        showQuickJumper
                        pageSize={getGroupChatList?.data?.data?.size || 20}
                        current={getGroupChatList?.data?.data?.current || 1}
                        onChange={(page: number, pageSize: number) => {
                            ref.current?.scrollTo({ top: 0 })
                            setListData({ ...listData, pageNum: page, pageSize })
                        }}
                        showTotal={(total: number) => <span style={{ fontSize: 12 }}>共 {total} 条</span>}
                    />
                </div>
            </Card>
        </div>

        {/* 设置备注弹窗 */}
        {remarkVisible && <RemarkSet
            corpId={listData.corpId}
            listData={listData}
            editSelectedRow={editSelectedRow}
            visible={remarkVisible}
            onClose={() => {
                setRemarkVisible(false)
            }}
            onChange={() => {
                setEditSelectedRow([])
                setRemarkVisible(false)
                getGroupChatList.refresh()
            }}
        />}

        {/* 客户列表弹窗 */}
        <Drawer
            title={userData?.chatName + '--成员列表'}
            placement="right"
            width='80%'
            onClose={() => { setUserData(null) }}
            open={userData}
        >
            <UserContent userData={userData} />
        </Drawer>

        {/* 指派公众号 */}
        {zpVisible && <ZpMp
            corpId={listData.corpId}
            visible={zpVisible}
            onClose={() => setZpVisible(false)}
            editSelectedRow={editSelectedRow}
            onChange={() => {
                setEditSelectedRow([])
                setZpVisible(false)
                getGroupChatList.refresh()
            }}
        />}

        {/* 变更记录 */}
        {chatLogData?.visible && <ChatLog
            {...chatLogData}
            corpId={listData.corpId}
            onClose={() => setChatLogData(undefined)}
        />}
    </div>;
};

export default WeAssociationList;