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";
const { Title, Text } = Typography;

interface Props {
    value?: any,
    visible?: boolean
    onClose?: () => void
    onChange?: (value: any) => void
}

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

    /*****************************/
    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 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)
    }, [queryParamsNew])

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

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


    return <Drawer
        title={<strong style={{ fontSize: 20 }}>定向模板</strong>}
        visible={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={getTargetingList?.data?.records}
                            size="small"
                            loading={getTargetingList?.loading}
                            scroll={{ y: 320 }}
                            bordered
                            rowSelection={{
                                type: 'checkbox',
                                selectedRowKeys: selectedTargetKeys?.map((item: any) => item?.id?.toString()),
                                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 }}>已选：3</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}
            onClose={() => {
                setAddTemVisible(false)
                setModifyDta(undefined)
            }}
            onChange={() => {
                setAddTemVisible(false)
                setModifyDta(undefined)
            }}
        />}

    </Drawer>
}

export default React.memo(SelectTarget)