import React, { useEffect, useState } from "react"
import style from './index.less'
import { Button, Card, Checkbox, Divider, Empty, Form, message, Pagination, Popover, Radio, Result, Select, Space, Spin, Typography, Image } from "antd"
import { useAjax } from "@/Hook/useAjax"
import { getPageRemoteImageDataListApi } from "@/services/adqV3/cloudNew"
import { formatBytes, formatSecondsToTime, groupBy } from "@/utils/utils"
import SelectGroupSearch from "./selectGroupSearch"
import './global.less'
import '../../tencentAdPutIn/index.less'
import { showField1List } from "./const"
import { EyeOutlined, SortAscendingOutlined } from "@ant-design/icons"
import PlayVideo from "./playVideo"
import Lazyimg from "react-lazyimg-component"
import { useLocalStorageState } from "ahooks"
import SyncCloudSc from "./syncCloudSc"
import { getUserAccountListApi } from "@/services/launchAdq/adAuthorize"

const { Text, Paragraph } = Typography;

/**
 * 选择账户组媒体素材
 * @param param0 
 * @returns 
 */
const SelectGroupCloudNew: React.FC<CLOUDNEW.SelectGroupCloudNewProps> = ({ num, defaultParams, checkedFolderList, setCheckedFolderList, accountCreateLogs, putInType }) => {

    /*****************************************/
    const [rowNum, setRowNum] = useState<number>(0)

    const [checkFolderAll, setCheckFolderAll] = useState<boolean>(false);
    const [indeterminateFolder, setIndeterminateFolder] = useState<boolean>(false);

    const [queryParams, setQueryParams] = useState<Omit<CLOUDNEW.GetPageRemoteImageDataListProps, 'materialType'>>({ pageNum: 1, pageSize: 20 })
    const [searchParams, setSearchParams] = useState<Partial<Omit<CLOUDNEW.GetPageRemoteImageDataListProps, 'materialType'>>>({})
    const [ownerAccountId, setOwnerAccountId] = useState<number>()
    const [previewData, setPreviewData] = useState<{ visible: boolean, url?: string }>({ visible: false })
    const [sortData, setSortData] = useLocalStorageState<{ sortField: string | undefined, sortType: boolean }>('sort-data-group', { sortField: undefined, sortType: false });
    const [showField, setShowField] = useLocalStorageState<string[]>('show-field-group', ['material.create_time', 'material_data_day.cost', 'material_data_day.ctr', 'material_data_day.conversions_rate', 'material_data_day.dynamic_creative_count']);

    const getPageRemoteImageDataList = useAjax((params) => getPageRemoteImageDataListApi(params))
    const getUserAccountList = useAjax((params) => getUserAccountListApi(params))
    /*****************************************/

    // 根据内容宽度计算列数
    useEffect(() => {
        let rowNum = Math.floor(1350 / 220)
        setRowNum(rowNum || 1)
    }, [])

    // 处理全选按钮状态
    useEffect(() => {
        let data: any[] = getPageRemoteImageDataList?.data?.records || []
        let dataIds = data.map(item => item.image_id || item.video_id)
        let selectIds = checkedFolderList.map(item => item.id)
        if (selectIds.length === 0 || dataIds.length === 0) {
            setCheckFolderAll(false)
            setIndeterminateFolder(false);
        } else if (dataIds.every((element) => selectIds.includes(element))) {
            setCheckFolderAll(true)
            setIndeterminateFolder(false);
        } else if (dataIds.some((element) => selectIds.includes(element))) {
            setCheckFolderAll(false)
            setIndeterminateFolder(true);
        } else {
            setCheckFolderAll(false)
            setIndeterminateFolder(false);
        }
    }, [checkedFolderList, getPageRemoteImageDataList?.data?.records])

    useEffect(() => {
        if (accountCreateLogs?.length) {
            getUserAccountList.run({ adUnitTypeList: putInType === 'NOVEL' ? ['NOVEL', 'NOVEL_IAA', 'SKIT_IAA'] : ['GAME', 'GAME_IAA'], pageNum: 1, pageSize: 20000, accountIdList: accountCreateLogs.map(item => item.accountId) }).then(res => {
                if (res?.records?.length) {
                    const list = accountCreateLogs.map(item => item.accountId)
                    const selectAccountList = res.records.filter((item: { accountId: any }) => list.includes(item.accountId))
                    const groupAccount = groupBy(selectAccountList, (item) => item.groupId, true)
                    const GrounpArray = Object.keys(groupAccount).map(function (group) {
                        return groupAccount[group];
                    })
                    if (GrounpArray.length === 1 && !groupAccount['undefined']) {
                        setOwnerAccountId(GrounpArray?.[0]?.[0]?.authMainAccountId || GrounpArray?.[0]?.[0]?.accountId)
                    } else if (GrounpArray.length === 2 && groupAccount?.['undefined']?.length === 1) {
                        const undefinedAccount = groupAccount?.['undefined'][0].accountId
                        let authMainAccountId: any
                        Object.keys(groupAccount).forEach(key => {
                            if (key !== 'undefined') {
                                authMainAccountId = groupAccount[key][0].authMainAccountId
                            }
                        })
                        if (undefinedAccount === authMainAccountId) {
                            setOwnerAccountId(authMainAccountId)
                        } else {
                            setOwnerAccountId(-1)
                        }
                    } else if (groupAccount?.['undefined']?.length === 1 && groupAccount?.['undefined']?.[0]?.isGroupMainAccount) {
                        setOwnerAccountId(groupAccount?.['undefined']?.[0]?.accountId)
                    } else {
                        setOwnerAccountId(-1)
                    }
                }
            })
        }
    }, [accountCreateLogs])

    useEffect(() => {
        if (ownerAccountId) {
            let params = { ...searchParams, ...defaultParams, ...queryParams, ownerAccountId }
            if (sortData?.sortField) {
                params = { ...params, ...sortData }
            }
            getPageRemoteImageDataList.run(params)
        }
    }, [queryParams, defaultParams, searchParams, sortData, showField, ownerAccountId])

    // 选择
    const onCheckboxChange = (checked: boolean, item: any) => {
        let newCheckedFolderList: any[] = JSON.parse(JSON.stringify(checkedFolderList))
        if (checked) { // 选中
            newCheckedFolderList.push({ ...item, id: item.image_id || item.video_id, material_type: defaultParams.materialType, oss_url: item.preview_url, materialType: 1 })
        } else { // 取消
            let id = item.image_id || item.video_id
            newCheckedFolderList = newCheckedFolderList.filter(i => i.id !== id)
        }
        setCheckedFolderList(newCheckedFolderList)
    };

    return <Spin spinning={getUserAccountList.loading} wrapperClassName={'select_group_spin'}>
        <div className={style.select_cloudNew_layout}>
            {ownerAccountId && ownerAccountId !== -1 ? <>
                {/* 搜索 */}
                <SelectGroupSearch
                    type={defaultParams.materialType}
                    onSearch={(value) => { setSearchParams(value) }}
                />
                <Card
                    style={{ height: '100%', flex: '1 0', overflow: 'hidden' }}
                    bodyStyle={{ padding: 0, overflow: 'auto hidden', height: '100%' }}
                    className="cardResetCss buttonResetCss"
                    bordered
                >
                    <div className={style.cloudNew}>
                        <div className={style.material} style={{ height: '100%' }}>
                            <div className={style.operates}>
                                <div className={style.left_bts}>
                                    <Checkbox
                                        onChange={(e) => {
                                            let newCheckedFolderList: any[] = JSON.parse(JSON.stringify(checkedFolderList))
                                            const data: any[] = getPageRemoteImageDataList?.data?.records

                                            if (e.target.checked) { // 全选
                                                const selectIds = newCheckedFolderList.map(item => item.id)
                                                const remainData = data.filter(item => {
                                                    const id = item.image_id || item.video_id
                                                    return !selectIds.includes(id)
                                                })
                                                const remainDataLength = remainData.length
                                                const remainNum = num - newCheckedFolderList.length
                                                if (remainNum > remainDataLength) {
                                                    newCheckedFolderList.push(...remainData.map(i => ({ ...i, material_type: defaultParams.materialType, id: i.image_id || i.video_id, oss_url: i.preview_url, materialType: 1 })))
                                                } else {
                                                    newCheckedFolderList.push(...remainData.splice(0, remainNum).map(i => ({ ...i, material_type: defaultParams.materialType, id: i.image_id || i.video_id, oss_url: i.preview_url, materialType: 1 })))
                                                }
                                                newCheckedFolderList = Array.from(new Set(newCheckedFolderList.map(item => JSON.stringify(item)))).map(item => JSON.parse(item));
                                            } else { // 取消全选
                                                const dataIds = data.map(item => item.image_id || item.video_id)
                                                newCheckedFolderList = newCheckedFolderList.filter(i => !dataIds.includes(i.id))
                                            }
                                            setCheckedFolderList(newCheckedFolderList)
                                        }}
                                        disabled={checkedFolderList?.length >= num}
                                        indeterminate={indeterminateFolder}
                                        checked={checkFolderAll}
                                    >全选</Checkbox>
                                    <span>已选 <span style={{ color: '#1890FF' }}>{checkedFolderList?.length || 0}</span>/{num} 个素材</span>
                                    {checkedFolderList.length > 0 && <a style={{ color: 'red' }} onClick={() => setCheckedFolderList([])}>清除所有</a>}
                                    {sortData?.sortField && <Text>「排序-{showField1List.find(item => item.value === sortData.sortField)?.label}-{sortData.sortType ? '正序' : '倒序'}」</Text>}
                                    {/* 同步素材 */}
                                    <SyncCloudSc
                                        accountId={ownerAccountId}
                                    />
                                </div>
                                <div className={style.left_bts}>
                                    <Popover
                                        content={<div style={{ width: 320 }}>
                                            <Form
                                                labelCol={{ span: 5 }}
                                                labelAlign="left"
                                                colon={false}
                                            >
                                                <Form.Item label={<strong>展示指标</strong>}>
                                                    <Select
                                                        placeholder="选择展示指标"
                                                        showSearch
                                                        filterOption={(input, option) =>
                                                            (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                        }
                                                        mode="multiple"
                                                        options={showField1List}
                                                        value={showField}
                                                        onChange={(value) => {
                                                            if (value.length > 6) {
                                                                message.warn('最多只能选择6个指标')
                                                                return
                                                            }
                                                            if (value.length < 1) {
                                                                message.warn('最少选择1个指标')
                                                                return
                                                            }
                                                            setSortData({ ...sortData, sortField: undefined })
                                                            setShowField(value as any)
                                                        }}
                                                    />
                                                </Form.Item>
                                                <Form.Item label={<strong>排序</strong>}>
                                                    <Space>
                                                        <Select
                                                            style={{ width: 125 }}
                                                            placeholder="选择排序指标"
                                                            showSearch
                                                            filterOption={(input, option) =>
                                                                (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                            }
                                                            options={showField1List.filter(item => showField.includes(item.value) && item.value !== 'description')}
                                                            value={sortData.sortField}
                                                            allowClear
                                                            onChange={(value) => {
                                                                setSortData({ ...sortData, sortField: value as any })
                                                            }}
                                                        />
                                                        <Radio.Group value={sortData.sortType} onChange={(e) => setSortData({ ...sortData, sortType: e.target.value })} buttonStyle="solid">
                                                            <Radio.Button value={true}>正序</Radio.Button>
                                                            <Radio.Button value={false}>倒序</Radio.Button>
                                                        </Radio.Group>
                                                    </Space>
                                                </Form.Item>
                                            </Form>
                                        </div>}
                                        trigger={['click']}
                                        title={<strong>自定义展示指标与排序</strong>}
                                        placement="bottomRight"
                                    >
                                        <Button icon={<SortAscendingOutlined />}>自定义展示指标与排序</Button>
                                    </Popover>
                                </div>
                            </div>
                            <div className={`${style.content} content_global`}>
                                <Spin spinning={getPageRemoteImageDataList.loading}>
                                    <div className={`${style.content_scroll} scroll`}>
                                        {getPageRemoteImageDataList?.data?.records?.length > 0 ? <Checkbox.Group value={checkedFolderList?.map(item => item.id)} style={{ width: '100%' }}>
                                            <div className={style.content_scroll_div}>
                                                {getPageRemoteImageDataList?.data?.records.map((item: any) => {
                                                    let id = defaultParams.materialType === 'image' ? item.image_id : item.video_id
                                                    const isSelect = checkedFolderList?.map(item => item.id).includes(id)
                                                    const disabled = checkedFolderList.length >= num && !isSelect
                                                    return <div key={id} className={style.content_row} style={{ width: rowNum ? (1 / rowNum * 100) + '%' : 220 }}>
                                                        <Card
                                                            hoverable
                                                            bodyStyle={{ padding: 0 }}
                                                            style={{ cursor: disabled ? 'not-allowed' : 'pointer' }}
                                                            className={`${style.content_col}`}
                                                            cover={<div style={{ height: 120, padding: 0 }} className={style.content_cover}>
                                                                <div className={style.checkbox}><Checkbox disabled={disabled} value={id} onChange={(e) => onCheckboxChange(e.target.checked, item)} /></div>
                                                                {defaultParams.materialType === 'video' ? <div className={style.playr}>
                                                                    <PlayVideo videoUrl={item.preview_url}>{(onPlay) => <img onClick={(e) => {
                                                                        e.stopPropagation(); e.preventDefault()
                                                                        onPlay()
                                                                    }} src={require('../../../../../public/image/play.png')} alt="" />}</PlayVideo>
                                                                </div> : <div className={style.imgPreview} onClick={(e) => {
                                                                    e.stopPropagation()
                                                                    setPreviewData({ visible: true, url: item.preview_url })
                                                                }}>
                                                                    <Space><EyeOutlined /><span>预览</span></Space>
                                                                </div>}
                                                                <div className={style.file_info}>
                                                                    <div>{item.width}*{item.height}</div>
                                                                    {defaultParams.materialType === 'video' && item.image_duration_millisecond && <div>{formatSecondsToTime(Math.floor(item.image_duration_millisecond / 1000))}</div>}
                                                                </div>
                                                                <Lazyimg
                                                                    animateType="transition"
                                                                    src={defaultParams.materialType === 'image' ? item.preview_url : item?.key_frame_image_url}
                                                                    className={`${style.coverImg} lazy`}
                                                                    animateClassName={['transition-enter', 'transition-enter-active']}
                                                                />
                                                            </div>}
                                                            onClick={() => !disabled && onCheckboxChange(!isSelect, item)}
                                                        >
                                                            <div className={style.body}>
                                                                <Text ellipsis strong style={{ flex: '1 0' }}>{item?.material_name}</Text>
                                                                <Text style={{ fontSize: 12 }}>{formatBytes(item?.file_size)}</Text>
                                                            </div>
                                                            <Divider style={{ margin: '0 0 4px 0' }} />
                                                            <div style={{ padding: '0 10px 6px' }}>
                                                                {showField.map(field => {
                                                                    switch (field) {
                                                                        case 'material.created_time':
                                                                            return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>创建时间：{item?.created_time}</Paragraph>
                                                                        case 'material_data_day.cost':
                                                                            return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>消耗：{(item?.cost === null || item?.cost === undefined) ? '--' : item?.cost}</Paragraph>
                                                                        case 'material_data_day.order_pv':
                                                                            return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>下单次数：{(item?.order_pv === null || item?.order_pv === undefined) ? '--' : item?.order_pv}</Paragraph>
                                                                        case 'material_data_day.order_cost':
                                                                            return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>下单成本：{(item?.order_cost === null || item?.order_cost === undefined) ? '--' : item?.order_cost}</Paragraph>
                                                                        case 'material_data_day.ctr':
                                                                            return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>点击率：{(item?.ctr === null || item?.ctr === undefined) ? '--' : (item?.ctr * 100).toFixed(2) + '%'}</Paragraph>
                                                                        case 'material_data_day.conversions_rate':
                                                                            return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>目标转化率：{(item?.conversions_rate === null || item?.conversions_rate === undefined) ? '--' : (item?.conversions_rate * 100).toFixed(2) + '%'}</Paragraph>
                                                                        case 'material_data_day.adgroup_count':
                                                                            return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>广告关联数：{(item?.adgroup_count === null || item?.adgroup_count === undefined) ? '--' : item?.adgroup_count}</Paragraph>
                                                                        case 'material_data_day.dynamic_creative_count':
                                                                            return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>创意关联数：{(item?.dynamic_creative_count === null || item?.dynamic_creative_count === undefined) ? '--' : item?.dynamic_creative_count}</Paragraph>
                                                                        default:
                                                                            return null
                                                                    }
                                                                })}
                                                                {showField.includes('description') && <Paragraph style={{ fontSize: 12, marginBottom: 1 }} ellipsis={{ tooltip: true }}>备注：{item.description || '--'}</Paragraph>}
                                                            </div>
                                                        </Card>
                                                    </div>
                                                })}
                                            </div>
                                        </Checkbox.Group> : <div style={{ height: '100%', width: '100%', alignContent: 'center' }}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></div>}
                                    </div>
                                </Spin>
                            </div>
                            <div className={style.fotter}>
                                <Pagination
                                    size="small"
                                    total={getPageRemoteImageDataList?.data?.total || 0}
                                    showSizeChanger
                                    showQuickJumper
                                    pageSize={getPageRemoteImageDataList?.data?.size || 20}
                                    current={getPageRemoteImageDataList?.data?.current || 1}
                                    onChange={(page: number, pageSize: number) => {
                                        setQueryParams({ ...queryParams, pageNum: page, pageSize })
                                    }}
                                    pageSizeOptions={[10, 15, 20, 50, 100]}
                                />
                            </div>
                        </div>
                    </div>
                </Card>
            </> : ownerAccountId === -1 ? <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
                <Result
                    title="警告"
                    status="500"
                    subTitle="选择的账户不在一个账户分组中."
                />
            </div> : undefined}
        </div>

        {/* 预览 */}
        {previewData.visible && <Image
            width={200}
            style={{ display: 'none' }}
            preview={{
                visible: previewData.visible,
                src: previewData.url,
                onVisibleChange: value => {
                    setPreviewData({ visible: false })
                },
            }}
        />}
    </Spin>
}

export default React.memo(SelectGroupCloudNew)