import { Button, Card, DatePicker, Input, Select, Space } from "antd"
import moment from "moment";
import React, { useCallback, useEffect, useState } from "react"
import TableData from "../components/TableData";
import PlanDetail from './components/planDetail'
import { useModel } from "umi";
import columnsPlanList from './tablePlanListConfig'
import { allPlanProps, downLoadAllAdListApi } from '@/services/launch/adMonitor'
import { GUANGGAOZHUANGTAI, CHUANGYIZHUANGTAI } from './enum'
import { guanggao } from './config'
import { CloudDownloadOutlined } from "@ant-design/icons";
import { formatDate, downloadFile1 } from '@/utils/downloadFile';

/**
 * 广告监控
 * @returns 
 */
function PlanList() {
    const { getAllPlanList, getAgencyList, getBookList, getAdGroupList, getBookListAll } = useModel('useLaunch.useMonitor')
    const { state } = useModel('useOperating.useWxGroupList')
    // 变量开始
    const [queryForm, setQueryForm] = useState<allPlanProps>({ page: 1, pageSize: 20, createStartTime: moment().subtract(3, 'days').unix(), createEndTime: moment().unix() }) // 搜索变量
    const [visible, setVisible] = useState<boolean>(false) // 详情弹窗控制
    const [datas, setDatas] = useState<any[]>([])  // 所有数据
    const [pichers, setPichers] = useState<any[]>([]) // 投手数据
    const [mpDatas, setMpDatas] = useState<any[]>([]) // 公众号
    const [mpDatasB, setMpDatasB] = useState<any[]>([]) // 备份公众号
    const [adId, setAdId] = useState<any>()
    const [downLoadLoading, setDownLoadLoading] = useState<boolean>(false)
    // 变量结束
    useEffect(() => {
        if (state?.allOfMember?.length > 0) {
            setDatas(state?.allOfMember)
        } else if (state?.myallOfUser?.length > 0) {
            setDatas(state?.myallOfUser)
        }
    }, [state])

    // 处理公众号
    useEffect(() => {
        if (datas.length > 0) {
            let new_pichers = datas?.map((item: { key: { nickName: string, userId: number } }) => ({ nickName: item.key.nickName, userId: item.key.userId }))
            if (JSON.stringify(pichers) !== JSON.stringify(new_pichers)) {//避免重复设置触发条件多次请求接口
                setPichers(new_pichers)
            }
            if (queryForm?.pitcherIds?.length > 0) {
                let arr: any = []
                queryForm?.pitcherIds?.forEach((pitcherId: any) => {
                    let data = datas?.find((item: { key: any }) => item.key.userId == pitcherId)
                    arr.push(data)
                })
                if (arr?.length > 0) {
                    setMpDatas(arr)
                    setMpDatasB(arr)
                }
            } else {
                setMpDatas(datas)
                setMpDatasB(datas)
            }
        }
    }, [datas, queryForm?.pitcherIds, pichers])

    useEffect(() => {
        if (sessionStorage.getItem('ADIDORNAME')) {
            let data = JSON.parse(sessionStorage.getItem('ADIDORNAME') as any)
            setQueryForm({ ...queryForm, adIdOrName: data.adId, planIdOrName: data.campaignId, pitcherIds: data.pitcherId.split(), mpAppIds: data.mpAppId.split() })
            sessionStorage.removeItem('ADIDORNAME')
        }
    }, [])

    // 获取分组
    useEffect(() => {
        getAdGroupList.run().then((res: any) => {
            let newQueryForm = JSON.parse(JSON.stringify(queryForm))
            if (res?.code === 200 && res?.data?.length > 0) {
                newQueryForm['groupId'] = res?.data[0].id
                setQueryForm(() => ({ ...queryForm, groupId: res?.data[0].id }))
            }
            // 首次获取列表
            getList(newQueryForm)
        })
    }, [pichers])

    const getList = useCallback((data: allPlanProps) => {
        let newQueryForm = JSON.parse(JSON.stringify(data))
        Object.keys(newQueryForm).forEach((key: any) => {
            if (key === 'mpAppIds' || key === 'pitcherIds') {
                newQueryForm[key] = newQueryForm[key]
            }
        })
        if (!newQueryForm['pitcherIds'] && (!queryForm['mpAppIds'] || queryForm['mpAppIds']?.length === 0)) {
            newQueryForm['pitcherIds'] = pichers?.map(item => item.userId)
        }
        getAllPlanList.run(newQueryForm)
    }, [pichers])

    /** 获取服务商，书 */
    useEffect(() => {
        let listQueryForm: { mpAppIds?: string, pitcherIds?: string } = {}
        if (queryForm?.mpAppIds) {
            listQueryForm.mpAppIds = queryForm?.mpAppIds.join()
        }
        if (queryForm?.pitcherIds) {
            listQueryForm.pitcherIds = queryForm?.pitcherIds.join()
        }
        if (!listQueryForm['pitcherIds'] && (!queryForm?.mpAppIds || queryForm?.mpAppIds?.length === 0)) {
            listQueryForm['pitcherIds'] = pichers?.map(item => item.userId)?.join()
        }
        getAgencyList.run(listQueryForm)
        // getBookList.run(listQueryForm)
    }, [queryForm?.mpAppIds, queryForm?.pitcherIds, pichers])
    /** 获取书 */
    useEffect(() => {
        getBookListAll.run()
    }, [])

    // 设置创建时间
    const setUnix = ([str, end]: string[]) => {
        if (str && end) {
            setQueryForm({ ...queryForm, page: 1, createStartTime: moment(str).unix(), createEndTime: moment(end).unix() })
        } else {
            const { createStartTime, createEndTime, ...newQueyFor } = queryForm
            setQueryForm({ ...newQueyFor, page: 1 })
        }
    }

    // 详情
    const detail = (data: number) => {
        setAdId(data)
        setVisible(true)
    }
    // 接口自动刷新10分钟一次
    useEffect(() => {
        let time = setInterval(() => {
            console.log('广告列表10分钟刷新')
            getAllPlanList.refresh()
        }, 1000 * 60 * 10)
        return () => {
            clearInterval(time)
        }
    }, [getAllPlanList])

    // 下载
    const downLoadExcel = useCallback(() => {
        setDownLoadLoading(true)
        let newQueryForm = JSON.parse(JSON.stringify(queryForm))
        // let { page, pageSize, ...newQueryForm } = queryForm
        Object.keys(newQueryForm).forEach((key: any) => {
            if (key === 'mpAppIds') {
                newQueryForm[key] = newQueryForm[key].join()
            } else if (key === 'pitcherIds') {
                newQueryForm[key] = newQueryForm[key]
            }
        })
        if (!newQueryForm['pitcherIds'] && (!queryForm['mpAppIds'] || queryForm['mpAppIds']?.length === 0)) {
            newQueryForm['pitcherIds'] = pichers?.map(item => item.userId)
        }
        downLoadAllAdListApi(newQueryForm).then(res => {
            setDownLoadLoading(false)
            downloadFile1(res, 'octet-stream', formatDate(new Date()) + ".xlsx")
        }).catch(() => setDownLoadLoading(false))
    }, [queryForm, pichers, downLoadLoading])

    return <Space direction='vertical' style={{ width: '100%' }} className="planlist">
        {/* 详情弹窗 */}
        {visible && <PlanDetail visible={visible} onClose={() => { setVisible(false) }} adId={adId} dataStartTime={queryForm?.dataStartTime} dataEndTime={queryForm?.dataEndTime} />}
        <Card hoverable>
            <Space direction='vertical' style={{ width: '100%' }}>
                <Space wrap>
                    <Select
                        placeholder="请选择分组"
                        value={queryForm.groupId}
                        allowClear
                        onChange={(value: number) => {
                            setQueryForm({ ...queryForm, groupId: value, page: 1 })
                        }}>
                        {getAdGroupList?.data?.data?.map((item: { groupName: string, id: number, remark?: string }, index: number) => <Select.Option value={item.id} key={item.id || index}>{item.groupName}</Select.Option>)}
                    </Select>
                    <Select style={{ minWidth: 150 }} placeholder="请选择服务商" allowClear value={queryForm.serviceProviderIdList} onChange={(e) => { setQueryForm({ ...queryForm, page: 1, serviceProviderIdList: e }) }} mode="tags" maxTagCount={1}>
                        {getAgencyList?.data?.data?.map((item: { agencyId: number, agencyName: string }) => <Select.Option value={item?.agencyId?.toString()} key={item.agencyId?.toString()}>{item?.agencyName}</Select.Option>)}
                    </Select>
                    <Select
                        showSearch
                        disabled={queryForm?.mpAppIds?.length > 0}
                        filterOption={(input, option) =>
                            option?.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        value={queryForm.pitcherIds?.map((s: any) => s.toString())} mode='multiple' maxTagCount={1} style={{ minWidth: 150 }} allowClear placeholder="请选择投手" onChange={(value: any[]) => { setQueryForm({ ...queryForm, page: 1, pitcherIds: value }) }}>
                        {pichers?.map((item: { nickName: string, userId: number }, index: number) => <Select.Option value={item.userId.toString()} key={item.userId + '' + index}>{item.nickName}</Select.Option>)}
                    </Select>
                    <Select
                        showSearch
                        mode='multiple'
                        value={queryForm.mpAppIds}
                        onBlur={() => {
                            setMpDatas(mpDatasB)
                        }}
                        onSearch={(value: string) => {
                            if (value) {
                                let arr: any = []
                                mpDatas.forEach((item: { key: { userId: string, nickName: string }, value: any[] }) => {
                                    let i: any = { key: item.key, value: [] }
                                    item?.value?.forEach(v => {
                                        if (v?.nickName?.includes(value)) {
                                            i.value.push(v)
                                        }
                                    })
                                    if (i.value.length > 0) {
                                        arr.push(i)
                                    }
                                })
                                if (arr.length > 0 && JSON.stringify(mpDatas) !== JSON.stringify(arr)) {
                                    setMpDatas(arr)
                                }
                            } else {
                                setMpDatas(mpDatasB)
                            }
                        }}
                        filterOption={(input, option) => {
                            return true
                        }
                        }
                        style={{ minWidth: 220 }} allowClear placeholder="请选择公众号"
                        onChange={(value: string) => {
                            setQueryForm({ ...queryForm, page: 1, mpAppIds: value })
                        }
                        }
                    >
                        {mpDatas?.map((item: { key: { userId: string, nickName: string }, value: any[] }, index: number) => {
                            if (item?.value?.length > 0) {
                                return <Select.OptGroup key={item?.key?.userId} label={item?.key?.nickName}>
                                    {
                                        item.value?.map((value: any) => {
                                            if (value.nickName && !value.nickName.includes('注销')) {
                                                return <Select.Option
                                                    value={value.appid}
                                                    key={value.appid + '' + index}
                                                >
                                                    {value.nickName}
                                                </Select.Option>
                                            }
                                            return null
                                        })
                                    }
                                </Select.OptGroup>
                            }
                            return null
                        })}
                    </Select>
                    <Select style={{ minWidth: 150 }} placeholder="请选择主投书" allowClear value={queryForm?.mainBookList} onChange={(e) => { setQueryForm({ ...queryForm, page: 1, mainBookList: e }) }} mode="multiple" maxTagCount={1}>
                        {getBookListAll?.data?.data?.map((item: { id: number, bookName: string }) => <Select.Option value={item.id} key={item?.id}>{item.bookName}</Select.Option>)}
                    </Select>
                    <Select style={{ width: 150 }} placeholder="请选择广告状态" value={queryForm.adStatus} onChange={(value: number) => {
                        setQueryForm({ ...queryForm, page: 1, adStatus: value })
                    }} allowClear>
                        {
                            Object.keys(GUANGGAOZHUANGTAI).map(key => {
                                return <Select.Option value={key} key={key}>{GUANGGAOZHUANGTAI[key]}</Select.Option>
                            })
                        }
                    </Select>
                    <Select style={{ width: 150 }} placeholder="请选择创意状态" value={queryForm?.creativeStatus} onChange={(e) => { setQueryForm({ ...queryForm, page: 1, creativeStatus: e }) }} allowClear>
                        {
                            Object.keys(CHUANGYIZHUANGTAI).map(key => {
                                return <Select.Option value={key} key={key}>{CHUANGYIZHUANGTAI[key]}</Select.Option>
                            })
                        }
                    </Select>
                    {/* <Select style={{ width: 150 }} placeholder="请选择关注状态" value={queryForm?.followStatus} onChange={(e) => { setQueryForm({ ...queryForm, followStatus: e }) }} allowClear>
                        <Select.Option value={1}>已关注</Select.Option>
                        <Select.Option value={2}>未关注</Select.Option>
                    </Select> */}

                </Space>
                <Space wrap>
                    <Input placeholder="请输入计划名称或ID" allowClear value={queryForm?.planIdOrName} onChange={(e) => { setQueryForm({ ...queryForm, page: 1, planIdOrName: e.target.value }) }} />
                    <Input placeholder="请输入广告名称或ID" allowClear value={queryForm?.adIdOrName} onChange={(e) => { setQueryForm({ ...queryForm, page: 1, adIdOrName: e.target.value }) }} />
                    <Input placeholder="请输入创意名称或ID" allowClear value={queryForm?.creativeIdOrName} onChange={(e) => { setQueryForm({ ...queryForm, page: 1, creativeIdOrName: e.target.value }) }} />
                    <DatePicker.RangePicker placeholder={['数据开始日期', '数据结束日期']} onChange={(mo: any, str: string[]) => { setQueryForm({ ...queryForm, page: 1, dataStartTime: str[0], dataEndTime: str[1] }) }} value={queryForm?.dataStartTime && queryForm?.dataEndTime ? [moment(queryForm?.dataStartTime), moment(queryForm?.dataEndTime)] : null} />
                    <DatePicker.RangePicker placeholder={['创建开始日期', '创建结束日期']} onChange={(mo: any, str: string[]) => { setUnix(str) }} value={queryForm?.createStartTime && queryForm?.createEndTime ? [moment(queryForm?.createStartTime * 1000), moment(queryForm?.createEndTime * 1000)] : null} />
                    {/* <DatePicker onChange={(e) => { e ? setQueryForm({ ...queryForm, dataTime: moment(e).format('YYYY-MM-DD') }) : setQueryForm({ ...queryForm, dataTime: '' }) }} value={queryForm?.dataTime ? moment(queryForm?.dataTime) : null} /> */}
                    <Button type="primary" onClick={() => { getList(queryForm) }}>搜索</Button>
                </Space>
            </Space>
        </Card>

        <TableData
            columns={columnsPlanList(detail)}
            ajax={getAllPlanList}
            dataSource={getAllPlanList?.data?.data?.adInfoVoList}
            loading={getAllPlanList?.loading}
            scroll={{ y: 600 }}
            total={getAllPlanList?.data?.data?.totalCount}
            page={getAllPlanList?.data?.data?.page}
            pageSize={getAllPlanList?.data?.data?.pageSize}
            leftChild={<Button size="small" icon={<CloudDownloadOutlined />} loading={downLoadLoading} onClick={downLoadExcel}>下载</Button>}
            onChange={(props: any) => {
                let { sortData, pagination } = props
                let { current, pageSize } = pagination
                let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                newQueryForm.page = current
                newQueryForm.pageSize = pageSize
                if (sortData && JSON.stringify('sortData') !== '{}') {
                    let { field, order } = sortData   // descend 降序 大到小  ascend 升序 小到大
                    if (order) {
                        newQueryForm.sortField = field
                        newQueryForm.sort = order === 'ascend' ? 'ASC' : 'DESC'
                    } else {
                        Object.keys(newQueryForm).forEach(key => {
                            if (key === 'sortField' || key === 'sort') {
                                delete newQueryForm[key]
                            }
                        })
                    }
                } else {
                    Object.keys(newQueryForm).forEach(key => {
                        if (key === 'sortField' || key === 'sort') {
                            delete newQueryForm[key]
                        }
                    })
                }
                setQueryForm({ ...newQueryForm })
                getList({ ...newQueryForm })
            }}
            config={guanggao}
            configName={'广告列表'}
        />
    </Space>
}

export default React.memo(PlanList)