import { Table, Button, Card, Space, message, Input, Tag, Select, DatePicker } from "antd"
import React, { useState, useEffect, useCallback } from "react"
import CreactPage from "../components/createPage"
import { getWeAppList, deletePage, analog, configDel, config, configList, userLists, orderList, orderCallback, getPageListNew, getGzhList } from '@/services/launch/page'
import { useAjax } from "@/Hook/useAjax"
import columns from './tableConfig'
import tscolumns from './tsTableConfig'
import useCopy from "@/Hook/useCopy"
import { useModel } from "umi"
import CallBackModel from "./callBackModel"
import callbackTableConfig from './callbackTableConfig'
import orderTableConfig from './orderTableConfig'
import moment from "moment"
import weAppTableConfig from "./weAppTableConfig"
import './table.less'
function StaticHtml() {
    const [show, setShow] = useState(false)
    const { copy } = useCopy()
    const getWeApp = useAjax((params) => getWeAppList(params))
    const getGzh = useAjax((params) => getGzhList(params))
    const getListNew = useAjax((params) => getPageListNew(params))
    const delPage = useAjax((params) => deletePage(params))
    const getUserList = useAjax((params) => userLists(params))
    const getAnalog = useAjax((params) => analog(params))
    const deleteConfig = useAjax((id) => configDel(id))
    const configAdd = useAjax((params) => config(params))
    const getConfigList = useAjax((params) => configList(params))
    const get_order_list = useAjax((params) => orderList(params))
    const put_order = useAjax((id) => orderCallback(id))
    const [editData, setEditData] = useState(null)
    const [sharePageName, setSharePageName] = useState('')
    const [mpAppId, setMpAppId] = useState([])
    const [key, setKey] = useState('1')
    const [sharePageUrl, setSharePageUrl] = useState('')
    // const userList = useModel('useOperating.useExamine', model => model.state.userList)
    const userInfo = useModel('@@initialState', model => model.initialState?.currentUser)
    const userList = useModel('useOperating.useWxGroupList', model => model.state.filterWxs)
    const [actionMpAppId, setActionMpAppId] = useState([])
    const [callbackShow, setCallBackShow] = useState(false)
    const [actionCallbackList, setActionCallbackList] = useState(null)
    // console.log('userList', userList)
    const [orderParams, setOrderParams] = useState<any>({
        adid: '',//广告ID
        amountMax: undefined,//最大金额
        amountMin: undefined,//最小金额
        callBackStatus: undefined,//回传状态
        isFirstOrder: undefined,//是否首单
        mpAppIdList: [],//公众号
        orderTimeEnd: '',//订单结束时间
        orderTimeStart: '',//订单开始时间
        orderType: undefined,//订单类型
        pageNum: 1,
        pageSize: 20,
        regTimeEnd: '',//关注结束时间
        regTimeStart: '',//关注开始时间
    })
    // ===================================落地页=============================================
    // //添加TS视频加载js
    // useEffect(() => {
    //     if (!document.getElementById('jsmpeg')) {
    //         let jsmpeg = document.createElement('script')
    //         jsmpeg.id = 'jsmpeg'
    //         jsmpeg.src = 'https://mp.zanxiangnet.com/aaplugin/h/jsmpeg.js'
    //         document.head.append(jsmpeg)
    //     }
    //     return () => {
    //         let jsmpeg = document.getElementById('jsmpeg')
    //         jsmpeg && document.head.removeChild(jsmpeg)
    //     }

    // }, [])
    // 获取列表
    useEffect(() => {
        query({ pageNum: 1, pageSize: 20 })
    }, [])
    // 搜索
    const query = useCallback((params) => {
        let mpAppIdList: any = mpAppId?.length > 0 ? mpAppId : userList?.map((item: { appid: any }) => item?.appid)
        if (mpAppIdList?.length > 0) {
            getListNew.run({ ...params, sharePageName, mpAppIdList })
        }
    }, [sharePageName, mpAppId])
    // 编辑
    const edit = useCallback((data) => {
        setEditData(data)
        setShow(true)
    }, [])
    // 删除page
    const del = useCallback((id) => {
        delPage.run({ id }).then(res => {
            if (res) {
                message.success('删除成功！')
                getListNew.refresh()
            }
        })
    }, [])
    // =============================================调试=============================================
    // 获取用户列表
    const getUsers = useCallback(() => {
        console.log(sharePageUrl)
        if (sharePageUrl) {
            getUserList.run({ url: sharePageUrl })
        }
    }, [sharePageUrl])
    // 回调
    const getAnalogCallback = useCallback((id) => {
        getAnalog.run({ sharePageUserCallId: id })
    }, [])
    // =========================================回传配置=============================================
    // 首次获取回传全部公众号列表
    useEffect(() => {
        getConfig({ pageNum: 1, pageSize: 20, mpAppIdList: userList?.map((item: { appid: any }) => item?.appid) })
    }, [])
    // 获取回传列表
    const getConfig = useCallback((params) => {
        let mpAppIdList: any = actionMpAppId?.length > 0 ? actionMpAppId : userList?.map((item: { appid: any }) => item?.appid)
        if (mpAppIdList?.length > 0) {
            getConfigList.run({ pageNum: 1, pageSize: 20, ...params, mpAppIdList: mpAppIdList })
        }
    }, [actionMpAppId])
    // 删除回传
    const delConfig = useCallback((id) => {
        deleteConfig.run(id).then(res => {
            if (res) {
                getConfigList.refresh()
            }
        })
    }, [getConfigList])
    // 创建更新回传
    const addConfig = useCallback((values) => {
        console.log(values)
        if (!values.mpAppId) {
            message.warning('请选择公众号')
            return
        }
        if (!values?.id) {
            delete values.id
        }
        if (values.callBackType !== 2) {
            delete values.callBackCount
            delete values.callBackSkip
        } else {
            if (!values.callBackCount) {
                message.warning('请输入回传量')
                return
            }
            if (!values.callBackSkip) {
                message.warning('请输入漏单量')
                return
            }
        }
        if (values?.regLimitType === 1 && !values?.bHour) {
            message.warning('关注后必须填入时间')
            return
        }
        if (values?.regLimitType === 1 && values?.bHour) {
            values['regAfterHour'] = values?.bHour
        }
        if (values?.regLimitType === 0 && values?.aHour) {
            values['regAfterHour'] = values?.aHour
        }
        delete values['aHour']
        delete values['bHour']
        configAdd.run(values).then(res => {
            console.log(res)
            if (res) {
                getConfigList.refresh()
                setCallBackShow(false)
                setActionCallbackList(null)
            }
        })
    }, [getConfigList])
    // 编辑
    const editCallback = useCallback((data) => {
        setActionCallbackList(data)
        setCallBackShow(true)
    }, [])
    // ====================================补单=========================
    // 首次获取列表
    useEffect(() => {
        getOrderList({ pageNum: 1, pageSize: 20 })
    }, [])
    // 获取列表
    const getOrderList = useCallback((params) => {
        let param = JSON.parse(JSON.stringify(params))
        Object.keys(param).forEach(key => {
            (param[key] === '' || params[key] === undefined) && (delete param[key])
        })
        if (param['isFirstOrder'] || param['isFirstOrder'] === 0) {
            param['isFirstOrder'] = !!param['isFirstOrder']
        }
        let mpAppIdList = param['mpAppIdList']?.length > 0 ? param['mpAppIdList'] : userList?.map((item: { appid: any }) => item?.appid)
        if (mpAppIdList?.length > 0) {
            get_order_list.run({ pageNum: 1, pageSize: 20, ...param, mpAppIdList }).then(res => {
                console.log(res)
            })
        }
    }, [])
    // 补单
    const putOrder = useCallback((id) => {
        put_order.run(id).then(res => {
            get_order_list.refresh()
        })
    }, [get_order_list])
    // 重置搜索条件
    const initQuery = useCallback(() => {
        setOrderParams(
            {
                adid: '',//广告ID
                amountMax: undefined,//最大金额
                amountMin: undefined,//最小金额
                callBackStatus: undefined,//回传状态
                isFirstOrder: undefined,//是否首单
                mpAppIdList: [],//公众号
                orderTimeEnd: '',//订单结束时间
                orderTimeStart: '',//订单开始时间
                orderType: undefined,//订单类型
                pageNum: 1,
                pageSize: 20,
                regTimeEnd: '',//关注结束时间
                regTimeStart: '',//关注开始时间
            }
        )
    }, [])
    // ====================================小程序列表=========================
    useEffect(() => {
        if (userInfo?.userId) {
            getWeApp.run(userInfo?.userId)
        }
    }, [userInfo])
    // ====================================公众号列表=========================
    useEffect(() => {
        if (userInfo?.userId) {
            getGzh.run(userInfo?.userId)
        }
    }, [userInfo])
    return <Card
        tabList={[
            {
                key: '1',
                tab: '落地页'
            },
            {
                key: '2',
                tab: '调试'
            },
            {
                key: '3',
                tab: '回传配置'
            },
            {
                key: '4',
                tab: '补单'
            },
            {
                key: '5',
                tab: '我的小程序'
            },
        ]}
        activeTabKey={key}
        onTabChange={(key) => {
            setKey(key)
        }}
    >
        {/* 落地页 */}
        {
            key === '1' && <>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
                    <Space>
                        <Select
                            style={{ minWidth: 200 }}
                            mode="multiple"
                            allowClear
                            onChange={(value: any) => {
                                setMpAppId(value)
                            }}
                            value={mpAppId}
                            showSearch
                            filterOption={(input, option: any) =>
                                option?.children?.toLowerCase()?.indexOf(input?.toLowerCase()) >= 0
                            }
                            placeholder='选择公众号'
                        >
                            {
                                userList?.map((user: any) => {
                                    return <Select.Option key={user?.appid} value={user?.appid}>{user?.nickName}</Select.Option>
                                })
                            }
                        </Select>
                        <Input placeholder='请输入落地页名称搜索' value={sharePageName} onChange={(e) => {
                            let value = e.target.value
                            setSharePageName(value)
                        }} allowClear />
                        <Button type='primary' onClick={() => {
                            query({ pageNum: 1, pageSize: 20 })
                        }}>搜索</Button>
                    </Space>
                    <Button type='primary' onClick={() => { setShow(true) }}>新增落地页</Button>
                </div>
                <Table
                    dataSource={getListNew?.data?.records}
                    loading={getListNew?.loading}
                    columns={columns(copy, edit, del, getWeApp?.data, getGzh?.data)}
                    size='small'
                    pagination={{
                        total: getListNew?.data?.total,
                        current: getListNew?.data?.current,
                        pageSize: getListNew?.data?.size,
                        showSizeChanger: true,
                        pageSizeOptions: ['10', '20', '50', '70', '100'],
                        showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                        onChange: (page, pageSize) => {
                            query({ pageNum: page, size: pageSize })
                        }
                    }}
                />
            </>
        }
        {/* 调试 */}
        {
            key === '2' && <>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
                    <Space>
                        <Input placeholder='请输入落地页地址' value={sharePageUrl} onChange={(e) => {
                            let value = e.target.value
                            setSharePageUrl(value)
                        }} allowClear />
                        <Button type='primary' onClick={getUsers}>搜索</Button>
                    </Space>
                </div>
                <Table
                    dataSource={getUserList?.data}
                    loading={getUserList?.loading}
                    columns={tscolumns(getAnalogCallback)}
                    size='small'
                />
            </>
        }
        {/* 回传配置 */}
        {
            key === '3' && <>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
                    <Space >
                        <Select
                            style={{ minWidth: 200 }}
                            mode="multiple"
                            allowClear
                            onChange={(value) => {
                                setActionMpAppId(value)
                            }}
                            value={actionMpAppId}
                            showSearch
                            filterOption={(input, option: any) =>
                                option?.children?.toLowerCase()?.indexOf(input?.toLowerCase()) >= 0
                            }
                            placeholder='选择公众号'
                        >
                            {
                                userList?.map((user: any) => {
                                    return <Select.Option key={user?.appid} value={user?.appid}>{user?.nickName}</Select.Option>
                                })
                            }
                        </Select>
                        <Button type='primary' onClick={() => { getConfig({}) }}>搜索</Button>
                    </Space>
                    <Button type='primary' onClick={() => { setCallBackShow(true) }}>新增回传</Button>
                </div>
                <Table
                    dataSource={getConfigList?.data?.records}
                    loading={getConfigList?.loading}
                    columns={callbackTableConfig(editCallback, delConfig)}
                    size='small'
                    pagination={
                        {
                            total: getConfigList?.data?.total,//总共多少条数据,服务器给,设置后分页自动计算页数
                            showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                            showSizeChanger: true,
                            showLessItems: true,
                            defaultCurrent: 1,
                            defaultPageSize: 20,//默认初始的每页条数
                            current: getConfigList?.data?.current || 1,
                            pageSize: getConfigList?.data?.size || 20,
                            onChange: (page, pageSize) => {
                                getConfig({ pageNum: page, pageSize })
                            }
                        }
                    }
                />
            </>
        }
        {/* 补单 */}
        {
            key === '4' && <>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
                    <Space wrap>
                        <Select
                            style={{ minWidth: 200 }}
                            mode="multiple"
                            allowClear
                            onChange={(value) => {
                                setOrderParams({ ...orderParams, mpAppIdList: value })
                            }}
                            value={orderParams.mpAppIdList}
                            showSearch
                            filterOption={(input, option: any) =>
                                option?.children?.toLowerCase()?.indexOf(input?.toLowerCase()) >= 0
                            }
                            placeholder='选择公众号'
                        >
                            {
                                userList?.map((user: any) => {
                                    return <Select.Option key={user?.appid} value={user?.appid}>{user?.nickName}</Select.Option>
                                })
                            }
                        </Select>
                        <Input placeholder='广告ID' allowClear
                            value={orderParams.adid}
                            onChange={(e) => {
                                let value = e.target.value
                                if (value.match(/^[1-9]\d*$/) || value === '') {
                                    setOrderParams({ ...orderParams, adid: value ? Number(value) : '' })
                                } else {
                                    message.error('请输入正整数')
                                }
                            }}
                        />
                        <Input
                            style={{ width: 100 }}
                            placeholder='最大金额'
                            allowClear
                            value={orderParams.amountMax}
                            onChange={(e) => {
                                let value = e.target.value
                                if (value.match(/^[1-9]\d*$/) || value === '') {
                                    setOrderParams({ ...orderParams, amountMax: value ? Number(value) : '' })
                                } else {
                                    message.error('请输入正整数')
                                }
                            }}
                        />
                        <Input
                            style={{ width: 100 }}
                            placeholder='最小金额'
                            allowClear
                            value={orderParams.amountMin}
                            onChange={(e) => {
                                let value = e.target.value
                                if (value.match(/^[1-9]\d*$/) || value === '') {
                                    setOrderParams({ ...orderParams, amountMin: value ? Number(value) : '' })
                                } else {
                                    message.error('请输入正整数')
                                }
                            }}
                        />
                        <Select
                            style={{ minWidth: 150 }}
                            allowClear
                            onChange={(value) => {
                                setOrderParams({ ...orderParams, callBackStatus: value })
                            }}
                            value={orderParams.callBackStatus}
                            placeholder='回传状态'
                        >
                            <Select.Option value={0}>未回传</Select.Option>
                            <Select.Option value={1}>已回传</Select.Option>
                        </Select>
                        <Select
                            style={{ minWidth: 180 }}
                            allowClear
                            onChange={(value) => {
                                setOrderParams({ ...orderParams, orderType: value })
                            }}
                            value={orderParams.orderType}
                            placeholder='订单类型'
                        >
                            <Select.Option value={0}>关注自然日订单</Select.Option>
                            <Select.Option value={1}>关注12小时内订单</Select.Option>
                            <Select.Option value={2}>关注24小时内订单</Select.Option>
                        </Select>
                        <DatePicker onChange={(time, str) => {
                            setOrderParams({ ...orderParams, orderTimeStart: str })
                        }} placeholder='订单开始时间' value={orderParams.orderTimeStart ? moment(orderParams.orderTimeStart) : undefined} />
                        <DatePicker onChange={(time, str) => {
                            setOrderParams({ ...orderParams, orderTimeEnd: str })
                        }} placeholder='订单结束时间' value={orderParams.orderTimeEnd ? moment(orderParams.orderTimeEnd) : undefined} />
                        <DatePicker onChange={(time, str) => {
                            setOrderParams({ ...orderParams, regTimeStart: str })
                        }} placeholder='关注开始时间' value={orderParams.regTimeStart ? moment(orderParams.regTimeStart) : undefined} />
                        <DatePicker onChange={(time, str) => {
                            setOrderParams({ ...orderParams, regTimeEnd: str })
                        }} placeholder='关注结束时间' value={orderParams.regTimeEnd ? moment(orderParams.regTimeEnd) : undefined} />
                        <Select
                            style={{ minWidth: 150 }}
                            allowClear
                            onChange={(value) => {
                                setOrderParams({ ...orderParams, isFirstOrder: value })
                            }}
                            value={orderParams.isFirstOrder}
                            placeholder='是否首单'
                        >
                            <Select.Option value={1}>首单</Select.Option>
                            <Select.Option value={0}>非首单</Select.Option>
                        </Select>
                        <Button type='primary' onClick={() => { getOrderList({ pageNum: 1, pageSize: 20, ...orderParams }) }}>搜索</Button>
                        <Button type='primary' onClick={initQuery}>重置</Button>
                    </Space>
                </div>
                <Table
                    dataSource={get_order_list?.data?.records}
                    loading={get_order_list?.loading}
                    columns={orderTableConfig(putOrder)}
                    size='small'
                    scroll={{ x: 1100 }}
                    pagination={
                        {
                            total: get_order_list?.data?.total,//总共多少条数据,服务器给,设置后分页自动计算页数
                            showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                            showSizeChanger: true,
                            showLessItems: true,
                            defaultCurrent: 1,
                            defaultPageSize: 20,//默认初始的每页条数
                            current: get_order_list?.data?.current || 1,
                            pageSize: get_order_list?.data?.size || 20,
                            onChange: (page, pageSize) => {
                                console.log(page, pageSize)
                                getOrderList({ ...orderParams, pageNum: page, pageSize })
                            }
                        }
                    }
                />
            </>
        }
        {/* 我的小程序列表 */}{
            key === '5' && <>
                <Table
                    dataSource={getWeApp?.data}
                    loading={getWeApp?.loading}
                    columns={weAppTableConfig()}
                    size='small'
                    rowClassName={(record) => {
                        if (record?.useStatus === 1) {
                            return 'disableWeAppList'
                        }
                        return ''
                    }}
                />
            </>
        }
        {
            show && <CreactPage visible={show} onHide={() => {
                setShow(false)
            }} editData={editData} initEdit={() => setEditData(null)} getList={() => getListNew.refresh()} userList={userList} getWeAppList={getWeApp?.data} getGzhList={getGzh?.data} />
        }
        {
            callbackShow && <CallBackModel visible={callbackShow} hide={() => {
                setCallBackShow(false)
                setActionCallbackList(null)
            }} userList={userList} userInfo={userInfo} addConfig={addConfig} actionCallbackList={actionCallbackList} />
        }
    </Card>
}
export default StaticHtml