import { useAjax } from "@/Hook/useAjax"
import { getCreativeReportApi, getMaterialDetailApi, getReportMaterialDetailApi, updateMaterialApi } from "@/services/adqV3/cloudNew"
import { Button, Card, DatePicker, Divider, Drawer, Input, InputNumber, message, Popover, Space, Spin, Statistic, Table, Tag, Typography } from "antd"
import React, { useEffect, useState } from "react"
import '../../tencentAdPutIn/index.less'
import style from './index.less'
import { formatBytes, formatSecondsToTime } from "@/utils/utils"
import moment from "moment"
import { DownOutlined, EditOutlined } from "@ant-design/icons"
import columns from "./tableConfig"
const { Title, Text, Paragraph } = Typography;


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

/**
 * 素材详情
 * @param param0 
 * @returns 
 */
const Details: React.FC<Props> = ({ data, visible, onClose, onChange }) => {

    /************************************/
    const [detailsData, setDetailsData] = useState<any>({})
    const [dataOverview, setDataOverview] = useState<{ conversions_cost: number | null, conversions_count: number | null, conversions_rate: number | null, cost: number | null, ctr: number | null }>({ conversions_cost: null, conversions_count: null, conversions_rate: null, cost: null, ctr: null })
    const [dataOverviewParams, setDataOverviewParams] = useState<{ dataTimeMix?: string, dataTimeMax?: string }>({ dataTimeMix: moment().subtract(12, 'months').format('YYYY-MM-DD'), dataTimeMax: moment().format('YYYY-MM-DD') })
    const [dynimicParams, setDynimicParams] = useState<CLOUDNEW.GetCreativeReport>({ pageNum: 1, pageSize: 20 })
    const [openDynimic, setOpenDynimic] = useState<boolean>(false)
    const [oldLastDay, setOldLastDay] = useState<number>(30)
    const [lastDay, setLastDay] = useState<number>(30)
    const [updateDayVisible, setUpdateDayVisible] = useState<boolean>(false)

    const getMaterialDetail = useAjax((params) => getMaterialDetailApi(params))
    const getReportMaterialDetail = useAjax((params) => getReportMaterialDetailApi(params))
    const updateMaterial = useAjax((params) => updateMaterialApi(params))
    const getCreativeReport = useAjax((params) => getCreativeReportApi(params))
    /************************************/

    useEffect(() => {
        getDetails()
    }, [data])

    useEffect(() => {
        getReportMaterialDetail.run({ ...dataOverviewParams, signature: data.md5 }).then(res => {
            setDataOverview(res || { conversions_cost: null, conversions_count: null, conversions_rate: null, cost: null, ctr: null })
        })
    }, [data, dataOverviewParams])

    // 创意列表
    useEffect(() => {
        if (openDynimic) {
            getCreativeReport.run({ ...dataOverviewParams, ...dynimicParams, signature: data.md5, creativeTimeMin: moment().subtract(lastDay, 'day').format('YYYY-MM-DD'), creativeTimeMax: moment().format('YYYY-MM-DD') })
        }
    }, [dynimicParams, data, dataOverviewParams, lastDay, openDynimic])

    // 获取素材详情
    const getDetails = (isChange?: boolean) => {
        getMaterialDetail.run({ id: data.id }).then(res => {
            if (res) {
                setDetailsData(res)
                if (isChange) {
                    onChange?.()
                }
            }
        })
    }

    // 修改名称
    const onSetEditable = (value: { materialName: string, description?: string }, fiele: string) => {
        if (fiele === 'materialName' && !value.materialName) {
            return
        }
        if (value[fiele as keyof typeof value] !== detailsData[fiele]) {
            updateMaterial.run({ ...value, id: detailsData.id }).then(res => {
                if (res) {
                    getDetails(true)
                    message.success('修改成功')
                }
            })
        }
    }

    return <Drawer
        title={<strong>{data.materialName} 素材详情</strong>}
        placement="right"
        onClose={onClose}
        open={visible}
        width={1000}
        headerStyle={{ padding: '10px 16px' }}
        maskClosable={false}
        className={`modalResetCss targetingSelect`}
        bodyStyle={{ overflow: 'auto' }}
    >
        <div className={style.file_details}>
            <Card
                title={<strong>基础信息</strong>}
                className={`cardResetCss 
                ${style.details_left}`}
            >
                <Spin spinning={getMaterialDetail.loading}>
                    <div style={{ minHeight: 350 }}>
                        {detailsData?.materialType === 'image' ? <img src={detailsData.ossUrl} /> : <video src={detailsData.ossUrl} controls></video>}
                        <Title level={5} ellipsis editable={{ onChange: (value) => onSetEditable({ materialName: value, description: detailsData?.description }, 'materialName') }}>{detailsData.materialName}</Title>
                        <Divider />
                        <ul className={style.details_xq}>
                            <li>
                                <span>创建时间</span>
                                <span>{detailsData?.createTime}</span>
                            </li>
                            <li>
                                <span>大小</span>
                                <span>{formatBytes(detailsData?.fileSize)}</span>
                            </li>
                            <li>
                                <span>尺寸</span>
                                <span>{detailsData?.width} * {detailsData?.height}</span>
                            </li>
                            {detailsData?.materialType === 'video' && <>
                                <li>
                                    <span>时长</span>
                                    <span>{formatSecondsToTime(Math.floor(detailsData?.videoDuration))}</span>
                                </li>
                            </>}
                            <li>
                                <span>备注</span>
                                <div><Text editable={{
                                    onChange: (value) => onSetEditable({ materialName: detailsData.materialName, description: value }, 'description')
                                }} ellipsis>{detailsData?.description || '--'}</Text></div>
                            </li>
                        </ul>
                    </div>
                </Spin>
            </Card>
            <div className={style.details_right}>
                <Card
                    className="cardResetCss"
                    title={<strong>数据概览</strong>}
                    extra={<DatePicker.RangePicker
                        ranges={{
                            '此刻': [moment(), moment()],
                            '昨天': [moment().subtract(1, 'day'), moment().subtract(1, 'day')],
                            '近7天': [moment().subtract(7, 'day'), moment()],
                            '本月': [moment().startOf('month'), moment()],
                            '上月': [moment().subtract(1, 'months').startOf('month'), moment().subtract(1, 'months').endOf('month')],
                        }}
                        style={{ width: 230 }}
                        value={(dataOverviewParams?.dataTimeMix && dataOverviewParams?.dataTimeMax) ? [moment(dataOverviewParams?.dataTimeMix), moment(dataOverviewParams?.dataTimeMax)] : undefined}
                        onChange={(_, option) => setDataOverviewParams({ dataTimeMix: option[0], dataTimeMax: option[1] })}
                    />}
                >
                    <Spin spinning={getReportMaterialDetail.loading}>
                        <div style={{ display: 'flex', gap: 10 }}>
                            <Card style={{ flex: 1, overflow: 'hidden' }} bordered={false} bodyStyle={{ backgroundColor: '#f6ffed' }} className="cardResetCss">
                                <Statistic
                                    title={<strong style={{ color: '#52c41a' }}>消耗</strong>}
                                    value={dataOverview?.cost === null ? '--' : dataOverview?.cost || 0}
                                    precision={2}
                                    valueStyle={{ color: '#52c41a' }}
                                />
                            </Card>
                            <Card style={{ flex: 1, overflow: 'hidden' }} bordered={false} bodyStyle={{ backgroundColor: '#e6f7ff' }} className="cardResetCss">
                                <Statistic
                                    title={<strong style={{ color: '#40a9ff' }}>转化成本</strong>}
                                    value={dataOverview?.conversions_cost === null ? '--' : dataOverview?.conversions_cost || 0}
                                    precision={2}
                                    valueStyle={{ color: '#40a9ff' }}
                                />
                            </Card>
                            <Card style={{ flex: 1, overflow: 'hidden' }} bordered={false} bodyStyle={{ backgroundColor: '#fff0f6' }} className="cardResetCss">
                                <Statistic
                                    title={<strong style={{ color: '#f759ab' }}>点击率</strong>}
                                    value={dataOverview?.ctr === null ? '--' : (dataOverview?.ctr || 0) * 100}
                                    precision={2}
                                    valueStyle={{ color: '#f759ab' }}
                                    suffix={dataOverview?.ctr === null ? undefined : '%'}
                                />
                            </Card>
                            <Card style={{ flex: 1, overflow: 'hidden' }} bordered={false} bodyStyle={{ backgroundColor: '#f9f0ff' }} className="cardResetCss">
                                <Statistic
                                    title={<strong style={{ color: '#9254de' }}>转化率</strong>}
                                    value={dataOverview?.conversions_rate === null ? '--' : (dataOverview?.conversions_rate || 0) * 100}
                                    precision={2}
                                    valueStyle={{ color: '#9254de' }}
                                    suffix={dataOverview?.conversions_rate === null ? undefined : '%'}
                                />
                            </Card>
                            <Card style={{ flex: 1, overflow: 'hidden' }} bordered={false} bodyStyle={{ backgroundColor: '#f0f5ff' }} className="cardResetCss">
                                <Statistic
                                    title={<strong style={{ color: '#597ef7' }}>转化量</strong>}
                                    value={dataOverview?.conversions_count === null ? '--' : dataOverview?.conversions_count || 0}
                                    valueStyle={{ color: '#597ef7' }}
                                />
                            </Card>
                        </div>
                    </Spin>
                </Card>
                <Card
                    className="cardResetCss"
                    title={<strong>
                        最近{lastDay}天创建的创意
                        <Popover
                            onOpenChange={(e) => {
                                setUpdateDayVisible(e)
                                if (e)
                                    setOldLastDay(lastDay)
                            }}
                            trigger={['click']}
                            open={updateDayVisible}
                            content={<div>
                                <Title level={5} style={{ fontSize: 12 }}>请设置创建时间范围</Title>
                                <Space>
                                    <InputNumber min={1} max={30} style={{ width: 300 }} value={oldLastDay} onChange={(value) => setOldLastDay(value || 1)} />
                                    <Button
                                        type="primary"
                                        onClick={() => {
                                            setLastDay(oldLastDay);
                                            setUpdateDayVisible(false)
                                        }}
                                    >
                                        确定
                                    </Button>
                                </Space>
                                <Paragraph style={{ marginTop: 10, fontSize: 12 }}>修改后，创建时间在最近{oldLastDay}天的关联广告信息被显示</Paragraph>
                            </div>}
                            title={<strong style={{ fontSize: 14 }}>调整创意创建时间范围</strong>}
                        >
                            <Button type="link"><EditOutlined /></Button>
                        </Popover>
                    </strong>}
                >
                    {
                        openDynimic ?
                            <Table
                                columns={columns()}
                                dataSource={getCreativeReport?.data?.records}
                                size="small"
                                bordered
                                loading={getCreativeReport.loading}
                                rowKey={'dynamic_creative_id'}
                                scroll={{ x: 1000, y: 500 }}
                                pagination={{
                                    current: getCreativeReport?.data?.current || 1,
                                    pageSize: getCreativeReport?.data?.size || 20,
                                    total: getCreativeReport?.data?.total || 0,
                                    showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                                    showSizeChanger: true
                                }}
                                onChange={(pagination, filters, sorter: any) => {
                                    console.log(pagination, sorter)
                                    let { current, pageSize } = pagination
                                    let newDynimicParams = JSON.parse(JSON.stringify(dynimicParams))
                                    if (sorter && sorter?.order) {
                                        newDynimicParams['sortType'] = sorter?.order === 'ascend' ? true : false
                                        newDynimicParams['sortFiled'] = sorter?.field
                                    } else {
                                        delete newDynimicParams['sortType']
                                        delete newDynimicParams['sortFiled']
                                    }
                                    newDynimicParams.pageNum = current || newDynimicParams.pageNum
                                    newDynimicParams.pageSize = pageSize || newDynimicParams.pageSize
                                    setDynimicParams({ ...newDynimicParams })
                                }}
                            />
                            : <Button style={{ width: '100%' }} type="primary" onClick={() => { setOpenDynimic(true) }}>点击展开查看 <DownOutlined /></Button>
                    }
                </Card>
            </div>
        </div>
    </Drawer>
}

export default React.memo(Details)