import { Button, Card, Col, DatePicker, Form, Input, Row, Select, Space } from "antd"
import React, { useState } from "react"
import { PlusCircleOutlined, SearchOutlined } from "@ant-design/icons";
import moment from "moment";
import { COMMON_POTENTIAL_STATUS_ENUM, COMPONENT_GENERATION_TYPE_ENUM, DEFAULT_COMPONENT_SUB_IMAGE_TYPE, DEFAULT_COMPONENT_SUB_VIDEO_TYPE } from "../../tencenTasset/manageComponent/const";
import { DefaultOptionType } from "antd/lib/select";
import SelectCloudComponent from "./selectCloudComponent";

interface Props {
    type: 'image' | 'video'
    defaultParams: CLOUDNEW.DefaultParams
    accountId: number,
    componentSubType?: string[]
    onSearch?: (value: Partial<CLOUDNEW.GetMaterialListProps>) => void
    putInType?: 'NOVEL' | 'GAME'
}

// 选择素材搜索
const SelectComponentsUnitSearch: React.FC<Props> = ({ type, defaultParams, accountId, onSearch, componentSubType, putInType }) => {

    /**********************************/
    const [form] = Form.useForm();
    // const idList = Form.useWatch('idList', form)
    const [selectCloudData, setSelectCloudData] = useState<{
        defaultParams: {
            sizeQueries?: {
                width: number,
                height: number,
                relation: string
            }[],
            materialType: 'image' | 'video'
            fileSize: number
        }
        num: number
    }>()
    const [materialConfig, setMaterialConfig] = useState<{
        adcreativeTemplateId?: number,
        type: string,
        cloudSize: { relation: string, width: number, height: number }[],
        list: any[],
        index: number,
        max: number,
        sliderImgContent: any,
        isGroup?: boolean
    }>({
        type: '',//类型
        cloudSize: [],//素材搜索条件
        list: [],//素材
        index: 0, // 素材组下标
        max: 1,//素材数量
        sliderImgContent: undefined
    })//图片素材配置
    const [selectVideoVisible, setSelectVideoVisible] = useState(false)
    /**********************************/

    const handleOk = (values: any) => {
        console.log(values)
        let params: any = []
        Object.keys(values).forEach(key => {
            let value = values[key]
            if (['idList'].includes(key) && value !== undefined && value !== null) {
                let value1 = value.replace(/[,，\s]/g, ',')
                params[type === 'image' ? 'imageId' : 'videoId'] = value1.split(',').filter((a: any) => a)
            } else if (['componentIdSting'].includes(key) && value !== undefined && value !== null) {
                let value1 = value.replace(/[,，\s]/g, ',')
                params['componentId'] = value1.split(',').filter((a: any) => a)
            }
            if ('createTime' === key && value?.length === 2) {
                params.createTimeMin = moment(value?.[0]).format('YYYY-MM-DD')
                params.createTimeMax = moment(value?.[1]).format('YYYY-MM-DD')
            } else if ('costTime' === key && value?.length === 2) {
                params.costStartTime = moment(value?.[0]).format('YYYY-MM-DD')
                params.costEndTime = moment(value?.[1]).format('YYYY-MM-DD')
            } else {
                params[key] = value
            }
        })
        onSearch?.(params)
    }

    return <Card
        bodyStyle={{ padding: '5px 10px', overflow: 'auto hidden', display: 'flex', gap: 6, flexWrap: 'wrap' }}
        className="cardResetCss buttonResetCss"
        bordered
    >
        <Form
            layout="inline"
            name="basicSelectSearch"
            colon={false}
            form={form}
            onFinish={handleOk}
        >
            <Row gutter={[0, 6]}>
                <Col><Form.Item name={'componentCustomName'}>
                    <Input style={{ width: 100 }} allowClear placeholder="组件名称" />
                </Form.Item></Col>
                <Col><Form.Item name={'idList'}>
                    <Input
                        style={{ width: 220 }}
                        allowClear
                        placeholder="素材ID(多个空格or换行隔开)"
                        addonAfter={<PlusCircleOutlined
                            style={{ cursor: 'pointer' }}
                            onClick={() => {
                                setSelectCloudData({
                                    num: 100,
                                    defaultParams: defaultParams as any
                                })
                                setMaterialConfig({
                                    ...materialConfig,
                                    type: type,
                                    max: 100,
                                    index: 1,
                                    isGroup: false
                                })
                                setTimeout(() => {
                                    setSelectVideoVisible(true)
                                }, 100)
                            }}
                        />}
                    />
                </Form.Item></Col>
                <Col><Form.Item name={'componentIdSting'}>
                    <Input.TextArea rows={1} style={{ width: 190 }} allowClear placeholder="组件ID(多个空格or换行隔开)" />
                </Form.Item></Col>
                <Col><Form.Item name={'componentSubType'}>
                    <Select
                        showSearch
                        placeholder="二级组件类型"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                        }
                        style={{ minWidth: 120 }}
                        maxTagCount={1}
                        mode="multiple"
                        allowClear
                        options={(type === 'image' ? DEFAULT_COMPONENT_SUB_IMAGE_TYPE : DEFAULT_COMPONENT_SUB_VIDEO_TYPE).filter(item => componentSubType?.includes(item.value)) as DefaultOptionType[]}
                    />
                </Form.Item></Col>
                <Col><Form.Item name={'potentialStatus'}>
                    <Select
                        showSearch
                        placeholder="组件潜力"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                        }
                        style={{ minWidth: 100 }}
                        maxTagCount={1}
                        mode="multiple"
                        options={Object.keys(COMMON_POTENTIAL_STATUS_ENUM).map(key => ({ label: COMMON_POTENTIAL_STATUS_ENUM[key as keyof typeof COMMON_POTENTIAL_STATUS_ENUM], value: key }))}
                    />
                </Form.Item></Col>
                <Col><Form.Item name={'generationType'}>
                    <Select
                        showSearch
                        placeholder="来源"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                        }
                        style={{ minWidth: 100 }}
                        maxTagCount={1}
                        mode="multiple"
                        options={Object.keys(COMPONENT_GENERATION_TYPE_ENUM).map(key => ({ label: COMPONENT_GENERATION_TYPE_ENUM[key as keyof typeof COMPONENT_GENERATION_TYPE_ENUM], value: key }))}
                    />
                </Form.Item></Col>
                <Col><Form.Item name={'createTime'}>
                    <DatePicker.RangePicker style={{ width: 260 }} placeholder={['创建时间开始', '创建时间结束']} />
                </Form.Item></Col>
                <Col><Form.Item name={'costTime'}>
                    <DatePicker.RangePicker style={{ width: 260 }} placeholder={['消耗时间开始', '消耗时间结束']} />
                </Form.Item></Col>
                <Col><Form.Item>
                    <Space>
                        <Button onClick={() => form.resetFields()}>重置</Button>
                        <Button type="primary" htmlType="submit" icon={<SearchOutlined />} className="modalResetCss">搜索</Button>
                    </Space>
                </Form.Item></Col>
            </Row>
        </Form>

        {/* 选择素材 */}
        {(selectVideoVisible && selectCloudData) && <SelectCloudComponent
            {...selectCloudData}
            tabType={['1']}
            accountCreateLogs={[{ accountId: accountId }]}
            visible={selectVideoVisible}
            isGroup={materialConfig?.isGroup}
            onClose={() => {
                setSelectVideoVisible(false)
                setSelectCloudData(undefined)
            }}
            putInType={putInType}
            title="选择素材查找"
            onChange={(content: any) => {
                if (content?.length > 0) {
                    const idList = content?.map((item: any) => item.id)?.toString()
                    form.setFieldsValue({ idList })
                }
                setSelectVideoVisible(false)
                setSelectCloudData(undefined)
            }}
        />}
    </Card>
}

export default React.memo(SelectComponentsUnitSearch)