import { Button, Card, Drawer, Input, Space, Typography, message } from "antd"
import React, { useEffect, useState } from "react"
import style from './index.less'
import './global.less'
import { CheckOutlined, CloseOutlined, PlusOutlined, SearchOutlined, UndoOutlined } from "@ant-design/icons";
import { useAjax } from "@/Hook/useAjax";
import Tables from "@/components/Tables";
import { TableConfig } from "./tableConfig";
import { randomString } from "@/utils/utils";
import NewFilterUser from "./newFiterUser";
import dayjs from "dayjs"
import { delSiftPopulationConfigApi, getSiftPopulationConfigApi } from "../../API/businessPlan/filterUser";
const { Title, Text } = Typography;

interface Props {
    configType: BUSINES_SPLAN_API.ConfigTypeProps
    bookCityList: { label: string, value: string }[]
    value?: any,
    visible?: boolean
    onClose?: () => void
    onChange?: (value: any) => void
}

/**
 * 选择人群包
 * @param param0 
 * @returns 
 */
const SelectFilterUser: React.FC<Props> = ({ configType, bookCityList, value = [], visible, onChange, onClose }) => {

    /*****************************/
    const [addTemVisible, setAddTemVisible] = useState<boolean>(false)
    const [queryParams, setQueryParams] = useState<BUSINES_SPLAN_API.GetSiftPopulationConfigProps>({ pageNum: 1, pageSize: 20, configType })
    const [queryParamsNew, setQueryParamsNew] = useState<BUSINES_SPLAN_API.GetSiftPopulationConfigProps>({ pageNum: 1, pageSize: 20, configType })

    const [modifyDta, setModifyDta] = useState<any>()
    const [selectedTargetKeys, setSelectedTargetKeys] = useState<any[]>(value)

    const getSiftPopulationConfig = useAjax((params) => getSiftPopulationConfigApi(params))
    const delSiftPopulationConfig = useAjax((params) => delSiftPopulationConfigApi(params))
    /*****************************/

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

    /** 编辑 复制 */
    const editHandle = (data: any, isCopy?: boolean) => {
        const { configName, configContent, id } = data
        const { condLastRechargeTimeMin, condLastRechargeTimeMax, condBeginTime, condEndTime, ...content } = JSON.parse(configContent)
        let newModifyDta = {
            ...content,
            configName,
        }
        if (condLastRechargeTimeMin && condLastRechargeTimeMax) {
            newModifyDta['lastRechargeTime'] = [dayjs(condLastRechargeTimeMin), dayjs(condLastRechargeTimeMax)]
        }
        if (condBeginTime) {
            newModifyDta['condBeginTime'] = dayjs(condBeginTime)
        }
        if (condEndTime) {
            newModifyDta['condEndTime'] = dayjs(condEndTime)
        }
        if (!isCopy) {
            newModifyDta.id = id
        } else {
            newModifyDta.configName = newModifyDta.configName + `_副本${randomString(true, 3, 5)}`
            newModifyDta.isCopy = isCopy
        }
        setModifyDta(newModifyDta)
        setAddTemVisible(true)
    }

    const handleOk = () => {
        if (selectedTargetKeys?.length > 0) {
            const { configName, id, configContent } = selectedTargetKeys[0]
            console.log(configName, id, configContent)
            onChange?.({ configName, id, configContent: JSON.parse(configContent) })
        } else {
            message.error('请选择定向模板')
        }
    }

    const delHandle = (id: number) => {
        delSiftPopulationConfig.run(id).then((res) => {
            if (res?.data) {
                message.success('删除成功')
                getSiftPopulationConfig.run(queryParamsNew)
            }
        })
    }


    return <Drawer
        title={<strong style={{ fontSize: 20 }}>{configType === 'GROUP_GROUP' ? '群' : '用户'}人群包模板</strong>}
        open={visible}
        onClose={onClose}
        width={1200}
        styles={{header: { padding: '10px 16px' }}}
        maskClosable={false}
        className={`modalResetCss targetingSelect`}
    >
        <Card className="cardResetCss" style={{ backgroundColor: '#FFF' }} styles={{ body: { padding: 0, height: 'calc(100vh - 130px)', overflow: 'hidden', overflowY: 'auto' } }}>
            <div className="flexColumnStart" style={{ height: '100%' }}>
                <div className={style.template}>
                    <div className={style.template_center}>
                        <div className="flexSpaceBetween" style={{ marginBottom: 10 }}>
                            <Space>
                                <Input placeholder="请输入人群包模板名称" value={queryParams?.configName} allowClear onChange={(e) => setQueryParams({ ...queryParams, configName: e.target.value, pageNum: 1 })} />
                                <Button type="primary" icon={<SearchOutlined />} loading={false} onClick={() => setQueryParamsNew({ ...queryParams })}>搜索</Button>
                            </Space>
                            <Space>
                                <Button type="primary" icon={<PlusOutlined />} onClick={() => setAddTemVisible(true)}>新增{configType === 'GROUP_GROUP' ? '群' : '用户'}人群包模板</Button>
                            </Space>
                        </div>
                        <Tables
                            columns={TableConfig(editHandle, delHandle, bookCityList)}
                            dataSource={getSiftPopulationConfig?.data?.data?.records}
                            size="small"
                            loading={getSiftPopulationConfig?.loading}
                            scroll={{ y: 320 }}
                            bordered
                            rowSelection={{
                                type: 'radio',
                                selectedRowKeys: selectedTargetKeys?.map((item: any) => item?.id?.toString()),
                                onChange: (_: React.Key[], selectedRows: any) => {
                                    setSelectedTargetKeys(selectedRows)
                                }
                            }}
                            total={getSiftPopulationConfig?.data?.data?.total}
                            defaultPageSize={20}
                            current={getSiftPopulationConfig?.data?.data?.current}
                            pageSize={getSiftPopulationConfig?.data?.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={{ margin: 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.configName}</Text>
                                <Button type="link" className={style.clear} size="small" 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, backgroundColor: '#FFF' }} styles={{ body: { display: 'flex', padding: 10, justifyContent: 'center', gap: 10 } }}>
            <Button onClick={onClose}>取消</Button>
            <Button type="primary" onClick={() => handleOk()}>确定</Button>
        </Card>

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

    </Drawer>
}

export default React.memo(SelectFilterUser)