import QueryForm from "@/components/QueryForm"
import { useAjax } from "@/Hook/useAjax"
import { getOrderListApi, getOrderTotalApi, OrderListType } from "@/services/gameData/order"
import React, { useEffect, useState } from "react"
import TableData from "../components/TableData"
import columns12 from "./tableConfig"
import { getPresets } from "@/components/QueryForm/const"
import moment from "moment"
import Details from "./details"
import Back from "./back"


const Order: React.FC = () => {

    /***************************/
    const [queryForm, setQueryForm] = useState<OrderListType>({ 
        pageNum: 1, 
        pageSize: 20, 
        sourceSystem: 'ZX_ONE', 
        sortFiled: 'orderCreateTime', 
        sortType: 'desc',
        beginDate: moment().format('YYYY-MM-DD'),
        endDate: moment().format('YYYY-MM-DD')
    })
    const [totalData, setTotalData] = useState<any[]>([])
    const [visible, setVisible] = useState<boolean>(false)
    const [orderData, setOrderData] = useState<any>({})
    const [backVisible, setBackVisible] = useState<boolean>(false)
    const [backData, setBackData] = useState<any>({})
    const getOrderList = useAjax((params) => getOrderListApi(params))
    const getOrderTotal = useAjax((params) => getOrderTotalApi(params))
    /***************************/

    useEffect(() => {
        getOrderList.run(queryForm)
        getOrderTotal.run(queryForm).then(res => {
            res.id = 1
            res.day = '总计'
            setTotalData([res])
        })
    }, [queryForm])

    // 详情
    const onDetail = (data: any) => {
        setOrderData(data)
        setVisible(true)
    }

    const back = (data: any) => {
        setBackData(data)
        setBackVisible(true)
    }

    return <div>
        {backVisible && <Back
            data={backData}
            visible={backVisible}
            onClose={() => { setBackVisible(false); setBackData({}) }}
            onChange={() => {
                setBackVisible(false); 
                setBackData({});
                getOrderList.refresh()
            }}
        />}
        <TableData
            leftChild={<QueryForm
                initialValues={{ sourceSystem: 'ZX_ONE', placeAnOrderTime: [moment(), moment()] }}
                onChange={(data: any) => {
                    const { os, regStartDay, orderStatus, gameUserId, regEndDay, payTime, placeAnOrderTime, agentId, regPayIntervalTime, ...params } = data
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    newQueryForm.pageNum = 1
                    newQueryForm.deviceSystem = os
                    newQueryForm.status = orderStatus
                    newQueryForm.userId = gameUserId
                    newQueryForm.channelId = agentId
                    if (regStartDay && regEndDay) {
                        newQueryForm.regTimeStart = regStartDay
                        newQueryForm.regTimeEnd = regEndDay
                    } else {
                        delete newQueryForm.regTimeStart
                        delete newQueryForm.regTimeEnd
                    }
                    if (payTime && payTime?.length > 0) {
                        newQueryForm.payTimeStart = moment(payTime[0]).format('YYYY-MM-DD')
                        newQueryForm.payTimeEnd = moment(payTime[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm.payTimeStart
                        delete newQueryForm.payTimeEnd
                    }

                    if (placeAnOrderTime && placeAnOrderTime?.length > 0) {
                        newQueryForm.beginDate = moment(placeAnOrderTime[0]).format('YYYY-MM-DD')
                        newQueryForm.endDate = moment(placeAnOrderTime[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm.beginDate
                        delete newQueryForm.endDate
                    }

                    if (regPayIntervalTime?.length > 0 && (regPayIntervalTime[0] || regPayIntervalTime[1])) {
                        newQueryForm.regPayIntervalTimeMin = regPayIntervalTime[0]
                        newQueryForm.regPayIntervalTimeMax = regPayIntervalTime[1]
                    }
                    setQueryForm({ ...newQueryForm, ...params })
                }}
                isSource
                isAccountId
                isCpName
                isCpOrderId
                isCpStatus
                isOs
                isOrderLy
                isGameIds
                isFirstRecharge
                isMerchantNo
                isMerchantOrderNo
                isOrderId
                isPayWay
                isSysUserId
                isProductName
                isGameRoleName
                isServerName
                isSourceServerName
                isPayStatus
                isGameUserId
                isProjectId1
                isPromotionId1
                isUserName
                isPayIntervalTime={{ tips: '充值距注册时间区间（分钟）' }}
                isAgentId
                isBackStatus
                payTimeDay={{ ranges: getPresets() }}
                isRegDay={{ ranges: getPresets() }}
                placeAnOrderDay={{ ranges: getPresets() }}
            />}
            isZj
            totalData={totalData}
            scroll={{ x: 1000, y: 600 }}
            ajax={getOrderList}
            fixed={{ left: 3, right: 3 }}
            dataSource={getOrderList?.data?.records?.map((item: any, index: number) => ({ ...item, id: Number(queryForm.pageNum.toString() + index.toString()) }))} // ?.map((item: any, index: number) => ({ ...item, id: item.sourceSystem + '' + item.id }))
            total={getOrderList?.data?.total}
            page={queryForm.pageNum}
            pageSize={queryForm.pageSize}
            title='订单明细'
            onChange={(props: any) => {
                let { pagination, sortData } = props
                let { current, pageSize } = pagination
                let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                if (sortData && sortData?.order) {
                    newQueryForm['sortType'] = sortData?.order === 'ascend' ? 'asc' : 'desc'
                    newQueryForm['sortFiled'] = sortData?.field
                } else {
                    delete newQueryForm['sortType']
                    delete newQueryForm['sortFiled']
                }
                newQueryForm.pageNum = current
                newQueryForm.pageSize = pageSize
                setQueryForm({ ...newQueryForm })
            }}
            config={columns12(onDetail, back)}
            configName={'订单明细'}
        />

        {/* <TablePro
            leftChild={<QueryForm
                initialValues={{ sourceSystem: 'ZX_ONE' }}
                onChange={(data: any) => {
                    const { os, regStartDay, orderStatus, gameUserId, regEndDay, payTime, placeAnOrderTime, agentId, regPayIntervalTime, ...params } = data
                    let newQueryForm = JSON.parse(JSON.stringify(queryForm))
                    newQueryForm.pageNum = 1
                    newQueryForm.deviceSystem = os
                    newQueryForm.status = orderStatus
                    newQueryForm.userId = gameUserId
                    newQueryForm.channelId = agentId
                    if (regStartDay && regEndDay) {
                        newQueryForm.regTimeStart = regStartDay
                        newQueryForm.regTimeEnd = regEndDay
                    } else {
                        delete newQueryForm.regTimeStart
                        delete newQueryForm.regTimeEnd
                    }
                    if (payTime && payTime?.length > 0) {
                        newQueryForm.payTimeStart = moment(payTime[0]).format('YYYY-MM-DD')
                        newQueryForm.payTimeEnd = moment(payTime[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm.payTimeStart
                        delete newQueryForm.payTimeEnd
                    }

                    if (placeAnOrderTime && placeAnOrderTime?.length > 0) {
                        newQueryForm.beginDate = moment(placeAnOrderTime[0]).format('YYYY-MM-DD')
                        newQueryForm.endDate = moment(placeAnOrderTime[1]).format('YYYY-MM-DD')
                    } else {
                        delete newQueryForm.beginDate
                        delete newQueryForm.endDate
                    }

                    if (regPayIntervalTime?.length > 0 && (regPayIntervalTime[0] || regPayIntervalTime[1])) {
                        newQueryForm.regPayIntervalTimeMin = regPayIntervalTime[0]
                        newQueryForm.regPayIntervalTimeMax = regPayIntervalTime[1]
                    }
                    setQueryForm({ ...newQueryForm, ...params })
                }}
                isSource
                isAccountId
                isCpName
                isCpOrderId
                isCpStatus
                isOs
                isOrderLy
                isGameIds
                isFirstRecharge
                isMerchantNo
                isMerchantOrderNo
                isOrderId
                isPayWay
                isSysUserId
                isProductName
                isGameRoleName
                isServerName
                isSourceServerName
                isPayStatus
                isGameUserId
                isProjectId1
                isPromotionId1
                isUserName
                isPayIntervalTime={{ tips: '充值距注册时间区间（分钟）' }}
                isAgentId
                payTimeDay={{ ranges: getPresets() }}
                isRegDay={{ ranges: getPresets() }}
                placeAnOrderDay={{ ranges: getPresets() }}
            />}
            config={columns12(onDetail)}
            fixed={{ left: 3, right: 2 }}
            configName={'订单明细'}
            title='订单明细'
            ajax={getOrderList}
        /> */}

        {visible && <Details visible={visible} initialValues={orderData} onClose={() => setVisible(false)} />}
    </div>
}

export default Order