import { Button, message, Modal, Space, Transfer } from "antd"
import { TransferDirection } from "antd/es/transfer"
import React, { useCallback, useEffect, useState } from "react"
import { useModel } from "umi"
import PupCode from "../../weChat/components/createPlan/components/PupCode"
import style from './index.less'

interface CustomSelectProps {
    btText?: string,
    onChange?: (value: any) => void,
    defaultValue?: any,
}
let timer: NodeJS.Timeout | undefined = undefined
function CustomSelect(props: CustomSelectProps) {
    let { btText = '选择投放号', onChange, defaultValue } = props
    const { getAcc, getScanStatus, refreshData } = useModel('useLaunch.useWeChat')
    const [isModalVisible, setIsModalVisible] = useState<boolean>(false)  // 弹窗控制
    const [data, setData] = useState<any[]>([])  // 选择的数据
    const [open, setOpen] = useState<boolean>(false)  // 控制是否展开
    const [codeImg, setCodeImg] = useState<string>('') // 二维码
    const [visible, setVisible] = useState<boolean>(false)  // 控制二维码弹窗
    const currentUser = useModel('@@initialState', model => model.initialState?.currentUser)
    /** 穿梭框start */
    const [oneWay, setOneWay] = useState<boolean>(false);
    const [mockData, setMockData] = useState<any[]>([]);
    const [targetKeys, setTargetKeys] = useState<string[]>([]);
    const onChangeTransfer = (newTargetKeys: string[], direction: TransferDirection, moveKeys: string[]) => {
        console.log(newTargetKeys, direction, moveKeys);
        setTargetKeys(newTargetKeys);
    };
    /** 穿梭框end */

    useEffect(() => {
        if (isModalVisible) {
            getAcc.run().then((res: any) => {
                if (res?.msg === "SUCCESS") {
                    let { data } = res
                    const newMockData = data?.map((item: any, index: number) => {
                        let { serviceName, wechatName } = item
                        let key = '', title = ''
                        if (serviceName?.indexOf('巨网') !== -1) {
                            key = '巨网-' + wechatName
                            title = '巨网-' + wechatName
                        } else if (serviceName?.indexOf('太古') !== -1) {
                            key = '太古-' + wechatName
                            title = '太古-' + wechatName
                        } else if (serviceName?.indexOf('广联') !== -1) {
                            key = '广联-' + wechatName
                            title = '广联-' + wechatName
                        } else if (serviceName?.indexOf('赞象') !== -1) {
                            key = '赞象-' + wechatName
                            title = '赞象-' + wechatName
                        } else {
                            key = serviceName + '-' + wechatName
                            title = serviceName + '-' + wechatName
                        }
                        return {
                            key: key,
                            title: title,
                            wechat_info: item
                        }
                    })
                    // newTargetKeys.push(data.key);  // key  字符串
                    setMockData(newMockData);
                }
            })
        }
    }, [currentUser, isModalVisible])

    /** 关闭按钮 */
    const handleCancel = useCallback(() => {
        setIsModalVisible(false)
    }, [isModalVisible])

    /** 确定按钮 */
    const handleOk = useCallback(() => {
        let backData = targetKeys?.map((item: string) => {
            let newItem = mockData?.find((mock: any) => item === mock?.key)
            return {...newItem, wechat_info: {service_name: newItem?.wechat_info?.serviceName, wechat_name: newItem?.wechat_info?.wechatName}}
        })
        onChange && onChange(backData)
        setData(targetKeys)
        setIsModalVisible(false)
    }, [isModalVisible, targetKeys, mockData, data])
    
    /** 刷新投放号 */
    const refreshAcc = useCallback(() => {
        refreshData.run({ userId: currentUser?.userId, is_refresh: '1' }).then((res: any) => {
            if (res?.msg === "SUCCESS") {
                let data = JSON.parse(res?.data)
                if(data?.wechat_code) {
                    setCodeImg(data?.wechat_code)
                    scanStatusHandle()
                    setVisible(true)
                }
            }
        })
    }, [visible, currentUser])

    /** 二维码扫码回调 */
    const scanStatusHandle = useCallback(() => {
        timer = setInterval(()=>{
            getScanStatus.run().then((res: any) => {
                console.log(res);
                if (res?.msg === "SUCCESS" && res?.data?.scanAction === 'done' ) {
                    timer && clearInterval(timer)
                    setVisible(false)
                    // message.success('刷新成功')
                    getAcc.run().then((res: any) => {
                        if (res?.msg === "SUCCESS") {
                            let { data } = res
                            const newMockData = data?.map((item: any, index: number) => {
                                let { serviceName, wechatName } = item
                                let key = '', title = ''
                                if (serviceName?.indexOf('巨网') !== -1) {
                                    key = '巨网-' + wechatName
                                    title = '巨网-' + wechatName
                                } else if (serviceName?.indexOf('太古') !== -1) {
                                    key = '太古-' + wechatName
                                    title = '太古-' + wechatName
                                } else if (serviceName?.indexOf('广联') !== -1) {
                                    key = '广联-' + wechatName
                                    title = '广联-' + wechatName
                                } else if (serviceName?.indexOf('赞象') !== -1) {
                                    key = '赞象-' + wechatName
                                    title = '赞象-' + wechatName
                                } else {
                                    key = serviceName + '-' + wechatName
                                    title = serviceName + '-' + wechatName
                                }
                                return {
                                    key: key,
                                    title: title,
                                    wechat_info: item
                                }
                            })
                            // newTargetKeys.push(data.key);  // key  字符串
                            setMockData(newMockData);
                        }
                    })
                }else if(res?.msg === "SUCCESS" && res?.data?.scanAction === "error") {
                    message.error('刷新失败')
                    timer && clearInterval(timer)
                    setVisible(false)
                }
            })
        }, 2000)
    }, [currentUser, visible])

    /**数据回填*/
    useEffect(() => {
        if (defaultValue?.length > 0) {
            let arr = defaultValue?.map((item:any)=>item.key)
            console.log(22222);
            setTargetKeys(arr)
            setData(arr)
        }else {
            setData([])
            setTargetKeys([])
        }
        return () => {
            if (timer) {
                clearInterval(timer)
            }
        }
    }, [defaultValue])

    /** 扫码弹窗关闭 */
    const codeCloce = useCallback(() => {
        setVisible(false)
        if (timer) {
            clearInterval(timer)
        }
        // window.location.href = '/#/launchSystem/launchManage/taskList'
    }, [visible])
    return <>
        <div className={style.customSelect}>
            <div className={style.flexBox}>
                {/* <div className={style.title}>{title}</div> */}
                <div className={style.uiTof}>
                    {
                        data.length > 0 && <>
                            {data[0]}
                            <span className={style.uiCGray}>共{data?.length}项</span>
                            {!open ? <Button type='link' style={{ marginLeft: 8, fontSize: 12, padding: '0 2px' }} size="small" onClick={() => { setOpen(true) }}>展开</Button>
                                : <Button type='link' style={{ marginLeft: 8, fontSize: 12, padding: '0 2px' }} size="small" onClick={() => { setOpen(false) }}>收起</Button>}
                        </>
                    }
                </div>
                <Button type="text" className={style.button} size='small' onClick={() => { setIsModalVisible(true) }}>{btText}</Button>

                <div className={`${style.popup}`} style={{ display: open ? 'block' : 'none' }}>
                    {data?.map((item: any, index: number) => {
                        return <div className={`${style.flexBox} ${style.list}`} key={index}>
                            <div className={style.uiTof}>{item}</div>
                        </div>
                    })}
                </div>
            </div>
        </div>
        <Modal
            title={<Space>
                <span>{btText}</span>
                <Button type="link" onClick={refreshAcc} loading={refreshData?.loading}>刷新</Button>
            </Space>}
            visible={isModalVisible}
            onOk={handleOk}
            onCancel={handleCancel}>
            <Transfer
                showSearch
                dataSource={mockData}
                targetKeys={targetKeys}
                onChange={onChangeTransfer}
                render={item => item.title}
                oneWay={oneWay}
                pagination
            />
        </Modal>
        <PupCode callBack={codeCloce} codeImg={codeImg} visible={visible} />
    </>
}

export default CustomSelect