import Tables from "@/components/Tables";
import { DeleteOutlined, FormOutlined, MenuFoldOutlined, MenuUnfoldOutlined, PlusOutlined, SearchOutlined } from "@ant-design/icons";
import { Button, Card, Checkbox, Divider, Form, Input, message, Modal, Popconfirm, Radio, Select, Space, Spin, Tabs } from "antd";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { useModel } from "umi";
import './index.less'
import columns from './tableConfig'
import { AccountListProps } from '@/services/launch/adMonitor'
import { CheckboxChangeEvent } from "antd/lib/checkbox";

/**
 * 监控数据源
 * @returns 
 */
function MonitorDataSource() {

    const { addEditGroup, getAdGroupList, deleteAdGroup, getAccountList, addDelAccount } = useModel('useLaunch.useMonitor')
    // 变量开始
    const { state } = useModel('useOperating.useWxGroupList')
    const [tab, setTab] = useState<string>('monitor')  // tab切换
    const [leftShow, setLeftShow] = useState<boolean>(true)  // 左边展示隐藏
    const [isNewGrouping, setIsNewGrouping] = useState<boolean>(false);  // 是否新增分组
    const inputRef = useRef<any>(null);
    const [addVisible, setAddVisible] = useState<boolean>(false)  // 添加分组
    const [queryForm, setQueryForm] = useState<AccountListProps>({ pageNum: 1, pageSize: 20 })
    const [pichers, setPichers] = useState<any[]>([]) // 投手数据
    const [datas, setDatas] = useState<any[]>([])  // 所有数据
    const [mpDatas, setMpDatas] = useState<any[]>([]) // 公众号
    const [mpDatasB, setMpDatasB] = useState<any[]>([]) // 备份公众号
    const [groupData, setGroupData] = useState<{ groupName: string, remark?: string, id?: number }>({ groupName: '' }) // 分组添加
    const [selectAccData, setSelectAccData] = useState<{ id: number, mpName: string }[]>([])  // 选中
    const [addDelData, setAddDelData] = useState<{ accountIdList: number[], groupId: number | undefined, type: 0 | 1 }>({ accountIdList: [], groupId: undefined, type: 1 })
    const [indeterminate, setIndeterminate] = useState<boolean>(false)
    const [checkAll, setCheckAll] = useState<boolean>(true)
    const { pitcherIdList, groupId = 0, pageNum, pageSize, mpAppIdList } = queryForm
    // 变量结束

    const clickHandle = (e: any) => {
        if (isNewGrouping || groupData?.id) {
            let className = e.target.getAttribute('class')
            let parentNode = e.target?.parentNode
            let pnClassName: any = null
            if (parentNode) {
                pnClassName = parentNode?.getAttribute('class')
            }
            if ((className && className?.indexOf('stop') !== -1) || (pnClassName && pnClassName?.indexOf('stop') !== -1)) {
                return
            }
            setIsNewGrouping(() => false)
            setGroupData(() => ({ groupName: '' }))
        }
    }
    useEffect(() => {
        document.body.addEventListener('click', clickHandle, false)
        return () => {
            document.body.removeEventListener('click', clickHandle, false)
        }
    }, [isNewGrouping, groupData])

    // 首次获取分组
    useEffect(() => {
        getGroup()
    }, [])
    // 首次获取列表
    useEffect(() => {
        if (pichers.length > 0) {
            getList()
        }
    }, [pichers, pageNum, pageSize, groupId])

    // 点击新增处理聚焦
    useEffect(() => {
        if (isNewGrouping && inputRef?.current) {
            inputRef.current!.focus({
                cursor: 'end',
            });
        }
    }, [inputRef, isNewGrouping])

    useEffect(() => {
        if (state?.allOfMember?.length > 0) {//组长数据存在使用组长数据
            setDatas(state?.allOfMember)
        } else if (state?.myallOfUser?.length > 0) {//否则个人
            setDatas(state?.myallOfUser)
        }
    }, [state])
    // 处理公众号
    useEffect(() => {
        if (datas.length > 0) {
            let new_pichers = datas?.map((item: { key: { nickName: string, userId: number } }) => ({ nickName: item.key.nickName, userId: item.key.userId }))
            if (JSON.stringify(pichers) !== JSON.stringify(new_pichers)) {//避免重复设置触发条件多次请求接口
                setPichers(new_pichers)
            }
            if (pitcherIdList && pitcherIdList?.length > 0) {
                let arr: any = []
                pitcherIdList?.forEach((pitcherId: any) => {
                    let data = datas?.find((item: { key: any }) => item.key.userId == pitcherId)
                    arr.push(data)
                })
                if (arr?.length > 0) {
                    setMpDatas(arr)
                    setMpDatasB(arr)
                }
            } else {
                setMpDatas(datas)
                setMpDatasB(datas)
            }
            // select()//首次搜索数据
        }
    }, [datas, pitcherIdList, pichers])

    /**分页 */
    const pageChange = useCallback((page: string | number, pageSize?: string | number) => {
        setQueryForm({ ...queryForm, pageNum: page as number, pageSize: pageSize as number })
    }, [queryForm])

    // 获取列表
    const getList = useCallback(() => {
        let newQueryForm = { pageNum, pageSize, groupId, mpAppIdList, pitcherIdList }
        if (groupId === 0 && (!newQueryForm['pitcherIdList'] || newQueryForm['pitcherIdList']?.length === 0) && (!queryForm['mpAppIdList'] || queryForm['mpAppIdList']?.length === 0)) {
            newQueryForm['pitcherIdList'] = pichers?.map(item => item.userId)
        }
        getAccountList.run(newQueryForm)
    }, [pageNum, pageSize, groupId, pichers, mpAppIdList, pitcherIdList])

    // 获取分组
    const getGroup = () => {
        getAdGroupList.run()
    }
    // 新增修改分组
    const addEditHandle = useCallback(() => {
        if (groupData?.groupName) {
            addEditGroup.run(groupData).then((res: any) => {
                if (res?.data) {
                    message.success(groupData?.id ? '修改成功' : '添加成功')
                    setGroupData({ groupName: '' })
                    setIsNewGrouping(false)
                    getGroup()
                }
            })
        } else {
            message.error('请填写分组名称')
        }
    }, [groupData, isNewGrouping])
    // 删除分组
    const delGroup = (id: number) => {
        deleteAdGroup.run({ id }).then((res: any) => {
            if (res?.data) {
                message.success('删除成功');
                getGroup();
            }
        })
    }

    // 新增至分组按钮
    const restoreDefault = () => {
        setAddDelData(() => ({ ...addDelData, accountIdList: selectAccData?.map((item: { id: number }) => item.id), type: 1 }));
        setAddVisible(true);
        setCheckAll(true);
        setIndeterminate(false);
    }
    // 移除出分组
    const delAccHandle = () => {
        if (selectAccData?.length === 0) {
            message.error('请选择公众号')
            return
        }
        addDelAccount.run({ ...addDelData, accountIdList: selectAccData?.map((item: { id: number }) => item.id), type: 0, groupId: groupId }).then((res: any) => {
            if (res?.code === 200) {
                message.success(`移除分组成功`);
                setSelectAccData([])
                setAddDelData({ accountIdList: [], groupId: undefined, type: 1 })
                getList()
            }
        })
    }
    // 全选触发
    const onCheckAllChange = (e: CheckboxChangeEvent) => {
        setIndeterminate(false);
        setCheckAll(e.target.checked);
        setAddDelData({ ...addDelData, accountIdList: e.target.checked ? selectAccData?.map((item: { id: number }) => item.id) : [] })
    }
    // 单个选中触发
    const checkboxOnChange = (checkedValue: any[]) => {
        setAddDelData({ ...addDelData, accountIdList: checkedValue?.map((item: number) => item) })
        setIndeterminate(!!checkedValue.length && checkedValue.length < selectAccData.length);
        setCheckAll(checkedValue.length === selectAccData.length);
    }
    // 分配移除
    const addDelAccHandle = useCallback(() => {
        // addDelAccount
        if (addDelData.type === 1 && !addDelData?.groupId) {
            message.error('请选择分组')
            return
        }
        if (addDelData?.accountIdList?.length === 0) {
            message.error('请选择公众号')
            return
        }
        addDelAccount.run(addDelData).then((res: any) => {
            if (addDelData.type === 1) {
                let count = addDelData?.accountIdList?.length || 0
                let succ = res?.data || 0
                message.success(`添加成功，总提交数：${count}，成功：${succ}，重复：${count - succ}`);
            } else {

            }
            setAddVisible(false);
            setSelectAccData([])
            setAddDelData({ accountIdList: [], groupId: undefined, type: 1 })
        })
    }, [addDelData, addVisible, selectAccData])

    return <div className="dataSource">
        <Tabs activeKey={tab} className="adMonitorListTab" type="card" size="small" onChange={(activeKey: string) => {
            setLeftShow(!leftShow)
            setTab(activeKey)
        }}>
            <Tabs.TabPane tab={leftShow ? <MenuFoldOutlined /> : <MenuUnfoldOutlined />} key="monitor" />
        </Tabs>
        <div className="source">
            {leftShow && <div className="left">
                <div className="header">
                    <div>全部分组</div>
                    <Button type="link" icon={<PlusOutlined />} className="stop" onClick={(e) => {
                        e.stopPropagation()
                        setIsNewGrouping(true)
                    }}>新增分组</Button>
                </div>
                <div className="content">
                    {isNewGrouping && <div className="item">
                        <div className="edit stop">
                            <Space direction="vertical" className="stop">
                                <Space className="stop">
                                    <div style={{ width: 70 }} className="stop">分组名称：</div>
                                    <Input placeholder="请输入分组名称（最多10个字）" className="stop" maxLength={10} ref={inputRef} onChange={(e) => { setGroupData({ ...groupData, groupName: e.target.value }) }} value={groupData?.groupName} />
                                </Space>
                                <Space className="stop">
                                    <div style={{ width: 70 }} className="stop">分组备注：</div>
                                    <Input placeholder="请输入分组备注（最多10个字）" className="stop" maxLength={10} onChange={(e) => { setGroupData({ ...groupData, remark: e.target.value }) }} value={groupData?.remark} />
                                </Space>
                                <div style={{ display: 'flex', justifyContent: 'flex-end' }} className="stop">
                                    <Space className="stop">
                                        <Button size="small" className="stop" onClick={() => { setIsNewGrouping(false); setGroupData({ groupName: '' }) }}>取消</Button>
                                        <Button type="primary" className="stop" size="small" onClick={addEditHandle} loading={addEditGroup?.loading}>确定</Button>
                                    </Space>
                                </div>
                            </Space>
                        </div>
                    </div>}

                    <Spin spinning={getAdGroupList.loading}>
                        <div className="item">
                            <div className={`con ${groupId === 0 ? 'select' : ''}`} onClick={() => { setQueryForm({ ...queryForm, groupId: 0 }); setSelectAccData([]) }}>
                                <div className="left">
                                    <div className="title">默认分组</div>
                                </div>
                            </div>
                        </div>
                        {getAdGroupList?.data?.data?.map((item: { groupName: string, id: number, remark?: string }, index: number) => <div className="item" key={item.id || index}>
                            {groupData?.id && groupData?.id === item?.id ? <div className="edit stop">
                                <Space direction="vertical" className="stop">
                                    <Space className="stop">
                                        <div style={{ width: 70 }} className="stop">分组名称：</div>
                                        <Input placeholder="请输入分组名称（最多10个字）" className="stop" maxLength={10} ref={inputRef} onChange={(e) => { setGroupData({ ...groupData, groupName: e.target.value }) }} value={groupData?.groupName} />
                                    </Space>
                                    <Space className="stop">
                                        <div style={{ width: 70 }} className="stop">分组备注：</div>
                                        <Input placeholder="请输入分组备注（最多10个字）" className="stop" maxLength={10} onChange={(e) => { setGroupData({ ...groupData, remark: e.target.value }) }} value={groupData?.remark} />
                                    </Space>
                                    <div style={{ display: 'flex', justifyContent: 'flex-end' }} className="stop">
                                        <Space className="stop">
                                            <Button size="small" className="stop" onClick={() => { setIsNewGrouping(false); setGroupData({ groupName: '' }) }}>取消</Button>
                                            <Button type="primary" className="stop" size="small" onClick={addEditHandle} loading={addEditGroup?.loading}>修改</Button>
                                        </Space>
                                    </div>
                                </Space>
                            </div> : <div className={`con ${groupId === item.id ? 'select' : ''}`} onClick={() => { setQueryForm({ ...queryForm, groupId: item.id, pageNum: 1 }); setSelectAccData([]) }} key={item.id || index}>
                                <div className="left">
                                    <div className="title">{item.groupName}</div>
                                    {item?.remark && <div className="subTitle">{item?.remark}</div>}
                                </div>
                                <div className="right">
                                    <Space>
                                        <FormOutlined onClick={(e) => { e.stopPropagation(); setGroupData({ ...item }) }} />
                                        <Popconfirm
                                            title="确定删除?"
                                            onConfirm={() => { delGroup(item.id) }}
                                            okText="确定"
                                            cancelText="取消"
                                        >
                                            <DeleteOutlined style={{ color: 'red' }} />
                                        </Popconfirm>
                                    </Space>
                                </div>
                            </div>}

                        </div>)}
                    </Spin>
                </div>
            </div>}
            <div className="right" style={leftShow ? {} : { width: '100%' }}>
                <div className="mySpace">
                    <div className="top">
                        <Card>
                            <Space>
                                <Radio.Group defaultValue="a" buttonStyle="solid">
                                    <Radio.Button value="a">MP</Radio.Button>
                                    <Radio.Button value="b" disabled>GDT</Radio.Button>
                                </Radio.Group>
                                <Select
                                    showSearch
                                    value={queryForm?.pitcherIdList}
                                    style={{ minWidth: 180 }}
                                    mode='multiple'
                                    maxTagCount={1}
                                    disabled={queryForm?.mpAppIdList && queryForm?.mpAppIdList?.length > 0}
                                    allowClear placeholder="请选择投手"
                                    onChange={(value: string[]) => { setQueryForm({ ...queryForm, pitcherIdList: value, pageNum: 1 }) }}
                                    filterOption={(input, option) =>
                                        option?.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {pichers?.map((item: { nickName: string, userId: number }, index: number) =>
                                        <Select.Option
                                            value={item.userId}
                                            key={item.userId + '' + index}
                                        >
                                            {item.nickName}
                                        </Select.Option>
                                    )}
                                </Select>
                                <Select
                                    showSearch
                                    mode='multiple'
                                    maxTagCount={1}
                                    value={queryForm?.mpAppIdList}
                                    onBlur={() => {
                                        setMpDatas(mpDatasB)
                                    }}
                                    onSearch={(value: string) => {
                                        if (value) {
                                            let arr: any = []
                                            mpDatas.forEach((item: { key: { userId: string, nickName: string }, value: any[] }) => {
                                                let i: any = { key: item.key, value: [] }
                                                item?.value?.forEach(v => {
                                                    if (v?.nickName?.includes(value)) {
                                                        i.value.push(v)
                                                    }
                                                })
                                                if (i.value.length > 0) {
                                                    arr.push(i)
                                                }
                                            })
                                            if (arr.length > 0 && JSON.stringify(mpDatas) !== JSON.stringify(arr)) {
                                                setMpDatas(arr)
                                            }
                                        } else {
                                            setMpDatas(mpDatasB)
                                        }
                                    }}
                                    filterOption={(input, option) => {
                                        return true
                                    }
                                    }
                                    style={{ minWidth: 220 }} allowClear placeholder="请选择公众号"
                                    onChange={(value: string[]) => {
                                        setQueryForm({ ...queryForm, mpAppIdList: value, pageNum: 1 })
                                    }}
                                >
                                    {mpDatas?.map((item: { key: { userId: string, nickName: string }, value: any[] }, index: number) => {
                                        if (item?.value?.length > 0) {
                                            return <Select.OptGroup key={item?.key?.userId} label={item?.key?.nickName}>
                                                {
                                                    item?.value?.map((value: any) => {
                                                        if (value.nickName && !value.nickName.includes('注销')) {
                                                            return <Select.Option
                                                                value={value.appid}
                                                                key={value.appid + '' + index}
                                                            >
                                                                {value.nickName}
                                                            </Select.Option>
                                                        }
                                                        return null
                                                    })
                                                }
                                            </Select.OptGroup>
                                        }
                                        return null
                                    })}
                                </Select>
                                <Button type="primary" icon={<SearchOutlined />} onClick={getList}>搜索</Button>
                                {groupId === 0 ?
                                    <Button type="primary" icon={<PlusOutlined />} disabled={selectAccData.length === 0} onClick={() => { restoreDefault() }}>新增至分组</Button> :
                                    <Popconfirm
                                        title="确定从分组中移除?"
                                        onConfirm={() => { delAccHandle() }}
                                        okText="确定"
                                        cancelText="取消"
                                    >
                                        <Button type="primary" icon={<DeleteOutlined />} danger disabled={selectAccData.length === 0}>从分组中移除</Button>
                                    </Popconfirm>}
                            </Space>
                        </Card>
                    </div>
                    <div className="bottom">
                        <Card>
                            <Tables
                                columns={columns()}
                                dataSource={getAccountList?.data?.data?.records}
                                total={getAccountList?.data?.data?.total || 0}
                                pageChange={pageChange}
                                sizeChange={pageChange}
                                current={queryForm.pageNum}
                                size="small"
                                loading={getAccountList.loading}
                                scroll={{ x: 1000, y: 622 }}
                                bordered
                                rowClassName={(record: any) => {
                                    if (record?.status === 1) {
                                        return 'error'
                                    } else {
                                        return ""
                                    }
                                }}
                                rowSelection={{
                                    selectedRowKeys: selectAccData?.map((item: any) => item.id?.toString()),
                                    onSelect: (record: { id: number, mpName: string }, selected: boolean) => {
                                        if (selected) {
                                            selectAccData.push({ ...record })
                                            setSelectAccData([...selectAccData])
                                        } else {
                                            let newSelectAccData = selectAccData.filter((item: { id: number, mpName: string }) => item.id !== record.id)
                                            setSelectAccData([...newSelectAccData])
                                        }
                                    },
                                    onSelectAll: (selected: boolean, selectedRows: { id: number, mpName: string }[], changeRows: { id: number, mpName: string }[]) => {
                                        if (selected) {
                                            let newSelectAccData = [...selectAccData]
                                            changeRows.forEach((item: { id: number, mpName: string }) => {
                                                let index = newSelectAccData.findIndex((ite: { id: number, mpName: string }) => ite.id === item.id)
                                                if (index === -1) {
                                                    newSelectAccData.push({ ...item })
                                                }
                                            })
                                            setSelectAccData([...newSelectAccData])
                                        } else {
                                            let newSelectAccData = selectAccData.filter((item: { id: number, mpName: string }) => {
                                                let index = changeRows.findIndex((ite: { id: number, mpName: string }) => ite.id === item.id)
                                                if (index !== -1) {
                                                    return false
                                                } else {
                                                    return true
                                                }
                                            })
                                            setSelectAccData([...newSelectAccData])
                                        }
                                    }
                                }}
                            />
                        </Card>
                    </div>
                </div>
            </div>
        </div>

        {/* 新增分组 */}
        <Modal title="添加到分组" visible={addVisible} onOk={addDelAccHandle} onCancel={() => { setAddVisible(false) }} width={540} confirmLoading={addDelAccount.loading}>
            <Form labelCol={{ span: 4.5 }}>
                <Form.Item label="公众号分组">
                    <Select placeholder="请选择分组" value={addDelData.groupId} onChange={(value: number) => { setAddDelData({ ...addDelData, groupId: value }) }} allowClear>
                        {getAdGroupList?.data?.data?.map((item: { groupName: string, id: number, remark?: string }, index: number) => <Select.Option value={item.id} key={item.id || index}>{item.groupName}</Select.Option>)}
                    </Select>
                </Form.Item>
                {/* <Form.Item label="分组备注">
                    <Input />
                </Form.Item> */}
                <Form.Item label="已选公众号">
                    <div className="alreadyAcc">
                        <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>全选</Checkbox>
                        <Divider style={{ margin: '5px 0 10px' }} />
                        <Checkbox.Group value={addDelData?.accountIdList} onChange={checkboxOnChange} className="myCheck">
                            {selectAccData?.map((item: { id: number, mpName: string }) => <Checkbox key={item.id} value={item.id}>{item.mpName}</Checkbox>)}
                        </Checkbox.Group>
                    </div>
                </Form.Item>
            </Form>
        </Modal>
    </div>
}

export default React.memo(MonitorDataSource)