import { Button, Card, Drawer, Input, Space, Typography, message } from "antd"
import React, { useEffect, useState } from "react"
import '../../index.less'
import New1Radio from "@/pages/launchSystemV3/components/New1Radio";
import style from '../index.less'
import { CheckOutlined, CloseOutlined, PlusOutlined, SearchOutlined, UndoOutlined } from "@ant-design/icons";
import AddTarget from "./addTarget";
import { useAjax } from "@/Hook/useAjax";
import { getTargetingListApi } from "@/services/adqV3";
import Tables from "@/components/Tables";
import { TableConfig } from "./tableConfig";
import { getTargetingGagsApi } from "@/services/adqV3/global";
import { randomString } from "@/utils/utils";
import { targetingData } from "@/pages/launchSystemV3/components/TargetingTooltip";
const { Title, Text } = Typography;

interface Props {
    value?: any,
    putInType?: 'NOVEL' | 'GAME'
    visible?: boolean
    onClose?: () => void
    onChange?: (value: any) => void
    targetRules?: PULLIN.TargetingRulesProps
}

/**
 * 添加定向
 * @param param0 
 * @returns 
 */
const SelectTarget: React.FC<Props> = ({ value = [], putInType, visible, onChange, onClose, targetRules }) => {

    /*****************************/
    const [distributionRule, setDistributionRule] = useState<'1' | '2'>('1')
    const [addTemVisible, setAddTemVisible] = useState<boolean>(false)
    const [queryParams, setQueryParams] = useState<PULLIN.GetTargeting>({ pageNum: 1, pageSize: 20 })
    const [queryParamsNew, setQueryParamsNew] = useState<PULLIN.GetTargeting>({ pageNum: 1, pageSize: 20 })

    const [geoLocationList, setGeoLocationList] = useState<any>({}) // 所有地域列表
    const [modelList, setModelList] = useState<any>({})  // 所有品牌手机
    const [modifyDta, setModifyDta] = useState<any>()
    const [selectedTargetKeys, setSelectedTargetKeys] = useState<any[]>(value)
    const [tableList, setTableList] = useState<any[]>([])

    const getTargetingGags = useAjax((params) => getTargetingGagsApi(params))
    const getTargetingList = useAjax((params) => getTargetingListApi(params))
    /*****************************/

    // 设置地域
    useEffect(() => {
        async function handle() {
            await getTargetingGags.run({ type: 'REGION' }).then(res => {
                if (res && Array.isArray(res)) {
                    setGeoLocationList(() => (res as any[])?.reduce((prev: any, cur: { id: number }) => {
                        prev[cur.id] = cur
                        return prev
                    }, {}))
                }
            })
            await getTargetingGags.run({ type: 'DEVICE_BRAND_MODEL' }).then(res => {
                if (res && Array.isArray(res)) {
                    setModelList(() => (res as any[])?.reduce((prev: any, cur: { id: number }) => {
                        prev[cur.id] = cur
                        return prev
                    }, {}))
                }
            })
        }
        handle()
    }, [])

    useEffect(() => {
        getTargetingList.run({ ...queryParamsNew, taskType: putInType }).then(res => {
            let newTableList = res?.records || []
            if (targetRules) {
                let target = ''
                const rulesField = new Set(targetRules.rules.map(item => {
                    const fieldName = item
                    let targetName = targetingData.find(item => item.key === fieldName)?.name
                    if (!targetName) {
                        targetName = { excludedCustomAudience: '排除用户群', customAudience: '定向用户群' }[fieldName]
                    }
                    target += target ? ',' + targetName : targetName
                    return fieldName
                }))
                const msg = targetRules.desc + '，仅支持' + target
                newTableList = newTableList.map((item: { targeting: Record<string, any> }) => {
                    if (Object.keys(item.targeting).every(key => rulesField.has(key))) {
                        return { ...item, isSelect: true, noSelectMsg: '' }
                    }
                    return { ...item, isSelect: false, noSelectMsg: msg }
                })
            }
            setTableList(newTableList || [])
        })
    }, [queryParamsNew, targetRules])

    /** 编辑 复制 */
    const editHandle = (data: any, isCopy?: boolean) => {
        const { targetingName, targeting, description, id, accountId, taskType } = data
        let newModifyDta = {
            ...targeting,
            targetingName,
            description,
            accountId: accountId || undefined,
            taskType
        }
        if (!isCopy) {
            newModifyDta.id = id
        } else {
            newModifyDta.targetingName = newModifyDta.targetingName + `_副本${randomString(true, 3, 5)}`
            newModifyDta.isCopy = isCopy
        }
        setModifyDta(newModifyDta)
        setAddTemVisible(true)
    }

    const handleOk = () => {
        if (selectedTargetKeys?.length > 0) {
            onChange?.(selectedTargetKeys)
        } else {
            message.error('请选择定向模板')
        }
    }


    return <Drawer
        title={<strong style={{ fontSize: 20 }}>定向模板</strong>}
        open={visible}
        onClose={onClose}
        width={1200}
        headerStyle={{ padding: '10px 16px' }}
        maskClosable={false}
        className={`modalResetCss targetingSelect`}
    >
        <Card className="cardResetCss" bodyStyle={{ padding: 0, height: 'calc(100vh - 136px)', overflow: 'hidden', overflowY: 'auto' }}>
            <div className="flexColumnStart" style={{ height: '100%' }}>
                <div className="flexSpaceBetween" style={{ padding: 16 }}>
                    <Space size={20}>
                        <Text strong>定向模板分配规则</Text>
                        <New1Radio
                            // { label: '按账户选择', value: '2' }
                            data={[{ label: '全部相同', value: '1' }]}
                            value={distributionRule}
                            onChange={(e) => setDistributionRule(e)}
                        />
                    </Space>
                </div>
                <div className={style.template}>
                    {distributionRule === '2' && <div className={style.template_left}>
                        <h4 className={style.title}>媒体账户</h4>
                        <div onClick={() => { }} className={`${style.accItem}`}>
                            43151494
                            <CheckOutlined style={{ color: '#1890ff' }} />
                        </div>
                    </div>}
                    <div className={style.template_center}>
                        <div className="flexSpaceBetween" style={{ marginBottom: 10 }}>
                            <Space>
                                <Input placeholder="请输入定向模板名称" value={queryParams?.targetingName} allowClear onChange={(e) => setQueryParams({ ...queryParams, targetingName: e.target.value, pageNum: 1 })} />
                                <Button type="primary" icon={<SearchOutlined />} loading={getTargetingList.loading} onClick={() => setQueryParamsNew({ ...queryParams })}>搜索</Button>
                            </Space>
                            <Space>
                                <Button type="primary" icon={<PlusOutlined />} onClick={() => setAddTemVisible(true)}>新增定向模板</Button>
                            </Space>
                        </div>
                        <Tables
                            columns={TableConfig(geoLocationList, modelList, editHandle)}
                            dataSource={tableList}
                            size="small"
                            loading={getTargetingList?.loading}
                            scroll={{ y: 320 }}
                            bordered
                            rowSelection={{
                                type: 'checkbox',
                                selectedRowKeys: selectedTargetKeys?.map((item: any) => item?.id?.toString()),
                                getCheckboxProps: (record: any) => ({
                                    disabled: Object.keys(record).includes('isSelect') ? !record.isSelect : false
                                }),
                                onChange: (_: React.Key[], selectedRows: any) => {
                                    setSelectedTargetKeys(selectedRows)
                                }
                            }}
                            total={getTargetingList?.data?.total}
                            defaultPageSize={20}
                            current={getTargetingList?.data?.current}
                            pageSize={getTargetingList?.data?.size}
                            pageChange={(page: number, pageSize?: number) => {
                                setQueryParamsNew({ ...queryParamsNew, pageNum: page, pageSize: pageSize as number || 20 })
                                setQueryParams({ ...queryParams, pageNum: page, pageSize: pageSize as number || 20 })
                            }}
                        />
                    </div>
                    <div className={style.template_right}>
                        <div className={`flexSpaceBetween ${style.header}`}>
                            <Title level={5} style={{ marginBottom: 0 }}>已选：{selectedTargetKeys?.length || 0}</Title>
                            <Button type="link" style={{ padding: 0, fontSize: 12, lineHeight: 'normal' }} onClick={() => setSelectedTargetKeys([])} icon={<UndoOutlined />}>清空</Button>
                        </div>
                        <div className={style.selectTarget}>
                            {selectedTargetKeys?.map((item: any) => <div key={item.id} className={style.selectTarget__row}>
                                <Text ellipsis={{ tooltip: true }}>{item.targetingName}</Text>
                                <Button type="link" className={style.clear} onClick={() => setSelectedTargetKeys(selectedTargetKeys.filter(i => item.id !== i.id))} danger icon={<CloseOutlined />}></Button>
                            </div>)}
                        </div>
                    </div>
                </div>
            </div>
        </Card>

        <Card className="cardResetCss" style={{ marginTop: 8 }} bodyStyle={{ display: 'flex', justifyContent: 'center', gap: 10 }}>
            <Button onClick={onClose}>取消</Button>
            <Button type="primary" onClick={() => handleOk()}>确定</Button>
        </Card>

        {/* 新增修改定向模板 */}
        {addTemVisible && <AddTarget
            value={modifyDta}
            visible={addTemVisible}
            putInType={putInType}
            onClose={() => {
                setAddTemVisible(false)
                setModifyDta(undefined)
            }}
            onChange={() => {
                setAddTemVisible(false)
                setModifyDta(undefined)
                getTargetingList.refresh()
            }}
        />}

    </Drawer>
}

export default React.memo(SelectTarget)