
import { useAjax } from "@/Hook/useAjax"
import { CheckOutlined, CloseOutlined, QuestionCircleOutlined, SyncOutlined } from "@ant-design/icons"
import { Button, Input, message, Modal, Select, Space, Table, Tooltip, Typography } from "antd"
import React, { useEffect, useState } from "react"
import style from '../GoodsModal/index.less'
import columns from "./tableConfig"
import { getWechatAppletApi } from "@/services/adqV3/global"
import New1Radio from "../New1Radio"
import { getErpUserAll } from "@/services/launchAdq/adq"
const { Title, Text } = Typography;

/**
 * 获取微信小程序
 * @returns 
 */
interface Props {
    visible?: boolean,
    onClose?: () => void,
    onChange?: (value: { data: PULLIN.AccountCreateLogsProps[], landingPageType: 0 | 1 }) => void,
    adgroups: any
    dynamic: any
    data: PULLIN.AccountCreateLogsProps[]
}
const MiniProgramPage: React.FC<Props> = (props) => {

    /*************************/
    const { visible, onClose, data: data1, onChange, dynamic } = props
    const { creativeTemplateId, deliveryMode, creativeComponents: { mainJumpInfo }, landingPageType } = dynamic
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主
    const [data, setData] = useState<PULLIN.AccountCreateLogsProps[]>(data1 || [])
    const userId = localStorage.getItem('userId')
    const [queryForm, setQueryForm] = useState<{ appletName?: string, appletIdList?: string[], createBy?: number, pageSize: number, pageNum: number }>({ pageNum: 1, pageSize: 20, createBy: userId ? Number(userId) : undefined })
    const [pageAllocationType, setPageAllocationType] = useState<0 | 1>(landingPageType || 0)

    const listAjax = useAjax((params) => getWechatAppletApi(params))
    const allOfMember = useAjax(() => getErpUserAll())
    /*************************/

    useEffect(() => {
        allOfMember.run()
    }, [])

    useEffect(() => {
        getList()
    }, [queryForm])

    // 获取落地页列表
    const getList = () => {
        listAjax.run(queryForm)
    }

    const handleOk = () => {
        if (deliveryMode === "DELIVERY_MODE_COMPONENT" && !data?.every(item => item.pageList?.length === mainJumpInfo?.length)) {
            message.error(`当前落地页数量不足，跳转类型选择了${mainJumpInfo.length}组，落地页应当选择${mainJumpInfo.length}组`)
            return
        }
        if (data?.every(item => item.pageList)) {
            onChange && onChange({ data, landingPageType: pageAllocationType })
        } else {
            message.error('还有账号未选择落地页！')
        }
    }

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

    /** 一键设置 */
    const setOnekey = () => {
        const hide = message.loading(`正在设置...`, 0, () => {
            message.success('设置成功');
        });
        let newData: PULLIN.AccountCreateLogsProps[] = JSON.parse(JSON.stringify(data))
        let pageList = data[selectAdz - 1]['pageList']
        newData = newData.map(item => {
            if (item.accountId !== data[selectAdz - 1].accountId) {
                return { ...item, pageList: pageList }
            }
            return item
        })
        setData(newData)
        message.success('设置完成');
        hide()
    }

    return <Modal
        title={<Space>
            <strong>选择微信小程序</strong>
            {data?.length > 1 && <Button style={{ padding: 0, margin: 0 }} disabled={!data[selectAdz - 1]['pageList']?.length} onClick={setOnekey} type="link" loading={listAjax.loading}>
                <Space>
                    <span style={{ fontSize: 12 }}>一键设置</span>
                    <Tooltip color="#FFF" overlayInnerStyle={{ color: '#000' }} title="设置其它账号有相同名称的落地页为那个账号的落地页（需要落地页名称相同，否则不设置，注意只会根据当前条件去搜索，比如选择了被授权落地页，只会去被授权落地页里找对应落地页）">
                        <QuestionCircleOutlined />
                    </Tooltip>
                </Space>
            </Button>}
            <Button
                type="link"
                danger
                disabled={!data?.some(item => item.pageList?.length)}
                onClick={() => {
                    setData(data => data.map(item => ({ ...item, pageList: [] })))
                }}
            >全部清空</Button>
        </Space>}
        open={visible}
        onCancel={() => { onClose && onClose() }}
        onOk={handleOk}
        width={1100}
        className={`${style.SelectPackage} modalResetCss`}
        bodyStyle={{ padding: '0 10px 0 10px' }}
    >
        {[910].includes(creativeTemplateId) && <div className={style.pageType}>
            <Space size={12}>
                <strong>落地页分配规则</strong>
                <New1Radio
                    data={[{ label: '全部相同', value: 0 }, { label: '平均分配', value: 1 }]}
                    value={pageAllocationType}
                    onChange={(e) => {
                        setPageAllocationType(e)
                    }}
                />
            </Space>
        </div>}
        <div className={style.content}>
            <div className={style.left}>
                <h4 className={style.title}>媒体账户</h4>
                <div className={style.accountIdList}>
                    {data?.map((item, index) => (
                        <div key={index} onClick={() => { handleSelectAdz(index + 1, item) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            {item?.accountId}
                            {data[index].pageList?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>
                    ))}
                </div>
            </div>
            <div className={style.right}>
                <Space style={{ marginBottom: 10 }}>
                    <Select
                        showSearch
                        placeholder="请选择创建人"
                        onChange={(e) => setQueryForm({ ...queryForm, createBy: e, pageNum: 1 })}
                        filterOption={(input, option) =>
                            (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        value={queryForm?.createBy}
                        allowClear
                        style={{ width: 120 }}
                        loading={allOfMember.loading}
                        options={allOfMember?.data?.map((item: { userId: any; nickname: string }) => ({
                            value: item.userId,
                            label: item.nickname
                        }))}
                    />
                    <Input style={{ width: 160 }} placeholder="请输入小程序名称" value={queryForm?.appletName} allowClear onChange={(e) => setQueryForm({ ...queryForm, appletName: e.target.value, pageNum: 1 })} />
                    <Input.TextArea
                        style={{ width: 250 }}
                        placeholder="请输入小程序原始ID（多个逗号隔开）"
                        allowClear
                        rows={1}
                        onChange={(e) => {
                            let value = e.target.value
                            let arr: string[] = []
                            if (value) {
                                value = value.replace(/[,，\s]/g, ',')
                                arr = value.split(',').filter((a: string) => a)
                            }
                            setQueryForm({ ...queryForm, appletIdList: arr, pageNum: 1 })
                        }}
                    />
                    <Button style={{ padding: 0, margin: 0 }} icon={<SyncOutlined />} type='link' loading={listAjax?.loading} onClick={() => { listAjax?.refresh() }}><span style={{ fontSize: 12 }}>刷新</span></Button>
                </Space>
                <Table
                    columns={columns(3)}
                    dataSource={listAjax.data?.records?.map((item: { appletName: any; id: any }) => ({ ...item, pageName: item.appletName, pageId: item.id }))}
                    size="small"
                    loading={listAjax?.loading}
                    scroll={{ y: 400 }}
                    bordered
                    rowKey={'id'}
                    pagination={{
                        defaultPageSize: 20,
                        current: listAjax.data?.current || 1,
                        pageSize: listAjax.data?.size || 10,
                        total: listAjax.data?.total || 0
                    }}
                    onChange={(pagination) => {
                        const { current, pageSize } = pagination
                        setQueryForm({ ...queryForm, pageNum: current || 1, pageSize: pageSize || 10 })
                    }}
                    rowSelection={{
                        type: ([910].includes(creativeTemplateId) || deliveryMode === "DELIVERY_MODE_COMPONENT") ? 'checkbox' : 'radio',
                        getCheckboxProps: (record) => {
                            // 组件化创意
                            if (deliveryMode === "DELIVERY_MODE_COMPONENT") {
                                if (data[selectAdz - 1]?.pageList?.length >= mainJumpInfo?.length) {
                                    return {
                                        disabled: data[selectAdz - 1]?.pageList?.some((item: any) => item?.id === record?.id) ? false : true
                                    }
                                } else {
                                    return {
                                        disabled: false
                                    }
                                }
                            }
                            return {
                                disabled: false
                            }
                        },
                        selectedRowKeys: data[selectAdz - 1]?.pageList?.map((item: any) => item?.id),
                        hideSelectAll: deliveryMode === "DELIVERY_MODE_COMPONENT",
                        onSelect: (record: any, selected: boolean) => {
                            let newData = JSON.parse(JSON.stringify(data))
                            if (([910].includes(creativeTemplateId) || deliveryMode === "DELIVERY_MODE_COMPONENT")) {
                                let selectedRows = newData?.[selectAdz - 1]?.['pageList'] || []
                                if (selected) {
                                    selectedRows.push({ ...record })
                                    newData[selectAdz - 1]['pageList'] = selectedRows
                                } else {
                                    newData[selectAdz - 1]['pageList'] = selectedRows.filter((item: { id: number }) => item.id !== record.id)
                                }
                            } else {
                                newData[selectAdz - 1]['pageList'] = [record]
                            }
                            setData([...newData])
                        },
                        onSelectAll: (selected: boolean, _: any[], changeRows: { id: number }[]) => {
                            let newData = JSON.parse(JSON.stringify(data))
                            let selectedRows = newData?.[selectAdz - 1]?.['pageList'] || []
                            if (selected) {
                                let newSelectAccData = [...selectedRows]
                                changeRows.forEach((item: { id: number }) => {
                                    let index = newSelectAccData.findIndex((ite: { id: number }) => ite.id === item.id)
                                    if (index === -1) {
                                        let data: any = { ...item }
                                        newSelectAccData.push(data)
                                    }
                                })
                                newData[selectAdz - 1]['pageList'] = newSelectAccData
                            } else {
                                newData[selectAdz - 1]['pageList'] = selectedRows.filter((item: { id: number }) => {
                                    let index = changeRows.findIndex((ite: { id: number }) => ite.id === item.id)
                                    if (index !== -1) {
                                        return false
                                    } else {
                                        return true
                                    }
                                })
                            }
                            setData([...newData])
                        }
                    }}
                />
            </div>
            <div className={style.center}>
                <Title level={5}>已选：{data[selectAdz - 1]?.pageList?.length || 0}</Title>
                <div className={style.select_content} style={{ height: 416 }}>
                    {data[selectAdz - 1]?.pageList?.map((item: any) => <div key={item.id}>
                        <Text ellipsis={{ tooltip: true }} className={style.marketingAssetName}>{item.appletName}</Text>
                        <CloseOutlined className={style.close} onClick={() => {
                            let newData: PULLIN.AccountCreateLogsProps[] = JSON.parse(JSON.stringify(data))
                            newData[selectAdz - 1].pageList = newData[selectAdz - 1]?.pageList?.filter((i: any) => i?.id !== item.id)
                            setData(newData)
                        }} />
                    </div>)}
                </div>
            </div>
        </div>

    </Modal>
}

export default React.memo(MiniProgramPage)