import { Button, Card, DatePicker, Input, Select, message } from "antd"
import React, { useEffect, useState } from "react"
import '../../tencentAdPutIn/index.less'
import { delTargetingApi, getTargetingListApi } from "@/services/adqV3"
import { useAjax } from "@/Hook/useAjax"
import { PlusOutlined, SearchOutlined } from "@ant-design/icons"
import moment from "moment"
import AddTarget from "../../tencentAdPutIn/create/Target/addTarget"
import Tables from "@/components/Tables"
import { TableConfig } from "./tableConfig"
import { randomString } from "@/utils/utils"
import { useModel } from "umi"

/**
 * 资产定向模板
 * @returns 
 */
const Targeting: React.FC = () => {

    /**************************************/
    const { getAllUserAccount } = useModel('useLaunchAdq.useAdAuthorize')
    const { initTargeting, geoLocationList, modelList } = useModel('useLaunchV3.useTargeting')
    const [queryParams, setQueryParams] = useState<PULLIN.GetTargeting>({ pageNum: 1, pageSize: 20 })
    const [queryParamsNew, setQueryParamsNew] = useState<PULLIN.GetTargeting>({ pageNum: 1, pageSize: 20 })
    const getTargetingList = useAjax((params) => getTargetingListApi(params))
    const [addTemVisible, setAddTemVisible] = useState<boolean>(false)
    const [modifyDta, setModifyDta] = useState<any>()

    const delTargeting = useAjax((params) => delTargetingApi(params))
    /**************************************/

    // 设置地域
    useEffect(() => {
        initTargeting()
        // 获取账户列表
        getAllUserAccount.run()
    }, [])

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

    /** 编辑 复制 */
    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 delHandle = (id: number) => {
        delTargeting.run({ id }).then(res => {
            if (res) {
                message.success('删除成功')
                getTargetingList.refresh()
            }
        })
    }

    return <Card
        className="cardResetCss"
        title={<div className="flexStart" style={{ gap: 8 }}>
            <Input style={{ width: 180 }} placeholder="请输入关键字查找" value={queryParams?.targetingName} allowClear onChange={(e) => setQueryParams({ ...queryParams, targetingName: e.target.value, pageNum: 1 })} />
            <Select
                style={{ width: 180 }}
                showSearch
                filterOption={(input, option) =>
                    (option!.children as unknown as string)?.toLowerCase()?.includes(input?.toLowerCase())
                }
                allowClear
                value={queryParams?.taskType}
                onChange={(e) => setQueryParams({ ...queryParams, taskType: e })}
                placeholder='请选择模板投放类型'
            >
                <Select.Option value={"GAME"}>游戏</Select.Option>
                <Select.Option value={"NOVEL"}>小说</Select.Option>
            </Select>
            <Select
                style={{ width: 250 }}
                showSearch
                filterOption={(input, option) =>
                    (option!.children as unknown as string)?.toLowerCase()?.includes(input?.toLowerCase())
                }
                allowClear
                value={queryParams?.accountId}
                onChange={(e) => setQueryParams({ ...queryParams, accountId: e })}
                placeholder='请选择媒体账户'
            >
                {getAllUserAccount?.data?.data?.map((item: any) => <Select.Option value={item.accountId} key={item.id}>{item.remark ? item.accountId + '_' + item.remark : item.accountId}</Select.Option>)}
            </Select>
            <DatePicker.RangePicker style={{ width: 250 }} placeholder={['创建开始时间', '创建结束时间']} value={(queryParams?.min && queryParams?.max) ? [moment(queryParams?.min), moment(queryParams?.max)] as any : undefined} onChange={(_, option) => setQueryParams({ ...queryParams, min: option[0], max: option[1], pageNum: 1 })} />
            <Button type="primary" icon={<SearchOutlined />} loading={getTargetingList.loading} onClick={() => setQueryParamsNew({ ...queryParams })}>搜索</Button>
        </div>}
    >
        <div className="flexColumnStart" style={{ gap: 8 }}>
            <div>
                <Button type="primary" icon={<PlusOutlined />} onClick={() => setAddTemVisible(true)}>新增定向模板</Button>
            </div>
            <div>
                <Tables
                    columns={TableConfig(geoLocationList, modelList, editHandle, delHandle)}
                    dataSource={getTargetingList?.data?.records}
                    size="small"
                    loading={getTargetingList?.loading}
                    scroll={{ y: 650 }}
                    bordered
                    // rowSelection={{
                    //     type: 'checkbox',
                    //     selectedRowKeys: data[selectAdz - 1]?.userActionSetsList?.map((item: any) => item?.id?.toString()),
                    //     onChange: onChangeTable
                    // }}
                    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>


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


export default Targeting