import React, { useState, useReducer, useEffect, useCallback } from 'react'
import { Button, Card, Checkbox, DatePicker, Image as AntImage, Input, message, Pagination, Select, Space, Spin, Tabs, Tag, Tooltip } from 'antd'
import style from './index.less'
import './index1.less'
import moment from 'moment'
import AddCom from './components/addCom'
import { SelectValue } from 'antd/es/select'
import { useModel } from 'umi'
import { CheckboxValueType } from 'antd/es/checkbox/Group'
import { CheckboxChangeEvent } from 'antd/es/checkbox'
import ImgPreview from '@/components/ImgPreview'
import { DownloadOutlined, EyeInvisibleOutlined, EyeOutlined, FieldTimeOutlined, HeartTwoTone, HistoryOutlined, PieChartOutlined, SelectOutlined } from '@ant-design/icons'
const { Option } = Select
const CheckboxGroup = Checkbox.Group
const { Search } = Input
const { TabPane } = Tabs
import BatchAddLabel from '@/components/BatchAddLabel'
const plainOptions = ['朋友圈信息流', '公众平台流量', '广点通', '小程序', '头条', '抖音']

interface State {
    pageNum: number,
    pageSize: number,
    channel: CheckboxValueType[], // 投放渠道
    beginDate: string | undefined,  // 上传时间
    endDate: string | undefined,  // 结束时间
    labelIds: SelectValue, // 标签
    novels: string | undefined,  //书籍
    sortRule: string | undefined, // 类型排序
    upOrder: boolean, // 升序降序
    type: number | undefined,  // 素材类型 图片 视频
    isCollect: boolean, // 收藏 全部
    singleImg: string | undefined, // 图片结构
    dataType: string, // 数据类型
}
interface Action {
    type: 'init' | 'begainDate' | 'endDate' | 'dataType' | 'singleImg' | 'channel' | 'labelIds' | 'novels' | 'sortRule' | 'upOrder' | 'type' | 'isCollect' | 'pageNum' | 'pageSize',
    params?: any
}

function reducer(state: State, action: Action) {
    let { type, params } = action
    switch (type) {
        case 'begainDate':
            return { ...state, beginDate: params.beginDate }
        case 'endDate':
            return { ...state, endDate: params.endDate }
        case 'channel':
            return { ...state, channel: params.channel }
        case 'labelIds':
            return { ...state, labelIds: params.labelIds }
        case 'novels':
            return { ...state, novels: params.novels }
        case 'sortRule':
            return { ...state, sortRule: params.sortRule }
        case 'upOrder':
            return { ...state, upOrder: params.upOrder }
        case 'type':
            return { ...state, type: params.type }
        case 'isCollect':
            return { ...state, isCollect: params.isCollect }
        case 'dataType':
            return { ...state, dataType: params.dataType }
        case 'singleImg':
            return { ...state, singleImg: params.singleImg }
        case 'pageNum':
            return { ...state, pageNum: params.pageNum }
        case 'pageSize':
            return { ...state, pageSize: params.pageSize }
        case 'init':
            return { ...initState }
        default:
            return { ...state }
    }
}
const initState = {
    pageNum: 1,
    pageSize: 20,
    channel: [],
    beginDate: undefined,
    endDate: undefined,
    labelIds: [],
    novels: undefined,
    sortRule: 'consume_amount',
    upOrder: false,
    type: 1,
    isCollect: false,
    singleImg: undefined,
    dataType: 'all'
}

const colors = ['magenta', 'red', 'volcano', 'orange', 'gold', 'lime', 'green', 'cyan', 'blue', 'geekblue', 'purple']
/**广告图片/视频素材*/
function AdMaterial() {
    const [state, dispatch] = useReducer(reducer, initState)
    const { beginDate, endDate, labelIds, dataType, sortRule, upOrder, type, isCollect, channel, singleImg, pageNum, pageSize } = state
    const { getLabels, dataList, datacollects, delMedias, setTagMedia } = useModel('useLaunch.useMaterial')
    const [visible, setVisible] = useState<boolean>(false)
    const [editData, setEditData] = useState<any>({})  // 修改数据保存
    const [indeterminate, setIndeterminate] = React.useState(false);
    const [checkAll, setCheckAll] = useState<boolean>(false);
    const [checkedList, setCheckedList] = useState<CheckboxValueType[]>([]);
    const [previewData, setPreviewData] = useState<string[]>([])
    const [previewShow, setPreviewShow] = useState<boolean>(false)
    const [headShow, setHeadShow] = useState<boolean>(true)  // 头部显示隐藏
    const [batchVisible, setBatchVisible] = useState<boolean>(false)  // 批量添加标签弹窗控制

    useEffect(() => {
        getLabels.run({ pageNum: 1, pageSize: 200 })
    }, [])
    /** 获取列表 */
    useEffect(() => {
        setCheckedList([])
        setCheckAll(false)
        setIndeterminate(false)
        dataList.run({ ...state, channel: channel.toString(), labelIds, name: 'mediaList' })
    }, [state])

    /** 多选处理 */
    const onChangeCheckbox = useCallback((checkedValue: CheckboxValueType[]) => {
        setCheckedList(checkedValue)
    }, [])
    const onCheckAllChange = (e: CheckboxChangeEvent) => {
        setCheckedList(e.target.checked ? plainOptions : []);
        setIndeterminate(false);
        setCheckAll(e.target.checked);
        if (e.target.checked) {
            let ids = dataList?.data?.records?.map((item: any) => item?.id)
            if (ids.length > 20) {
                message.error('最多选择20个')
                ids = ids.splice(0, 20)
            }
            setCheckedList(ids)
        } else {
            setCheckedList([])
        }
    };
    useEffect(() => {
        if (checkedList?.length > 0) {
            let length = dataList?.data?.records?.length
            if (length > checkedList.length) {
                setIndeterminate(true)
            } else {
                setIndeterminate(false)
                setCheckAll(true)
            }
        } else {
            setIndeterminate(false)
            setCheckAll(false)
        }
    }, [checkedList])

    /** 收藏 */
    const collectsHandle = useCallback(({ id, isCollects }: { id: number, isCollects: boolean }) => {
        let collectsType: number = type === 1 ? 2 : 3
        datacollects.run({ type: collectsType, contentIds: id.toString(), name: 'mediaCollect', collect: isCollects }).then(res => {
            dataList.refresh()
        })
    }, [dataList])
    /**分页 */
    const pageChange = useCallback((page: string | number, pageSize?: string | number) => {
        dispatch({ type: 'pageNum', params: { pageNum: page } })
        dispatch({ type: 'pageSize', params: { pageSize: pageSize } })
    }, [])

    /** 删除 */
    const delHandle = useCallback(() => {
        delMedias.run({ ids: checkedList.toString() }).then(res => {
            dataList.refresh()
            setCheckedList([])
        })
    }, [checkedList, dataList])

    /** 修改 */
    const edit = useCallback(() => {
        // setCheckboxIds([])
        if (checkedList.length > 0) {
            let data = dataList?.data?.records.find((item: any) => item?.id === checkedList[0])
            setEditData(data)
            setVisible(true)
        }
    }, [checkedList, editData, dataList])
    /** 下载 */
    const downLoad = (urls: string) => {
        if (urls) {
            urls?.split(',')?.map((url: string) => {
                const tag = document.createElement('a');
                // 此属性的值就是**时图片的名称，注意，名称中不能有半角点，否则**时后缀名会错误
                tag.setAttribute('download', 'download'.replace(/\./g, '。'));
                const image = new Image();
                // 设置 image 的 url, 添加时间戳，防止浏览器缓存图片
                image.src = url + '?time=' + new Date().getTime();
                //重要，设置 crossOrigin 属性，否则图片跨域会报错
                image.setAttribute('crossOrigin', 'Anonymous');
                // 图片未加载完成时操作会报错
                image.onload = () => {
                    tag.href = getImageDataURL(image);
                    tag.click();
                }
            })
        }
    }
    const getImageDataURL = (image: any) => {
        // 创建画布
        const canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        const ctx: any = canvas.getContext('2d');
        // 以图片为背景剪裁画布
        ctx.drawImage(image, 0, 0, image.width, image.height);
        // 获取图片后缀名
        const extension = image.src.substring(image.src.lastIndexOf('.') + 1).toLowerCase();
        // 某些图片 url 可能没有后缀名，默认是 png
        return canvas.toDataURL('image/' + extension, 1);
    }

    // 批量添加标签
    const batchEdit = useCallback(() => {
        setBatchVisible(true)
    }, [batchVisible])

    // 批量添加标签确定
    const batchEditOK = useCallback((value: string[]) => {
        setTagMedia.run({mediaIds: checkedList.toString(), labelIds: value.toString()}).then((res: any) => {
            dataList.refresh()
            setBatchVisible(false)
            // setCheckedList([])
        })
    }, [batchVisible, checkedList, dataList])

    return <Card className={style.adOrigin} title={
        headShow ?
            <>
                <div style={{ marginBottom: 20 }}><Space><div className='label'>投放渠道：</div> <CheckboxGroup options={plainOptions} value={channel} onChange={(e: CheckboxValueType[]) => { dispatch({ type: 'channel', params: { channel: e } }) }} /></Space></div>
                <div style={{ marginBottom: 20 }}>
                    <Space>
                        <DatePicker style={{ width: 120 }} value={beginDate ? moment(beginDate) : null} onChange={(e: moment.Moment | null) => { dispatch({ type: 'begainDate', params: { beginDate: e ? moment(e).format('YYYY-MM-DD') : null } }) }} placeholder='消耗开始时间' />
                        <DatePicker style={{ width: 120 }} value={endDate ? moment(endDate) : null} onChange={(e: moment.Moment | null) => { dispatch({ type: 'endDate', params: { endDate: e ? moment(e).format('YYYY-MM-DD') : null } }) }} placeholder='消耗结束时间' />
                        <Search placeholder="请输入小说" style={{ width: 150 }} onSearch={(e) => { dispatch({ type: 'novels', params: { novels: e } }) }} allowClear />
                        <Select style={{ width: 200 }} maxTagCount='responsive' value={labelIds} onChange={(value: SelectValue) => { dispatch({ type: 'labelIds', params: { labelIds: value } }) }} placeholder="选择标签" allowClear mode="multiple">
                            {getLabels?.data?.records.map((item: any) => (<Option value={item?.id} key={item?.id}>{item?.label}</Option>))}
                        </Select>
                    </Space>
                </div>
                <div className={style.headerItem}>
                    <div>
                        <Space>
                            <Select style={{ width: 150 }} value={sortRule} onChange={(value: SelectValue) => { dispatch({ type: 'sortRule', params: { sortRule: value } }) }} placeholder="选择排序类型" allowClear>
                                {/* <Option value="create_time">按照上传时间排序</Option> */}
                                {/* <Option value="click_times">点击次数</Option> */}
                                <Option value="view_times">浏览次数</Option>
                                <Option value="consume_amount">消耗金额</Option>
                                <Option value="click_rate">点击率</Option>
                            </Select>
                            <Select style={{ width: 70 }} value={upOrder ? '1' : '2'} onChange={(value: SelectValue) => { dispatch({ type: 'upOrder', params: { upOrder: value === '1' ? true : false } }) }} >
                                <Option value="1">升序</Option>
                                <Option value="2">降序</Option>
                            </Select>
                            <Select style={{ width: 70 }} value={type} onChange={(value: SelectValue) => { dispatch({ type: 'type', params: { type: value } }) }} placeholder="请选择素材类型">
                                <Option value={1}>图片</Option>
                                <Option value={2}>视频</Option>
                            </Select>
                            {type === 1 && <Select style={{ width: 140 }} value={singleImg} onChange={(value: SelectValue) => { dispatch({ type: 'singleImg', params: { singleImg: value } }) }} placeholder="请选择图片结构" allowClear>
                                <Option value={1}>单图</Option>
                                <Option value={0}>组图</Option>
                            </Select>}
                            <Select style={{ width: 100 }} value={isCollect ? 'true' : 'false'} onChange={(value: SelectValue) => { dispatch({ type: 'isCollect', params: { isCollect: value === 'true' ? true : false } }) }}>
                                <Option value="false">全部</Option>
                                <Option value="true">我的收藏</Option>
                            </Select>
                        </Space>
                    </div>
                    <div>
                        <Space>
                            <Button type="primary" disabled={checkedList?.length > 1 ? false : true} onClick={batchEdit}>批量添加标签</Button>
                            <Button type="primary" disabled={checkedList?.length !== 1} onClick={edit}>修改</Button>
                            {/* <Popconfirm placement="top" title='确定删除？' onConfirm={delHandle} okText="Yes" cancelText="No" disabled={checkedList.length === 0}>
                                <Button danger disabled={checkedList.length === 0}>删除</Button>
                            </Popconfirm> */}
                            {/* <Button type="primary" disabled={checkboxIds.length === 0}>收藏</Button> */}
                            {/* <Button type="primary" onClick={() => { setVisible(true); setEditData({}) }}>上传图片/视频</Button> */}
                        </Space>
                    </div>
                </div>
            </>
            : null
    }
    >
        {visible && <AddCom visible={visible} hideModal={() => { setVisible(false); }} editData={editData} ajax={dataList} dataType={dataType}></AddCom>}
        {previewShow && <ImgPreview data={previewData} show={previewShow} hidden={() => { setPreviewShow(false) }}></ImgPreview>}
        {/* 批量添加标签 */}
        {batchVisible && <BatchAddLabel show={batchVisible} onClose={()=>{setBatchVisible(false)}} onChange={batchEditOK} ajax={setTagMedia}/>}
        <Tabs onChange={(e) => { dispatch({ type: 'dataType', params: { dataType: e } }) }} tabBarExtraContent={<Space>
            <Tooltip placement="top" title={headShow ? '隐藏头部' : '显示头部'}>
                <Button type="primary" size="small" shape="circle" icon={headShow ? <EyeInvisibleOutlined /> : <EyeOutlined />} onClick={() => { setHeadShow(!headShow) }} />
            </Tooltip>
            <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
                全选
            </Checkbox>
        </Space>} type="card" size='small' className={style.tabs} activeKey={dataType}>
            <TabPane tab="公司云共享" key="all" />
            <TabPane tab="个人云共享" key="private" />
            {/* <TabPane tab="个人" key="personal" />
            <TabPane tab="组内共享" key="group" /> */}
        </Tabs>
        <Spin spinning={dataList.loading} size='large' >
            <Checkbox.Group onChange={onChangeCheckbox} value={checkedList} className={style.group}>
                <div className={style.contentbb}>
                    <div className={style.contentaa}>
                        {
                            dataList?.data?.records?.map((item: any, index: number) => {
                                return <div style={{ width: 300 }} key={Math.random() * 1000} >
                                    {<Card
                                        hoverable
                                        className={style.box_card}
                                        cover={<div className='covercc'>
                                            {
                                                item?.type === 1 ? <div className='imgs'>
                                                    {/* <Image.PreviewGroup>
                                                        {item?.content?.split(',').map((item: string, index: number) => (<Image key={index} src={item} placeholder />))}
                                                    </Image.PreviewGroup> */}
                                                    <div className='imgz'>
                                                        {
                                                            item?.content?.split(',').length === 4 ? <div className="con4">
                                                                {item?.content?.split(',').map((item: string, index: number) => (<div key={index}><AntImage src={item} preview={false} /></div>))}
                                                            </div> :
                                                                item?.content?.split(',').length === 6 ? <div className="con6">
                                                                    {item?.content?.split(',').map((item: string, index: number) => (<div key={index}><AntImage src={item} preview={false} /></div>))}
                                                                </div> :
                                                                    <AntImage src={item?.content?.split(',')[0]} preview={false} />
                                                        }
                                                    </div>
                                                    <div className="preview">
                                                        <Button type="text" onClick={() => { setPreviewData(item?.content?.split(',')); setPreviewShow(true) }}><EyeOutlined />预览</Button>
                                                    </div>
                                                    <div className='backImg'>
                                                        <img src={`${item?.content?.split(',')[0]}`} />
                                                    </div>
                                                </div>
                                                    : item?.type === 2 ? <video style={{ width: 300, height: 170 }} src={item?.content} loop={true} autoPlay={false} controls></video> : null
                                            }
                                            <div className='boxcc'><Checkbox value={item?.id} disabled={checkedList?.find((item1: any) => item1 === item?.id) ? false : checkedList.length >= 20 ? true : false}/></div>
                                            <div className='boxdd'>
                                                {
                                                    item?.content?.split(',').length > 1 && !item?.singleImg && <div className='zt'>组图</div>
                                                }
                                                {item?.type === 1 && <Tooltip title='下载'>
                                                    <DownloadOutlined style={{ color: '#108ee9', fontSize: 18, marginRight: 5, cursor: 'pointer' }} onClick={() => { downLoad(item?.content) }} />
                                                </Tooltip>}
                                                {
                                                    item?.isCollect ? <Tooltip title='取消收藏'>
                                                        <HeartTwoTone twoToneColor="#eb2f96" style={{ fontSize: 18 }} onClick={() => { collectsHandle({ id: item?.id, isCollects: false }) }} />
                                                    </Tooltip> : <Tooltip title='收藏'>
                                                            <HeartTwoTone color="#eb2f96" style={{ fontSize: 18 }} onClick={() => { collectsHandle({ id: item?.id, isCollects: true }) }} />
                                                        </Tooltip>
                                                }
                                            </div>
                                        </div>
                                        }
                                    >
                                        <Card.Meta
                                            style={{ fontSize: 12, padding: 10 }}
                                            description={
                                                <>
                                                    <div className="bottom">
                                                        <div>
                                                            {item?.createTime &&
                                                                <Tooltip placement="top" title='创建时间'>
                                                                    <Space><FieldTimeOutlined />{item?.createTime.split(' ')[0]}</Space>
                                                                </Tooltip>}
                                                        </div>
                                                        <div className="left">
                                                            {item?.startDate && item?.endDate && <Tooltip placement="top" title='消耗时间'>
                                                                <Space><HistoryOutlined />{item?.startDate + '/' + item?.endDate}</Space>
                                                            </Tooltip>}
                                                        </div>
                                                    </div>
                                                    <div className="bottom">
                                                        <div>
                                                            <Tooltip placement="topLeft" color="#FFF" title={
                                                                <div>
                                                                    {item?.labelInfos?.map((i: any, index: number) => {
                                                                        return <Tag color={colors[index]} key={i.id} >{i?.label}</Tag>
                                                                    })}
                                                                </div>
                                                            }>
                                                                <div className="title">
                                                                    {item?.labelInfos?.map((i: any, index: number) => {
                                                                        if (index > 2) return null
                                                                        return <Tag color={colors[index]} key={i.id} >{i?.label}</Tag>
                                                                    })}
                                                                </div>
                                                            </Tooltip>
                                                        </div>
                                                        <div className="left" style={{ color: 'purple' }}>
                                                            {item?.novels && <Tooltip placement="top" title={`小说：${item?.novels}`}>
                                                                {item?.novels?.split(',')[0] + (item?.novels?.split(',')?.length > 1 ? ',...' : '')}
                                                            </Tooltip>}
                                                        </div>
                                                    </div>
                                                    <div className="bottom">
                                                        <div className="right"><span style={{color:"#00bcd4"}}>归属人:</span>{item?.creator}</div>
                                                        <div className="left">
                                                            <Space>
                                                                <Tooltip placement="top" title='消耗'>
                                                                    <Space style={{ color: "#46BF12" }}><PieChartOutlined />{(item?.consumeAmount || 0)}</Space>
                                                                </Tooltip>
                                                                <Tooltip placement="top" title='点击率'>
                                                                    <Space style={{ color: "#02A7F0" }}><SelectOutlined />{item?.clickRate ? (item?.clickRate * 100).toFixed(2)  + '%' : 0}</Space>
                                                                </Tooltip>
                                                                {item?.channel && <span className="channer" style={{ backgroundColor: item?.channel === '头条' ? '#f50' : item?.channel === '抖音' ? '#2db7f5' : item?.channel === '广点通' ? '#87d068' : item?.channel === '小程序' ? '#108ee9' : item?.channel === '公众平台流量' ? 'green' : 'orange' }}>{item?.channel}</span>}
                                                            </Space>
                                                        </div>
                                                    </div>
                                                </>
                                            }
                                            className={style.meta}
                                        />
                                    </Card>
                                    }
                                </div>
                            })
                        }

                    </div>
                </div>

            </Checkbox.Group>
        </Spin>
        <div className="pagin"><Pagination size="small" onChange={pageChange} current={pageNum} pageSize={pageSize} total={dataList?.data?.total} showSizeChanger showQuickJumper /></div>
    </Card>
}
export default AdMaterial
