
import React, { useCallback, useEffect, useState } from 'react'
import Tables from '@/components/Tables'
import columns from './tableConfig'
import './index.less'
import { Button, Card, DatePicker, Input, message, Modal, Popconfirm, Select, Space, Switch, Tabs, Tooltip } from 'antd'
import { SearchOutlined, SyncOutlined } from '@ant-design/icons'
const { Option } = Select
import { adsPlanLogList } from '@/services/operating/adAuthorize'
import moment from 'moment'
import { useModel } from 'umi'
import BatchCopy from './batchCopy'
import BatchCopys from './batchCopys'
import BatchPageCopy from './batchPageCopy'
import LookLanding from '../../../components/lookLanding'
import AdLogin from '../../../components/adLogin'

type Props = {
    planCallBack: Function,
    checkLogin: (c: () => void) => void
}


/** 推广计划 */
function Plan(props: Props) {
    let { planCallBack, checkLogin } = props
    const [queryForm, setQueryForm] = useState<adsPlanLogList>({ pageNum: 1, pageSize: 20, posType: 999 })
    const [advertisers, setAdvertisers] = useState<any[]>([])   // 广告主列表
    // const [channelId, setChannelId] = useState<number | undefined>(undefined) // 选中服务商id
    const [channel] = useState<string>('MP') // 平台
    const [planIds, setPlanIds] = useState<number[]>([])  // 保存选择的id
    const [planData, setPlanData] = useState<any[]>([])  // 保存选择的id
    const [serverData, setServerData] = useState<any[]>([]) // 服务商数据
    const [copyShow, setCopyShow] = useState<boolean>(false)  // 批量复制改相同基本信息弹窗控制
    const [copysShow, setCopysShow] = useState<boolean>(false)  // 批量弹窗控制
    const [copyPageShow, setCopyPageShow] = useState<boolean>(false)  // 批量更换落地页弹窗控制
    const [copyPlanData, setCopyPlanData] = useState<any>() // 保存要批量复制的内容
    const [lookVisible, setLookVisible] = useState<boolean>(false) // 查看弹窗控制
    const [typesetting, setTypesetting] = useState<any>({})  // 落地页具体内容
    const [authData, setAuthData] = useState<{ base64: string, code: string }>({ base64: '', code: '' })
    const [crtSize, setcrtSize] = useState<number>(0)
    const [checked, setChecked] = useState<boolean>(true)//true开启批量操作，false开启批量删除

    const { getAdsPlanLog, allOfLoginUser, adsChannelAccountAdqAll, adsChannelAccountMpAll, addPlan, delLogBatch } = useModel('useLaunch.useAdAuthorize')
    /**分页 */
    const pageChange = useCallback((page: string | number, pageSize?: string | number) => {
        setQueryForm({ ...queryForm, pageNum: page as number, pageSize: pageSize as number })
        getAdsPlanLog.run({ ...queryForm, pageNum: page as number, pageSize: pageSize as number, accountIds: queryForm?.accountIds?.toString() })
    }, [queryForm])

    useEffect(() => {
        let task = sessionStorage.getItem('TASK')
        if (task) {
            let { taskName, posType } = JSON.parse(task)
            setQueryForm({ ...queryForm, taskName: taskName, createStartTime: undefined, posType })
            getAdsPlanLog.run({ ...queryForm, taskName: taskName, createStartTime: undefined, accountIds: queryForm?.accountIds?.toString(), posType })
            sessionStorage.removeItem('TASK')
        } else {
            getAdsPlanLog.run({ ...queryForm, accountIds: queryForm?.accountIds?.toString() })
        }
        allOfLoginUser.run().then((res: any) => {
            setServerData(res?.data)
        })
    }, [])

    /** 选择服务商 */
    const backISP = useCallback((value: number) => {
        // setChannelId(value)
        setQueryForm({ ...queryForm, channelId: value })
        if (value) {
            if (channel === 'MP') {
                adsChannelAccountMpAll.run(value).then((res: any) => {
                    setAdvertisers(res?.data?.map((item: any) => {
                        return { uname: item?.uname, id: item?.id }
                    }))
                })
            } else {
                adsChannelAccountAdqAll.run(value)
            }
        } else {
            setAdvertisers([])
        }
    }, [queryForm?.channelId, advertisers])
    /** 选择广告主 */
    const backAdvertisers = useCallback((value: any) => {
        setQueryForm({ ...queryForm, accountIds: value })
    }, [queryForm])

    /** 输入计划名称搜索 */
    const backPlanName = useCallback((value: string) => {
        setQueryForm({ ...queryForm, planName: value })
    }, [queryForm])
    /** 查询 */
    const fun = useCallback(() => {
        setQueryForm({ ...queryForm, pageNum: 1 })
        getAdsPlanLog.run({ ...queryForm, pageNum: 1, accountIds: queryForm?.accountIds?.toString() })
        clearSelect()
    }, [queryForm])

    /** 查看 */
    const look = useCallback((e) => {
        setTypesetting(e)
        setLookVisible(true)
    }, [])
    const backMenuKey = useCallback((item: any, key: any) => {
        function fn() {
            if (key === '0') { // 批量复制
                setCopyPlanData(item)
                setCopyShow(true)
            } else if (key === '5') {
                setCopyPlanData(item)
                setCopyPageShow(true)
            } else if (key === '1' || key === '4') {
                planCallBack(key === '1' ? '复制' : '修改', item)
            } else if (key === '3') {
                Modal.warning({
                    title: `确定删除“${item?.planInfo?.taskInfo?.taskName}”`,
                    okText: '确定',
                    closable: true,
                    onOk: () => {
                        delLogBatch.run({ logIds: item?.id?.toString() }).then((res: any) => {
                            getAdsPlanLog.refresh()
                        })
                    },
                })
            } else if (key === '6') { // 失败重新提交
                let channelMpAccount: any = {}
                let { planInfo, accountId, packageList } = item
                let { content, planName, putLocation, putTarget, firstContext, secondContext, sharePageId, taskInfo, sharePageInfo, posType } = planInfo
                channelMpAccount[accountId] = packageList
                secondContext = JSON.parse(secondContext)
                if (sharePageInfo?.name) {
                    secondContext['page_name'] = sharePageInfo?.name
                }
                addPlan.run({
                    channelAdqAccount: {},
                    channelMpAccount,
                    taskName: taskInfo?.taskName?.split('-')[0] + '-' + moment().unix(),
                    planDto: { posType, content, planName, putLocation, putTarget, pageId: sharePageId, firstContext, secondContext: JSON.stringify(secondContext) }
                }).then((res: any) => {
                    if (res?.code === 200) {
                        message.success('重新提交成功')
                        window.location.href = '/#/launchSystem/launchManage/taskList'
                    } else if (res?.code === 1003 && res?.data?.base64) {
                        setAuthData(res?.data)
                    }
                })
            }
        }
        checkLogin(fn)
    }, [copyShow, copyPlanData, copyPageShow, authData, getAdsPlanLog])
    // 结束日期不可选择日期
    const disabledEndDate = useCallback((current: any) => {
        // Can not select days before today and today
        if (queryForm?.createStartTime) {
            return current && current < moment(queryForm?.createStartTime)
        }
    }, [queryForm?.createStartTime])

    // 选择类型
    const selectPosType = useCallback((value: number) => {
        setQueryForm({ ...queryForm, posType: value, pageNum: 1 })
        clearSelect()
        getAdsPlanLog.run({ ...queryForm, pageNum: 1, posType: value })
    }, [queryForm, planIds])
    // 批量删除
    const allDel = useCallback(() => {
        delLogBatch.run({ logIds: planIds?.toString() }).then((res: any) => {
            getAdsPlanLog.refresh()
            clearSelect()
        })
    }, [planIds])
    // 清空选项
    const clearSelect=useCallback(()=>{
        setPlanData([])
        setPlanIds([])
    },[])
    console.log(planData,planIds)
    return <Card
        hoverable
        title={<Space wrap>
            <DatePicker style={{ width: 150 }} value={queryForm?.createStartTime ? moment(Number(queryForm?.createStartTime)) : null} onChange={(e: moment.Moment | null) => { setQueryForm({ ...queryForm, createStartTime: e ? moment(e).format("x") : '', createEndTime: '' }) }} placeholder='创建开始时间' />
            <DatePicker style={{ width: 150 }} disabledDate={disabledEndDate} value={queryForm?.createEndTime ? moment(Number(queryForm?.createEndTime)) : null} onChange={(e: moment.Moment | null) => { setQueryForm({ ...queryForm, createEndTime: e ? moment(e).format("x") : '' }) }} placeholder='创建截止时间' />
            <Select value={queryForm?.channelId} style={{ width: 200 }} onChange={backISP} placeholder="选择服务商" allowClear onClear={() => { setQueryForm({ ...queryForm, accountIds: [] }) }}>
                {serverData?.map((item: any) => (<Option value={item?.id} key={item?.id}>{item?.accountName}</Option>))}
            </Select>
            {queryForm?.channelId && advertisers && advertisers.length > 0 && <Select value={queryForm?.accountIds} style={{ minWidth: 180 }} mode="multiple" maxTagCount={1} onChange={backAdvertisers} placeholder="选择广告主名称" allowClear>
                {advertisers?.map((item: any) => (<Option value={item.id.toString()} key={item.id}>{item.uname}</Option>))}
            </Select>}
            <Input value={queryForm?.planName} onChange={(e) => { backPlanName(e.target.value) }} placeholder="输入计划名称搜索" allowClear />
            <Input value={queryForm?.taskName} onChange={(e) => { setQueryForm({ ...queryForm, taskName: e.target.value }); sessionStorage.setItem('TASKNAME', e.target.value) }} placeholder="输入任务名称搜索" allowClear />
            <Select value={queryForm?.createStatus} style={{ width: 150 }} onChange={(e) => { setQueryForm({ ...queryForm, createStatus: e }) }} placeholder="选择状态" allowClear>
                <Option value="-1">创建失败</Option>
                <Option value="0">创建中</Option>
                <Option value="100">创建成功</Option>
            </Select>
            <Button type='primary' onClick={fun}><SearchOutlined /> 查询</Button>
            {checked && <>
                <Tooltip title='支持更改一次广告创意,但所选计划都会使用本次更改的广告创意,即使不做修改也会把其它计划替换成第一个计划的创意信息，推荐在全部计划使用同一个广告创意并批量复制指定数量的情况'>
                    <Button type="primary"
                        icon={<SyncOutlined />}
                        style={{ background: '#67c23a', borderColor: '#67c23a' }}
                        disabled={!planIds?.length}
                        onClick={() => {
                            checkLogin(() => setCopyShow(true))
                            setCopyPlanData(planData)
                        }}>批量复制改相同基本信息</Button>
                </Tooltip>
                <Tooltip title='支持独立修改所选计划的创意信息,不修改保持原计划信息,推荐在不同计划不做任何变动并批量复制的情况'>
                    <Button type="primary"
                        icon={<SyncOutlined />}
                        style={{ background: '#67c23a', borderColor: '#67c23a' }}
                        disabled={!planIds?.length}
                        onClick={() => {
                            checkLogin(() => setCopysShow(true))
                            setCopyPlanData(planData)
                        }}>批量复制</Button>
                </Tooltip>
                <Tooltip title='所选计划更改指定创意信息，支持多个创意,推荐在计划需要批量替换多个不同的创意时'>
                    <Button type="primary"
                        icon={<SyncOutlined />}
                        style={{ background: '#67c23a', borderColor: '#67c23a' }}
                        disabled={!planIds?.length}
                        onClick={() => {
                            checkLogin(() => setCopyPageShow(true))
                            setCopyPlanData(planData)
                        }}>批量复制并更换落地页</Button>
                </Tooltip>
            </>}
            {
                !checked && <>

                    <Popconfirm
                        title="是否确定要删除选中的计划?"
                        onConfirm={allDel}
                        okText="是"
                        cancelText="否"
                        disabled={planIds.length === 0}
                    ><Button type="primary" danger disabled={planIds.length === 0}>批量删除</Button></Popconfirm>
                </>
            }
            <Switch checkedChildren="批量操作" unCheckedChildren="批量删除" checked={checked} style={checked ? {} : { background: 'red' }} onChange={(checked: boolean) => {
                setChecked(checked)
                setPlanData([])
                setPlanIds([])
            }} />
        </Space>}
    >
        <Tabs activeKey={queryForm?.posType.toString()} className="meTabs" onChange={(activeKey: string) => { selectPosType(Number(activeKey));setcrtSize(0) }} type="card">
            <Tabs.TabPane tab="微信朋友圈" key='999' />
            <Tabs.TabPane tab="公众号文章底部" key='0' />
            <Tabs.TabPane tab="优雅横板大图" key='101' />
            <Tabs.TabPane tab="激励式广告" key='8' />
        </Tabs>
        <Tables
            columns={columns(backMenuKey, look, queryForm?.posType)}
            dataSource={getAdsPlanLog?.data?.data?.records}
            total={getAdsPlanLog?.data?.data?.total}
            pageChange={pageChange}
            sizeChange={pageChange}
            current={queryForm?.pageNum}
            size="small"
            loading={getAdsPlanLog?.loading}
            scroll={{ x: 1200 }}
            bordered
            rowSelection={{
                selectedRowKeys: planIds.map(item => { return item?.toString()}).filter(item=>item !== undefined),
                onSelect: (record: any, selected: any, selectedRows: any[], nativeEvent: any) => {
                    if (selectedRows?.length === 0) {
                        setcrtSize(0)
                    } else {
                        let secondContext = JSON.parse(record?.planInfo?.secondContext)
                        let material = secondContext?.materials[0]
                        let crt_size = material?.crt_size
                        setcrtSize(crt_size)
                    }
                    console.log(selected,record,'selectedRows')
                    let planArr =selected? planData.concat([record]):planData.filter(item=>item?.id !== record?.id)
                    setPlanData(planArr)
                    setPlanIds(planArr.map(item=>item?.id?.toString()))
                },
                onSelectAll: (selected: any, selectedRows: any[], changeRows: any[]) => {
                    if (checked) {//批量操作逻辑
                        if (!selected && planData?.length === 0) {//反选，并且已选项为空才设置初始值
                            setcrtSize(0)
                        } else {
                            if (crtSize === 0) {
                                console.log(2222) 
                                let new_crt_size = 0
                                selectedRows = selectedRows?.reduce((prev: any[], cur: any) => {
                                    let secondContext = JSON.parse(cur?.planInfo?.secondContext)
                                    let material = secondContext?.materials[0]
                                    let crt_size = material?.crt_size
                                    console.log(prev,crt_size,new_crt_size)
                                    if (prev.length === 0) {
                                        new_crt_size = crt_size
                                        return prev.concat(cur)
                                    } else {
                                        if (crt_size === new_crt_size) {
                                            return prev.concat(cur)
                                        } else {
                                            return prev
                                        }
                                    }
                                }, [])
                                setcrtSize(new_crt_size)
                            }
                        }
                    }
                    let planArr =selected? planData.concat(selectedRows.filter(item=>item !== undefined)):planData.filter(item=>changeRows.every(i=>i?.id!==item?.id) )
                    setPlanData(planArr)
                    setPlanIds(planArr.map(item=>item?.id?.toString()))
                },
                getCheckboxProps: (record: any) => {
                    let secondContext = JSON.parse(record?.planInfo?.secondContext)
                    let material = secondContext?.materials[0]
                    let crt_size = material?.crt_size
                    return checked ? {
                        disabled: record.createStatus !== 100 ? true : crtSize !== 0 ? crt_size !== crtSize : false // Column configuration not to be checked
                    } : { disabled: false }
                }
            }}
            rowClassName={(record: any) => {
                if (record?.createStatus === -1) {
                    return 'error'
                } else {
                    return ""
                }
            }}
        />
        {/* 授权登录 */}
        <AdLogin onClose={() => { setAuthData({ base64: '', code: '' }) }} value={authData} onChange={() => { setAuthData({ base64: '', code: '' }); message.success('再次点击按钮') }} />

        {/* 批量复制 */}
        {copysShow && <BatchCopys ajax={getAdsPlanLog} visible={copysShow} onClose={() => { setCopysShow(false) }} defaultValue={copyPlanData} clearSelect={clearSelect}/>}
        {/* 批量复制改相同基本信息 */}
        {copyShow && <BatchCopy ajax={getAdsPlanLog} visible={copyShow} onClose={() => { setCopyShow(false) }} defaultValue={copyPlanData} clearSelect={clearSelect}/>}
        {/* 批量更换落地页 */}
        {copyPageShow && <BatchPageCopy ajax={getAdsPlanLog} visible={copyPageShow} onClose={() => { setCopyPageShow(false) }} defaultValue={copyPlanData} clearSelect={clearSelect}/>}
        {/* 查看详情落地页 */}
        {lookVisible && <LookLanding visible={lookVisible} hideModal={() => { setLookVisible(false) }} typesetting={typesetting}></LookLanding>}
    </Card>
}

export default Plan