import { App, Button, Card, Input, Pagination, Select, Table, Tabs } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { MenuUnfoldOutlined, MenuFoldOutlined, PlusOutlined, SearchOutlined, UsergroupAddOutlined } from '@ant-design/icons';
import style from './index.less'
import GroupLeft from './groupLeft';
import TeamMembers from '@/components/Team/teamMembers';
import { getAdAccountAllOfMember } from '../../API/global';
import { useAjax } from '@/Hook/useAjax';
import { delAccountToGroupApi, getCorpUserApi } from '../../API/corpUserManage';
import SearchBox from '../../components/searchBox';
import { WeTableConfig } from './tableConfig';
import { useSize } from 'ahooks';
import { getBindMpListApi } from '../../API/corpUserAssign';
import SettingsGroup from './settingsGroup';

/**
 * 企微号管理
 * @returns 
 */
const CorpUserManage: React.FC = () => {

    /***************************************************/
    const { message } = App.useApp();
    const ref = useRef<HTMLDivElement>(null)
    const size = useSize(ref)
    const [queryForm, setQueryForm] = useState<CORP_USER_ASSIGN_API.GetCorpUserProps>({ pageNum: 1, pageSize: 20 })
    const [queryFormNew, setQueryFormNew] = useState<CORP_USER_ASSIGN_API.GetCorpUserProps>({ pageNum: 1, pageSize: 20 })
    const [activeKey, setActiveKey] = useState<string>('1')
    const [showLeft, setShowLeft] = useState<boolean>(false)
    const [selectedRows, setselectedRows] = useState<any[]>([])
    const [settingsGroupData, setSettingsGroupData] = useState<{ visible?: boolean, type: 'add' | 'del', data: any[] }>();

    const allOfMember = useAjax(() => getAdAccountAllOfMember())
    const getBindMpList = useAjax(() => getBindMpListApi())
    const getCorpUser = useAjax((params) => getCorpUserApi(params))
    const delAccountToGroup = useAjax((params) => delAccountToGroupApi(params))
    /***************************************************/

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

    useEffect(() => {
        const params = { ...queryForm }
        if (params?.corpIds) {
            params.corpIds = (params.corpIds as any).split(/[\s,，\n]/).filter((item: string) => item)
        } else {
            delete params?.corpIds
        }
        if (params?.corpUserIds) {
            params.corpUserIds = (params.corpUserIds as any).split(/[\s,，\n]/).filter((item: string) => item)
        } else {
            delete params?.corpUserIds
        }
        getCorpUser.run(params)
    }, [queryForm])

    const delHandle = (groupId: number, data: any) => {
        delAccountToGroup.run({ currGroupId: groupId, corpUserList: [{ corpId: data.corpId, corpUserId: data.corpUserId }] }).then(res => {
            message.success('移出成功')
            getCorpUser.refresh()
        })
    }

    return <div className={style.corpUserManage}>
        <Tabs
            tabBarStyle={{ marginBottom: 1 }}
            activeKey={activeKey}
            type="card"
            onChange={(activeKey) => {
                if (activeKey !== 'contract') {
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    delete newQueryForm?.groupId
                    delete newQueryForm?.putUserId
                    setQueryForm(newQueryForm)
                    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 === '1' && <GroupLeft
                onChange={(groupId) => {
                    setQueryForm({ ...queryForm, groupId, pageNum: 1 })
                    setQueryFormNew({ ...queryFormNew, groupId, pageNum: 1 })
                }} value={queryForm?.groupId} />}
            {!showLeft && activeKey === '2' && <TeamMembers
                allOfMember={allOfMember}
                onChange={(putUserId) => {
                    setQueryForm({ ...queryForm, putUserId, pageNum: 1 })
                    setQueryFormNew({ ...queryFormNew, putUserId, pageNum: 1 })
                }}
                value={queryForm?.putUserId}
            />}
            <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={() => {
                            setQueryForm({ ...queryFormNew, pageNum: 1 })
                        }} loading={getCorpUser.loading} icon={<SearchOutlined />}>搜索</Button>
                        <Button type="primary" disabled={selectedRows?.length === 0} onClick={() => { setSettingsGroupData({ visible: true, data: selectedRows, type: 'add' }) }} icon={<UsergroupAddOutlined />}>添加到分组</Button>
                        <Button type="primary" danger disabled={selectedRows?.length === 0} onClick={() => { setSettingsGroupData({ visible: true, data: selectedRows, type: 'del' }) }} icon={<UsergroupAddOutlined />}>移除分组</Button>
                    </>}
                >
                    <>
                        <Input onChange={(e) => setQueryFormNew({ ...queryFormNew, corpIds: e.target.value as any })} value={queryFormNew?.corpIds} placeholder="企微ID（多个，,空格换行）" allowClear />
                        <Input onChange={(e) => setQueryFormNew({ ...queryFormNew, corpUserName: e.target.value as any })} value={queryFormNew?.corpUserName} placeholder="客服号名称" allowClear />
                        <Input onChange={(e) => setQueryFormNew({ ...queryFormNew, corpUserIds: e.target.value as any })} value={queryFormNew?.corpUserIds} placeholder="客服ID（多个，,空格换行）" allowClear />
                        <Select
                            value={queryFormNew?.operUserId}
                            onChange={(e) => setQueryFormNew({ ...queryFormNew, operUserId: e })}
                            showSearch
                            style={{ width: 110 }}
                            placeholder="运营"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            allowClear
                            options={allOfMember?.data?.data?.map((item: any) => ({ label: item.nickname, value: item.userId }))}
                        />
                        <Select
                            value={queryFormNew?.mpAccountId}
                            onChange={(e) => setQueryFormNew({ ...queryFormNew, mpAccountId: e })}
                            showSearch
                            style={{ width: 110 }}
                            placeholder="公众号"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            allowClear
                            options={getBindMpList?.data?.data?.map((item: any) => ({ label: item.name, value: item.id }))}
                        />
                        <Select
                            value={queryFormNew?.groupOwner}
                            onChange={(e) => setQueryFormNew({ ...queryFormNew, groupOwner: e })}
                            showSearch
                            style={{ width: 100 }}
                            placeholder="是否群主号"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            allowClear
                            options={[{ label: '是', value: 1 }, { label: '否', value: 0 }]}
                        />
                        <Select
                            value={queryFormNew?.machine}
                            onChange={(e) => setQueryFormNew({ ...queryFormNew, machine: e })}
                            showSearch
                            style={{ width: 100 }}
                            placeholder="是否机器号"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            allowClear
                            options={[{ label: '是', value: 1 }, { label: '否', value: 0 }]}
                        />
                        <Select
                            value={queryFormNew?.status}
                            onChange={(e) => setQueryFormNew({ ...queryFormNew, status: e })}
                            showSearch
                            style={{ width: 100 }}
                            placeholder="状态"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            allowClear
                            options={[{ label: '可用', value: 1 }, { label: '禁用', value: 0 }]}
                        />
                        <Select
                            value={queryFormNew?.stopUse}
                            onChange={(e) => setQueryFormNew({ ...queryFormNew, stopUse: e })}
                            showSearch
                            style={{ width: 100 }}
                            placeholder="是否停用"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            allowClear
                            options={[{ label: '可用', value: false }, { label: '停用', value: true }]}
                        />
                    </>
                </SearchBox>

                <div className={style.corpUserList_table} ref={ref}>
                    <Table
                        dataSource={getCorpUser?.data?.data?.records}
                        columns={WeTableConfig(activeKey, queryForm?.groupId, () => getCorpUser.refresh(), delHandle)}
                        bordered
                        pagination={false}
                        rowKey={'id'}
                        loading={getCorpUser?.loading}
                        scroll={{ y: size?.height && ref.current ? size?.height - ref.current.querySelector('.ant-table-thead').clientHeight : 300 }}
                        rowSelection={{
                            selectedRowKeys: selectedRows?.map((item: any) => item?.id),
                            onSelect: (record: { id: string }, selected: boolean) => {
                                let newData = JSON.parse(JSON.stringify(selectedRows))
                                if (selected) {
                                    newData.push({ ...record })
                                } else {
                                    newData = newData.filter((item: { id: string }) => item.id !== record.id)
                                }
                                setselectedRows(newData)
                            },
                            onSelectAll: (selected: boolean, _: { id: string }[], changeRows: { id: string }[]) => {
                                let newData = JSON.parse(JSON.stringify(selectedRows || '[]'))
                                if (selected) {
                                    changeRows.forEach((item: { id: string }) => {
                                        const index = newData.findIndex((ite: { id: string }) => ite.id === item.id)
                                        if (index === -1) {
                                            newData.push(item)
                                        }
                                    })
                                } else {
                                    const newSelectAccData = newData.filter((item: { id: string }) => {
                                        const index = changeRows.findIndex((ite: { id: string }) => ite.id === item.id)
                                        if (index !== -1) {
                                            return false
                                        } else {
                                            return true
                                        }
                                    })
                                    newData = newSelectAccData
                                }
                                setselectedRows(newData)
                            }
                        }}
                    />
                </div>

                <div className={style.corpUserList_footer}>
                    <Pagination
                        size="small"
                        total={getCorpUser?.data?.data?.total || 0}
                        showSizeChanger
                        showQuickJumper
                        pageSize={getCorpUser?.data?.data?.size || 20}
                        current={getCorpUser?.data?.data?.current || 1}
                        onChange={(page: number, pageSize: number) => {
                            // ref.current?.scrollTo({ top: 0 })
                            setTimeout(() => {
                                setQueryForm({ ...queryForm, pageNum: page, pageSize })
                                setQueryFormNew({ ...queryFormNew, pageNum: page, pageSize })
                            }, 50)
                        }}
                        showTotal={(total: number) => <span style={{ fontSize: 12 }}>共 {total} 条</span>}
                    />
                </div>
            </Card>
        </div>

        {/* 设置分组 */}
        {settingsGroupData?.visible && <SettingsGroup
            {...settingsGroupData}
            onClose={() => setSettingsGroupData(undefined)}
            onChange={() => {
                getCorpUser.refresh();
                setSettingsGroupData(undefined)
                setselectedRows([])
            }}
        />}
    </div>
};

export default CorpUserManage;