import Tables from "@/components/Tables"
import { useAjax } from "@/Hook/useAjax"
import { getCropWechatApi, sysCropWechatApi } from "@/services/launchAdq/createAd"
import { CheckOutlined, SyncOutlined } from "@ant-design/icons"
import { Button, Input, message, Modal, Space, Tooltip } from "antd"
import React, { useEffect, useState } from "react"
import style from '../goodsModal/index.less'
import columns from "./tableConfig"

/**
 * 获取客服组
 * @returns 
 */
interface Props {
    onChange?: (data: any) => void,
    data: any
}
const CustomerServiceModal: React.FC<Props> = (props) => {

    /************************/
    const { data: data1, onChange } = props
    const [tableData, setTableData] = useState<any[]>([])//table数据
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主
    const [selectCrop, setSelectCrop] = useState<number>(1)   // 选择按钮
    const [data, setData] = useState<any>(JSON.parse(JSON.stringify(data1)))
    const [visible, setVisible] = useState<boolean>(false)
    const [sysVisible, setSysVisible] = useState<boolean>(false)
    const [corpId, setCorpId] = useState<string>('')
    const [notConfigured, setNotConfigured] = useState<any>([])

    const getCropWechat = useAjax((params) => getCropWechatApi(params))
    const sysCropWechat = useAjax((params) => sysCropWechatApi(params))
    /************************/

    useEffect(() => {
        setData(data1)
    }, [data1])

    /** 未配置账户获取 */
    useEffect(() => {
        setNotConfigured(() => data.filter((item: { data: { cropList: any[] }[] }) => item?.data?.some((item: { cropList: any[] }) => item?.cropList?.length === 0)))
    }, [data])

    useEffect(() => {
        if (data?.length > 0) {
            getList([data[selectAdz - 1].adAccountId])
        } else {
            setTableData([])
        }
    }, [selectAdz])


    // 获取客服组列表
    const getList = (params: number[]) => {
        getCropWechat.run(params).then(res => {
            if (res && Object.keys(res)?.indexOf(params[0].toString()) !== -1) {
                setTableData(res[params[0]]?.map((item: { groupId: string }) => ({ ...item, id: item.groupId })))
            } else {
                setTableData([])
            }
        })
    }

    const handleOk = () => {
        onChange && onChange(data)
        setVisible(false)
    }

    /** 设置选中广告主 */
    const handleSelectAdz = (value: number, item: any) => {
        if (value === selectAdz) {
            return
        }
        setSelectAdz(value)
        setSelectCrop(1)
    }

    /** 设置选中广告主 */
    const handleSelectCrop = (value: number, item: any) => {
        if (value === selectCrop) {
            return
        }
        setSelectCrop(value)
    }

    /** 表格选折 */
    const onChangeTable = (selectedRowKeys: React.Key[], selectedRows: any) => {
        let newData = JSON.parse(JSON.stringify(data))
        newData[selectAdz - 1].data[selectCrop - 1].cropList = selectedRows
        setData([...newData])
    }

    /** 同步 */
    const handleSys = () => {
        if (corpId) {
            console.log(data[selectAdz - 1].id, corpId);
            sysCropWechat.run({ accountId: data[selectAdz - 1].adAccountId, corpId: corpId }).then(res => {
                if (res) {
                    getList([data[selectAdz - 1].adAccountId])
                    message.success('同步成功')
                    setSysVisible(false)
                }
            })
        } else {
            message.error('请输入企业微信ID')
        }
    }

    return <div>
        <Button type="link" size="small" onClick={() => setVisible(true)} style={{ fontSize: 12 }}>{data1.some((item: { data: { cropList: any[] }[] }) => item?.data?.some((item: { cropList: any[] }) => item?.cropList?.length > 0)) ? '修改客服' : '配置客服'}</Button>
        {visible && <Modal
            title={<Space>
                <span>客服组</span>
                <Button size="small" onClick={() => { setSysVisible(true) }} type='link'>同步客服组</Button>
            </Space>}
            open={visible}
            footer={<Space>
                <Button onClick={() => setVisible(false)}>取消</Button>
                {notConfigured?.length > 0 ? <Tooltip title={`${notConfigured?.map((item: { adAccountId: string }) => item.adAccountId)?.toString()}下按钮未全部配置客服`}>
                    <Button type="primary">确定</Button>
                </Tooltip> : <Button type="primary" onClick={handleOk}>确定</Button>}
            </Space>}
            width={1100}
            onCancel={() => setVisible(false)}
            className={style.SelectPackage}
            bodyStyle={{ padding: '0 10px 0 10px' }}
        >
            <div className={style.content}>
                <div className={style.left}>
                    <h4 className={style.title}>媒体账户</h4>
                    {data?.map((item: { adAccountId: number, id: number }, index: number) => (
                        <div key={index} onClick={() => { handleSelectAdz(index + 1, item) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            {item?.adAccountId}
                            {data[index]?.data?.every((item: { cropList: any[] }) => item?.cropList?.length > 0) && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>))}
                </div>
                <div className={style.left}>
                    <h4 className={style.title}>企微按钮</h4>
                    {data[selectAdz - 1].data?.map((item: { name: number }, index: number) => (
                        <div key={index} onClick={() => { handleSelectCrop(index + 1, item) }} className={`${style.accItem} ${selectCrop === index + 1 && style.select} `}>
                            <div>按钮{index + 1}<span style={{ fontSize: 12 }}>({item.name})</span></div>
                            {data[selectAdz - 1]?.data[index]?.cropList?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>))}
                </div>
                <div className={style.right}>
                    <Space style={{ marginBottom: 10 }} align="end">
                        <Button icon={<SyncOutlined />} type='link' loading={getCropWechat?.loading} onClick={() => { getList([data[selectAdz - 1].adAccountId]) }}></Button>
                    </Space>
                    <Tables
                        columns={columns()}
                        dataSource={tableData}
                        size="small"
                        loading={getCropWechat?.loading}
                        scroll={{ y: 300 }}
                        bordered
                        rowSelection={{
                            type: 'radio',
                            selectedRowKeys: data[selectAdz - 1]?.data[selectCrop - 1]?.cropList?.map((item: any) => item?.id?.toString()),
                            onChange: onChangeTable
                        }}
                    />
                </div>
            </div>
        </Modal>}

        {/* 输入企业微信ID同步 */}
        {sysVisible && <Modal title="输入企业微信ID同步" open={sysVisible} onOk={handleSys} onCancel={() => setSysVisible(false)} okText='同步' confirmLoading={sysCropWechat.loading}>
            <Input value={corpId} onChange={(e) => setCorpId(e.target.value)} placeholder='输入企业微信ID同步' />
        </Modal>}
    </div>
}

export default React.memo(CustomerServiceModal)