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


const PlanList: React.FC = () => {
    const { getAllPlanList, getBookListAll, getAdqAccountList } = useModel('useAdMonitor.useMonitor')
    const { getPicherList } = useModel('useOperating.useWxGroupList')
    // 变量开始
    const [queryForm, setQueryForm] = useState<allPlanProps>({ pageNum: 1, pageSize: 20, createStartTime: moment().subtract(3, 'days').format('YYYY-MM-DD'), createEndTime: moment().format('YYYY-MM-DD') }) // 搜索变量
    const [visible, setVisible] = useState<boolean>(false) // 详情弹窗控制
    const [adId, setAdId] = useState<any>()
    const [downLoadLoading, setDownLoadLoading] = useState<boolean>(false)
    // 变量结束

    // 获取广告账号
    useEffect(() => {
        getAdqAccountList.run()
    }, [])

    // 获取投手
    useEffect(() => {
        getPicherList.run()
    }, [])

    useEffect(() => {
        if (sessionStorage.getItem('ADIDORNAME')) {
            let data = JSON.parse(sessionStorage.getItem('ADIDORNAME') as any)
            setQueryForm({ ...queryForm, createStartTime: undefined, createEndTime: undefined, adgroup: data.adgroupId, campaign: data.campaignId, sysUserId: data.putUserId ? data.putUserId?.toString()?.split() : [], accountId: data?.accountId?.toString()?.split() })
            sessionStorage.removeItem('ADIDORNAME')
        }
    }, [])

    // 获取分组
    useEffect(() => {
        getList()
    }, [queryForm])

    const getList = useCallback(() => {
        getAllPlanList.run(queryForm)
    }, [queryForm])

    /** 获取书 */
    useEffect(() => {
        getBookListAll.run()
    }, [])

    // 设置创建时间
    const setUnix = ([str, end]: string[]) => {
        if (str && end) {
            setQueryForm({ ...queryForm, pageNum: 1, createStartTime: moment(str).format('YYYY-MM-DD'), createEndTime: moment(end).format('YYYY-MM-DD') })
        } else {
            const { createStartTime, createEndTime, ...newQueyFor } = queryForm
            setQueryForm({ ...newQueyFor, pageNum: 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))
        downLoadAllAdListApi(newQueryForm).then(res => {
            setDownLoadLoading(false)
            downloadFile1(res, 'octet-stream', formatDate(new Date()) + ".xlsx")
        }).catch(() => setDownLoadLoading(false))
    }, [queryForm, downLoadLoading])

    return <Space direction='vertical' style={{ width: '100%' }} className="planlist">
        {/* 详情弹窗 */}
        {visible && <PlanDetail visible={visible} onClose={() => { setVisible(false) }} data={adId} dataStartTime={queryForm?.dataStartTime} dataEndTime={queryForm?.dataEndTime} />}
        <Card hoverable>
            <Space direction='vertical' style={{ width: '100%' }}>
                <Space wrap>
                    <Select
                        showSearch
                        disabled={queryForm?.accountId?.length > 0}
                        filterOption={(input, option) =>
                            (option?.children as any).toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        value={queryForm?.sysUserId}
                        mode='multiple'
                        maxTagCount={1}
                        style={{ minWidth: 150 }}
                        allowClear
                        placeholder="请选择投手"
                        onChange={(value: any[]) => { setQueryForm({ ...queryForm, pageNum: 1, sysUserId: value }) }}
                    >
                        {getPicherList?.data?.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'
                        maxTagCount={1}
                        value={queryForm.accountId}
                        style={{ minWidth: 220 }}
                        allowClear
                        placeholder="请选择广告账号"
                        filterOption={(input, option) =>
                            (option?.children as any).toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        onChange={(value: string) => {
                            setQueryForm({ ...queryForm, accountId: value, pageNum: 1 })
                        }}
                    >
                        {getAdqAccountList?.data?.data?.map((item: { id: number, accountId: number, wechatAccountName: string }) => <Select.Option
                            value={item.accountId}
                            key={item.id}
                        >
                            {item.accountId}
                        </Select.Option>)}
                    </Select>
                    {/* <Select style={{ minWidth: 150 }} placeholder="请选择主投书" allowClear value={queryForm?.mainBookList} onChange={(e) => { setQueryForm({ ...queryForm, pageNum: 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, pageNum: 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, pageNum: 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> */}

                    <Input placeholder="请输入计划名称或ID" allowClear value={queryForm?.campaign} onChange={(e) => { setQueryForm({ ...queryForm, pageNum: 1, campaign: e.target.value }) }} />
                    <Input placeholder="请输入广告名称或ID" allowClear value={queryForm?.adgroup} onChange={(e) => { setQueryForm({ ...queryForm, pageNum: 1, adgroup: e.target.value }) }} />
                    <Input placeholder="请输入创意ID" allowClear value={queryForm?.creativeId} onChange={(e) => { setQueryForm({ ...queryForm, pageNum: 1, creativeId: e.target.value }) }} />

                </Space>
                <Space wrap>
                    <DatePicker.RangePicker placeholder={['数据开始日期', '数据结束日期']} onChange={(mo: any, str: string[]) => { setQueryForm({ ...queryForm, pageNum: 1, dataStartTime: str[0], dataEndTime: str[1] }) }} value={(queryForm?.dataStartTime && queryForm?.dataEndTime ? [moment(queryForm?.dataStartTime), moment(queryForm?.dataEndTime)] : null) as any} />
                    <DatePicker.RangePicker placeholder={['创建开始日期', '创建结束日期']} onChange={(mo: any, str: string[]) => { setUnix(str) }} value={(queryForm?.createStartTime && queryForm?.createEndTime ? [moment(queryForm?.createStartTime), moment(queryForm?.createEndTime)] : null) as any} />
                    {/* <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() }}>搜索</Button>
                </Space>
            </Space>
        </Card>

        <TableData
            columns={columnsPlanList(detail)}
            ajax={getAllPlanList}
            dataSource={getAllPlanList?.data?.data?.records}
            loading={getAllPlanList?.loading}
            scroll={{ y: 600 }}
            fixed={{ left: 0, right: 1 }}
            total={getAllPlanList?.data?.data?.total}
            page={queryForm.pageNum}
            pageSize={queryForm.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.pageNum = 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 })
            }}
            config={guanggao}
            configName={'广告列表'}
        />
    </Space>
}

export default React.memo(PlanList)