import { Button, Card, Checkbox, Col, Row, Spin } from 'antd'
import Modal from 'antd/lib/modal/Modal'
import React, { useCallback, useEffect, useImperativeHandle, useState } from 'react'
import { useModel } from 'umi'
import Left from '@/components/ActionModal/left'
import style from './index.less'
import NoFoundPage from '@/pages/empty'
type Props = {
}
let SyncModal = React.forwardRef((props: Props, ref) => {
    //映射ref
    useImperativeHandle(ref, () => ({
        show
    }))
    const { mpAccounts, actionWX, dispatch, actionArr, getDataList, getAllOfMember } = useModel('useOperating.useWxGroupList',
        models => ({
            mpAccounts: models.state.mpAccounts,
            actionWX: models.state.actionWX,
            dispatch: models.dispatch,
            actionArr: models.state.actionArr,
            getDataList: models.getDataList,
            getAllOfMember: models.getAllOfMember
        }))
    const { sync } = useModel('useOperating.useBdMedia')
    const [visible, setVisible] = useState<boolean>(false)//显示隐藏
    const [groupSyncWx, setGroupSyncWx] = useState<any[]>([])//当前组未选中的微信
    const [selectState, setSelectState] = useState<{ isAll: boolean, isChecked: boolean }>({ isAll: false, isChecked: false })
    const [sysMediaId, setSysMediaId] = useState<any>()

    //全选
    let allSelect = useCallback(() => {
        let isGroupWx: any[] = []//选中的数据
        let newActionArr: any[] = []
        let fiterMp: any[] = []
        mpAccounts?.forEach((mp: { id: number, verifyTypeInfo: number }) => {
            if (mp?.verifyTypeInfo !== -1) {//过滤未认证
                fiterMp.push(mp)
            }
            actionArr?.forEach((wx: { id: number }) => {
                if (wx.id === mp.id) {
                    isGroupWx.push(wx)
                }
            })
        })
        if (isGroupWx?.length === fiterMp?.length || isGroupWx?.length === fiterMp?.length - groupSyncWx?.length) {//清空
            newActionArr = actionArr?.filter((wx: { id: number }) => {
                if (isGroupWx.every((groupwx: { id: number }) => wx.id !== groupwx.id)) {
                    return wx
                }
                return
            })
            setSelectState({ isAll: false, isChecked: false })
            dispatch({ type: 'setActionArr', params: { actionArr: newActionArr } })
        } else {//全选
            newActionArr = actionArr?.filter((wx: { id: number }) => {
                if (isGroupWx.every((groupwx: { id: number }) => wx.id !== groupwx.id)) {
                    return wx
                }
                return
            })
            newActionArr = [...newActionArr, ...fiterMp]
            setSelectState({ isAll: false, isChecked: true })
            dispatch({ type: 'setActionArr', params: { actionArr: newActionArr } })
        }
    }, [selectState, mpAccounts, actionArr, actionWX, groupSyncWx])
    //反选
    let returnSelct = useCallback(() => {
        let isGroupWx: any[] = []
        let returnWx: any[] = []
        let newActionArr: any[] = []
        let fiterMp: any[] = []
        mpAccounts?.forEach((mp: { id: number, verifyTypeInfo: number }) => {
            if (mp?.verifyTypeInfo !== -1) {//过滤未认证
                fiterMp.push(mp)
            }
            actionArr?.forEach((wx: { id: number }) => {
                if (wx.id === mp.id) {
                    isGroupWx.push(wx)
                }
            })
        })
        returnWx = fiterMp?.filter((mp: { id: number }) => {
            if (isGroupWx.every((wx: { id: number }) => mp.id !== wx.id)) {
                return mp
            }
            return
        })
        newActionArr = actionArr?.filter((wx: { id: number }) => {
            if (isGroupWx.every((groupwx: { id: number }) => wx.id !== groupwx.id)) {
                return wx
            }
            return
        })
        if (returnWx.length !== 0 && groupSyncWx.length !== returnWx.length) {//假如选中个数的大于0
            setSelectState({ isAll: true, isChecked: true })
        } else {//假如等于0
            setSelectState({ isAll: false, isChecked: false })
        }
        if (returnWx.length === fiterMp.length && groupSyncWx.length === 0) {
            setSelectState({ isAll: false, isChecked: true })//假如反选值与当前组的个数一样证明全选
        }
        newActionArr = [...newActionArr, ...returnWx]
        dispatch({ type: 'setActionArr', params: { actionArr: newActionArr } })
    }, [selectState, mpAccounts, actionArr, actionWX, groupSyncWx])
    //每次切换组检测全选状态
    useEffect(() => {
        let isGroupWx: any[] = []
        let groupSyncWx: any[] = []
        mpAccounts?.forEach((mp: { id: number }) => {
            actionArr?.forEach((wx: { id: number }) => {
                if (wx.id === mp.id) {
                    isGroupWx.push(wx)
                }
            })
        })
        setGroupSyncWx(groupSyncWx)
        // }
        if (isGroupWx?.length === mpAccounts?.length) {
            setSelectState({ isAll: false, isChecked: true })
        } else {
            setSelectState({ isAll: true, isChecked: true })
        }
        if (isGroupWx?.length === 0) {
            setSelectState({ isAll: false, isChecked: false })
        }
    }, [mpAccounts, actionArr])
    //弹窗传参接受
    let show = useCallback((param: { sysMediaId: number }) => {
        setSysMediaId(param?.sysMediaId)
        setVisible(true)
    }, [])
    //关闭弹窗
    let handleCancel = useCallback(() => {
        dispatch({ type: 'setActionArr', params: { actionArr: [] } })
        setVisible(false)
    }, [])
    //确定同步
    let handleOk = useCallback(() => {
        if (!actionWX) {
            return
        }
        let mpIds: any[] = []//新建同步
        actionArr?.forEach((item: any) => {//选中的微信号循环处理
            mpIds.push(item.id)
        })
        sync.run({ mpIds, sysMediaId: sysMediaId }).then((res: any) => {
            console.log(res)
            handleCancel()
        })
    }, [actionArr, sysMediaId])
    //选中事件
    let action = useCallback((item: any) => {
        let isGroupWx: any[] = []//选中的数据
        if (actionArr?.some((obj: { appid: number }) => obj.appid === item.appid)) {//删除
            let newArr = actionArr?.filter((obj: { appid: number }) => obj.appid !== item.appid)
            mpAccounts?.forEach((mp: { id: number }) => {
                newArr?.forEach((wx: { id: number }) => {
                    if (wx.id === mp.id) {
                        isGroupWx.push(wx)
                    }
                })
            })
            if (isGroupWx.length === 0) {//假如为空
                setSelectState({ isAll: false, isChecked: false })
            } else {
                setSelectState({ isAll: true, isChecked: true })
            }
            dispatch({ type: 'setActionArr', params: { actionArr: newArr } })
        } else {//添加
            let arr = [...actionArr, item]
            if (mpAccounts?.every((mp: { id: number }) => arr?.some((wx: { id: number }) => mp.id === wx.id))) {//假如全部存在全选
                setSelectState({ isAll: false, isChecked: true })
            } else {
                setSelectState({ isAll: true, isChecked: true })
            }
            dispatch({ type: 'setActionArr', params: { actionArr: arr } })
        }
    }, [actionArr, mpAccounts])
    useEffect(() => {
        let newArr: any[] = []
        if (getDataList?.data) {
            getDataList?.data?.forEach((data: { mpAccounts: any }) => {
                if(data?.mpAccounts){
                    newArr = [...data?.mpAccounts]
                }
            })
        }
        if (getAllOfMember?.data) {
            getAllOfMember?.data?.forEach((data: { userMpAccounts: any }) => {
                data?.userMpAccounts?.forEach((mp: { id: number }) => {
                    if (newArr.every((arr: { id: number }) => mp?.id !== arr.id)) {
                        newArr.push(mp)
                    }
                })
            })
        }
    }, [getDataList?.data, getAllOfMember?.data,])
    //配合左侧搜索改变公众号帮助选中
    useEffect(() => {
        if (actionWX) {
            action(actionWX)
        }
    }, [actionWX])
    return <>
        <Modal
            title="选择公众号同步"
            width={1040}
            open={visible}
            onOk={handleOk}
            onCancel={handleCancel}
            okText='确定'
            cancelText='取消'
            destroyOnClose
            confirmLoading={sync?.loading}
        >
            <Spin tip='Loading...同步素材较慢，请耐心等待，可关闭窗口不影响其他操作' spinning={sync?.loading}
            >
                {
                    actionWX ? <Row className={style.colud}  >
                        <Col >
                            <Left />
                        </Col>
                        <Col>
                            <Card
                                style={{ height: '420px', overflow: 'hidden', minWidth: 290 }}
                                title={
                                    <>
                                        <span style={{ marginRight: 10 }}>组下成员</span>
                                        <Checkbox
                                            indeterminate={selectState.isAll}
                                            onChange={allSelect}
                                            checked={selectState.isChecked}
                                        >
                                            <span style={{ fontSize: 12, color: '#999' }}>全选</span>
                                        </Checkbox>
                                        <Button size='small' onClick={returnSelct}>反选</Button>
                                    </>
                                }
                                bodyStyle={{ height: 350, overflowY: 'auto' }}
                            >
                                <Checkbox.Group style={{ width: '100%', }} >
                                    <Row gutter={[10, 0]}>
                                        {

                                            mpAccounts?.map((item: any) => {
                                                let isAction: any = actionArr?.some((obj: any) => obj?.appid === item?.appid)
                                                return <Col key={item.id} span={24}>
                                                    <Checkbox value={item} className={style.box} onClick={() => action(item)} >
                                                        <div
                                                            className={`${isAction ? style.card_action : undefined} ${style.card_box}`}
                                                        >
                                                            <div
                                                                style={{ display: 'flex', alignItems: 'center' }} /**data?.syncVo?.some((obj:{appId:string}) => obj.appId === item.appid) ? {} :  */
                                                            // description="This is the description"
                                                            >
                                                                <img src={item?.headImg || localStorage?.bookImg} className={style.item_img} />
                                                                {item.nickName}
                                                            </div>
                                                        </div>
                                                    </Checkbox>
                                                </Col>
                                            })
                                        }
                                    </Row>
                                </Checkbox.Group>
                            </Card>
                        </Col>
                        <Col>
                            <Card
                                style={{ height: 420, overflow: 'hidden', minWidth: 280 }}
                                title={
                                    <>
                                        <span style={{ marginRight: 10 }}>已勾选</span>
                                        <Button size='small' onClick={() => { dispatch({ type: 'setActionArr', params: { actionArr: [] } }) }}>清空</Button>
                                    </>
                                }
                                bodyStyle={{ height: 350, overflowY: 'auto' }}
                            >
                                <Checkbox.Group style={{ width: '100%' }} >
                                    <Row gutter={[10, 0]}>
                                        {

                                            actionArr?.map((item: any) => {
                                                let isAction: any = actionArr?.some((obj: any) => obj?.appid === item?.appid)
                                                return <Col key={item.id}>
                                                    <Checkbox value={item} className={style.box} onClick={() => action(item)}>
                                                        <div
                                                            className={`${isAction ? style.card_action : undefined} ${style.card_box}`}
                                                        >
                                                            <div
                                                                style={{ display: 'flex', alignItems: 'center' }} /**data?.syncVo?.some((obj:{appId:string}) => obj.appId === item.appid) ? {} :  */
                                                            // description="This is the description"
                                                            >
                                                                <img src={item?.headImg || localStorage?.bookImg} className={style.item_img} />
                                                                {item.nickName}
                                                            </div>
                                                        </div>
                                                    </Checkbox>
                                                </Col>
                                            })
                                        }
                                    </Row>
                                </Checkbox.Group>
                            </Card>
                        </Col>
                    </Row> : <NoFoundPage />
                }
            </Spin>
        </Modal >
    </>
})

export default SyncModal