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

/**
 * 获取商品列表
 * @returns 
 */
interface Props {
    visible?: boolean,
    onClose?: () => void,
    onChange?: (data: any) => void,
    data: any
}
const GoodsModal: React.FC<Props> = (props) => {

    /************************/
    const { visible, onClose, data: data1, onChange } = props
    const [tableData, setTableData] = useState<any[]>([])//table数据
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主
    const [data, setData] = useState<any>(data1)

    const getGoods = useAjax((params) => getGoodsApi(params))
    const synGoods = useAjax((params) => synGoodsApi(params))
    /************************/

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

    // 获取商品列表
    const getList = (params: number[]) => {
        getGoods.run(params).then(res => {
            console.log('res===>', res)
            if (res && Object.keys(res)?.indexOf(params[0].toString()) !== -1) {
                setTableData(res[params[0]]?.map((item: { productOuterId: string }) => ({ ...item, id: Number(item?.productOuterId?.replace(/\D/ig, '')) })))
            } else {
                setTableData([])
            }
        })
    }

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

    // 同步商品库
    const synGoodsList = () => {
        synGoods.run(data?.map((item: { adAccountId: number }) => item?.adAccountId)).then(res => {
            getList([data[selectAdz - 1].adAccountId])
        })
    }

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

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

    // 清空已选
    const clearGoods = () => {
        let newData = JSON.parse(JSON.stringify(data))
        newData[selectAdz - 1]['productList'] = []
        setData([...newData])
    }

    /** 一键设置 */
    const setOnekey = () => {
        let goodsNames: string[] = data[selectAdz - 1]['productList']?.map((item: { productName: string }) => item.productName)
        let newData = JSON.parse(JSON.stringify(data))
        const hide = message.loading(`正在设置...`, 0, () => {
            message.success('设置成功');
        });
        getGoods.run(newData?.filter((item: { adAccountId: number }) => item.adAccountId !== data[selectAdz - 1].adAccountId)?.map((item: { adAccountId: number }) => item?.adAccountId)).then(res => {
            if (res && typeof res === 'object') {
                Object.keys(res).forEach((key: string) => {
                    let values = goodsNames.map(name => {
                        let value = res[key]?.find((item: { productName: string }) => item.productName === name)
                        if (value) {
                            return { ...value, id: Number(value?.productOuterId?.replace(/\D/ig, '')) }
                        }
                        return undefined
                    }).filter(item => item)
                    if (values.length > 0) {
                        newData = newData.map((item: { adAccountId: string }) => {
                            if (item.adAccountId.toString() === key.toString()) {
                                return { ...item, productList: values }
                            }
                            return item
                        })
                    }
                })
                setData(newData)
            }
            message.success('设置完成');
            hide()
        })
    }
    

    return <Modal
        title={<Space>
            <span>商品库</span>
            <Button size="small" onClick={() => { synGoodsList() }} type="link" loading={synGoods?.loading}>同步商品库</Button>
        </Space>}
        open={visible}
        onCancel={() => { onClose && onClose() }}
        onOk={handleOk}
        width={1100}
        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].productList?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                    </div>
                ))}
            </div>
            <div className={style.right}>
                <Space style={{ marginBottom: 10 }} align="end" size={0}>
                    <Button icon={<SyncOutlined />} type='link' loading={getGoods?.loading} onClick={() => { getList([data[selectAdz - 1].adAccountId]) }}>刷新</Button>
                    {data?.length > 1 && <Button disabled={!data[selectAdz - 1]['productList']?.length} onClick={setOnekey} type="link" loading={getGoods.loading}>
                        <Space>
                            <span>一键设置</span>
                            <Tooltip color="#FFF" overlayInnerStyle={{ color: '#000' }} title="设置其它账号有相同名称的商品为那个账号的商品（注意需要用户商品称相同，否则不设置）">
                                <QuestionCircleOutlined />
                            </Tooltip>
                        </Space>
                    </Button>}
                    {data[selectAdz - 1]?.productList?.length > 0 && <Button type='link' onClick={() => { clearGoods() }}>清空</Button>}
                </Space>
                <Tables
                    columns={columns()}
                    dataSource={tableData}
                    size="small"
                    loading={getGoods?.loading}
                    scroll={{ y: 300 }}
                    bordered
                    defaultPageSize={100}
                    rowSelection={{
                        type: 'radio',
                        selectedRowKeys: data[selectAdz - 1]?.productList?.map((item: any) => item?.id?.toString()),
                        onChange: onChangeTable
                    }}
                />
            </div>
        </div>
    </Modal>
}

export default React.memo(GoodsModal)