import { useAjax } from "@/Hook/useAjax"
import { GameServerListProps, delGameServerApi, gameSupperListApi, getGameServerListApi, mergeAddOrUpdateApi, unMergeServerListApi,gameServerlistexcelApi } from "@/services/gameData/roleOperate"
import { Button, Card, Col, DatePicker, Form, Input, Modal, Radio, Row, Select, Space, message } from "antd"
import React, { useCallback, useEffect, useState } from "react"
import moment from "moment"
import { getGameChoiceListApi } from "@/services/gameData"
import { getPresets } from "@/components/QueryForm/const"
import Tables from "@/components/Tables"
import columnsPos from "./tableConfig"
import style from '../../components/TableData/index.less'
import { PlusOutlined } from "@ant-design/icons"
import EditModal from "./editModal"
import UploadExcel from "./uploadExcel"
import AssignUser from "./assignUser"
import DownloadExcel from "@/components/DownloadExcel"

let hfParmasInit = {
    gameId: "",//超父游戏id
    mainServerId: "",//合服的主服id
    serverIdList: [],//合并的区服id列表
    serverName: "",//合服区服名称
    mergeTime: "",//合服时间
}

/**
 * 游戏区服
 * @returns 
 */
const GameServer: React.FC = () => {

    /********************************/
    const [form] = Form.useForm()
    const [queryFrom, setQueryForm] = useState<GameServerListProps>({ pageNum: 1, pageSize: 20 })
    const [hfParmas, set_hfParams] = useState<any>(hfParmasInit)
    const [visible, setVisible] = useState<boolean>(false)
    const [initialValues, setInitialValues] = useState<any>({})
    const [show, set_show] = useState(false)
    const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([])
    const [assignType, setAssignType] = useState<'GAME_SERVER_ASSIGN_CUSTOMER' | 'GAME_SERVER_ASSIGN_GS'>('GAME_SERVER_ASSIGN_CUSTOMER')
    const [assignVisible, setAssignVisible] = useState<boolean>(false)
    const [assignData, setAssignData] = useState<any>({})
    const getGameServerList = useAjax((params) => getGameServerListApi(params))
    const delGameServer = useAjax((params) => delGameServerApi(params))
    const game_supper_list_api = useAjax(() => gameSupperListApi())//获取合服超父游戏列表
    const un_merge_server_list_api = useAjax((params) => unMergeServerListApi(params))//获取合服超父游戏列表
    const merge_add_or_update_api = useAjax((params) => mergeAddOrUpdateApi(params))//新增合服
    const getGameChoiceList = useAjax(() => getGameChoiceListApi())
    const gameServerlistexcel = useAjax((params) => gameServerlistexcelApi(params),{isExcelData:true})
    /********************************/

    useEffect(() => {
        game_supper_list_api.run()
        getGameChoiceList.run()
    }, [])

    useEffect(() => {
        getGameServerList.run(queryFrom)
    }, [queryFrom])

    const editGameServer = (data: any) => {
        setVisible(true)
        const { id, gameId, serverId, serverName, startTime, nickName } = data
        setInitialValues({ id, gameId, serverId, serverName, startTime: moment(startTime), nickName })
    }

    const del = (id: number) => {
        delGameServer.run({ id }).then(res => {
            if (res) {
                message.success('删除成功')
                getGameServerList.refresh()
            }
        })
    }

    // 合服确认
    const hf_OK = useCallback(() => {
        let isOk = true
        for (let key of Object.keys(hfParmas)) {
            if (!hfParmas[key]) {
                message.error("缺少参数所有选项必填！！！！")
                isOk = false
                break
            }
        }
        if (isOk) {
            merge_add_or_update_api.run({ ...hfParmas, serverIdList: hfParmas.serverIdList?.map((item: { value: any; }) => item.value) }).then(res => {
                if (res) {
                    message.success('新增成功')
                    set_show(false)
                    getGameServerList.refresh()
                }
            })
        }
    }, [hfParmas, getGameServerList])


    const onFinish = (data: any) => {
        console.log('更新了字段---->', data);
        let oldQueryFrom = JSON.parse(JSON.stringify(queryFrom))
        if (data?.date) {
            oldQueryFrom['startTime'] = moment(data.date[0]).format('YYYY-MM-DD')
            oldQueryFrom['endTime'] = moment(data.date[1]).format('YYYY-MM-DD')
        } else {
            delete oldQueryFrom['startTime']
            delete oldQueryFrom['endTime']
        }
        delete data['date']
        setQueryForm({ ...oldQueryFrom, ...data, pageNum: 1 })
    }

    /** 指派 */
    const handleAssign = (data: any, type: 'GAME_SERVER_ASSIGN_CUSTOMER' | 'GAME_SERVER_ASSIGN_GS') => {
        setAssignType(type)
        setAssignData({ idList: [data.id], assignUserIdList: type === 'GAME_SERVER_ASSIGN_CUSTOMER' ? data?.customerList?.map((item: { userId: any }) => item.userId) : data?.gsList?.map((item: { userId: any }) => item.userId) })
        setAssignVisible(true)
    }

    return <Card
        style={{ borderRadius: 8 }}
        headStyle={{ textAlign: 'left' }}
        bodyStyle={{ padding: '5px 10px' }}
    >
        <div style={{ textAlign: 'center', fontWeight: 'bold', padding: '4px 6px 6px', fontSize: 16, marginBottom: 4, position: 'relative' }}>
            游戏区服
        </div>

        <Space style={{ width: '100%' }} direction="vertical" size={10}>
            <Form layout="inline" className='queryForm' initialValues={initialValues} name="basicGameServer" form={form} onFinish={onFinish}>
                <Row gutter={[0, 10]}>
                    <Col><Form.Item name='serverName'>
                        <Input placeholder="区服名称" allowClear style={{ width: 140 }} />
                    </Form.Item></Col>
                    <Col><Form.Item name='serverId'>
                        <Input placeholder="区服ID" allowClear style={{ width: 140 }} />
                    </Form.Item></Col>
                    <Col><Form.Item name='nickName'>
                        <Input placeholder="冠名名称" allowClear style={{ width: 140 }} />
                    </Form.Item></Col>
                    <Col><Form.Item name='gameId'>
                        <Select
                            maxTagCount={1}
                            showSearch
                            style={{ minWidth: 140 }}
                            allowClear
                            placeholder={'请选择游戏'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {getGameChoiceList?.data?.map((item: any) => <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>)}
                        </Select>
                    </Form.Item></Col>
                    <Col><Form.Item name='isSourceServer'>
                        <Select
                            maxTagCount={1}
                            showSearch
                            style={{ width: 100 }}
                            allowClear
                            placeholder={'是否原始区服'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            <Select.Option value={false}>否</Select.Option>
                            <Select.Option value={true}>是</Select.Option>
                        </Select>
                    </Form.Item></Col>
                    <Col><Form.Item name='date'>
                        <DatePicker.RangePicker placeholder={['开服开始日期', '开服结束日期']} ranges={getPresets() as any} />
                    </Form.Item></Col>

                    <Col>
                        <Space>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button onClick={() => form.resetFields()}>重置</Button>
                        </Space>
                    </Col>
                    <Col span={24}>
                        <Space>
                            <Button icon={<PlusOutlined />} type="primary" onClick={() => { setVisible(true); setInitialValues({ startTime: moment().add(90, 'd') }) }}>新增游戏区服</Button>
                            <Button icon={<PlusOutlined />} type="primary" onClick={() => { set_show(true) }}>新增合服</Button>
                            <UploadExcel gameList={game_supper_list_api?.data} onChange={() => getGameServerList.refresh()} />
                            <DownloadExcel  api={gameServerlistexcel} querys={form.getFieldsValue}/>
                            <Button icon={<PlusOutlined />} disabled={selectedRowKeys?.length === 0} type="primary" onClick={() => {
                                setAssignType('GAME_SERVER_ASSIGN_CUSTOMER')
                                setAssignData({ idList: selectedRowKeys.map(item => item.id), assignUserIdList: [] })
                                setAssignVisible(true)
                            }}>批量指派客服</Button>
                            <Button icon={<PlusOutlined />} disabled={selectedRowKeys?.length === 0} type="primary" onClick={() => {
                                setAssignType('GAME_SERVER_ASSIGN_GS')
                                setAssignData({ idList: selectedRowKeys.map(item => item.id), assignUserIdList: [] })
                                setAssignVisible(true)
                            }}>批量指派GS</Button>
                        </Space>
                    </Col>
                </Row>
            </Form>

            <div className={`${style['small']}`}>
                <Tables
                    className={`all_table content_table_body`}
                    bordered
                    sortDirections={['ascend', 'descend', null]}
                    current={queryFrom.pageNum}
                    pageSize={queryFrom.pageSize}
                    columns={columnsPos(editGameServer, del, handleAssign)}
                    dataSource={getGameServerList?.data?.records}
                    scroll={{ x: 1000, y: 600 }}
                    onChange={(pagination: any, filters: any, sortData: any) => {
                        let { current, pageSize } = pagination
                        let newQueryForm = JSON.parse(JSON.stringify(queryFrom))
                        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 })
                    }}
                    size="small"
                    total={getGameServerList?.data?.total}
                    loading={getGameServerList?.loading}
                    defaultPageSize={20}
                    rowSelection={{
                        getCheckboxProps: (record: any) => ({
                            disabled: selectedRowKeys?.length > 0 && record.gameId !== (selectedRowKeys[0] as any).gameId
                        }),
                        selectedRowKeys: selectedRowKeys.map((item: any) => item?.id.toString()),
                        onSelect: (record: any, selected: boolean, selectedRows: any) => {
                            let newSelectedRowKeys: any[] = JSON.parse(JSON.stringify(selectedRowKeys))
                            if (selected) {
                                newSelectedRowKeys.push(record)
                            } else {
                                newSelectedRowKeys = newSelectedRowKeys.filter(item => item.id != record.id)
                            }
                            setSelectedRowKeys(newSelectedRowKeys)
                        },
                        onSelectAll: (selected: boolean, selectedRows: any, changeRows: any) => {
                            let newSelectedRowKeys: any[] = JSON.parse(JSON.stringify(selectedRowKeys))
                            let gameId = newSelectedRowKeys?.[0]?.gameId || changeRows?.[0]?.gameId
                            if (selected) {
                                newSelectedRowKeys = newSelectedRowKeys.concat(changeRows.filter((item: { gameId: any }) => item.gameId === gameId))
                            } else {
                                let changeRowsIds: any[] = changeRows.map((item: { id: any }) => item.id);
                                newSelectedRowKeys = newSelectedRowKeys.filter(item => !changeRowsIds.includes(item.id))
                            }
                            setSelectedRowKeys(newSelectedRowKeys)
                        }
                    }}
                />
            </div>
        </Space>

        {visible && <EditModal
            visible={visible}
            initialValues={initialValues}
            gameList={game_supper_list_api?.data}
            onClose={() => { setVisible(false); setInitialValues({}) }}
            onChange={() => {
                setVisible(false);
                setInitialValues({})
                getGameServerList.refresh()
            }}
        />}

        {/* 合服弹窗 */}
        {show && <Modal title={`${hfParmas?.id ? '修改' : '新增'}合服`}
            visible={show}
            onCancel={() => set_show(false)}
            onOk={hf_OK}
            confirmLoading={merge_add_or_update_api?.loading}
        >
            <Row gutter={[20, 20]}>
                <Col span={24}>
                    <Space>
                        <div style={{ width: 140, textAlign: 'right' }}><span style={{ color: 'red' }}>*</span>超父游戏：</div>
                        <Select
                            showSearch
                            style={{ minWidth: 300 }}
                            allowClear
                            placeholder="选择游戏"
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            onChange={(value) => {
                                if (value) {
                                    un_merge_server_list_api.run({ gameId: value })
                                }
                                set_hfParams({ ...hfParmas, gameId: value })
                            }}
                        >
                            {game_supper_list_api?.data?.map((item: any) => <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>)}
                        </Select>
                    </Space>
                </Col>
                <Col span={24}>
                    <Space>
                        <div style={{ width: 140, textAlign: 'right' }}><span style={{ color: 'red' }}>*</span>合服区服名称：</div>
                        <Input placeholder="请输入合服区服名称" style={{ width: 300 }} onChange={(e) => {
                            let value = e.target.value
                            set_hfParams({ ...hfParmas, serverName: value })
                        }} />
                    </Space>
                </Col>
                <Col span={24}>
                    <Space>
                        <div style={{ width: 140, textAlign: 'right' }}><span style={{ color: 'red' }}>*</span>选择要合区服：</div>
                        <Select
                            mode="multiple"
                            showSearch
                            style={{ minWidth: 300 }}
                            allowClear
                            placeholder="选择区服"
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            onChange={(value, option) => {
                                console.log(value, option)
                                set_hfParams({ ...hfParmas, serverIdList: option })
                            }}
                        >
                            {un_merge_server_list_api?.data?.map((item: any) => <Select.Option value={item.serverId} key={item.serverId}>{item.serverName}</Select.Option>)}
                        </Select>
                    </Space>
                </Col>
                <Col span={24}>
                    <Space>
                        <div style={{ width: 140, textAlign: 'right' }}><span style={{ color: 'red' }}>*</span>选择合服主服：</div>
                        <Radio.Group onChange={(e) => {
                            let value = e.target.value
                            set_hfParams({ ...hfParmas, mainServerId: value })
                        }}>
                            {
                                hfParmas?.serverIdList?.map((item: any) => {
                                    return <Radio value={item.value} key={item.value}>{item.children}</Radio>
                                })
                            }
                        </Radio.Group>
                    </Space>
                </Col>
                <Col span={24}>
                    <Space>
                        <div style={{ width: 140, textAlign: 'right' }}><span style={{ color: 'red' }}>*</span>合服时间：</div>
                        <DatePicker showTime onChange={(d, str) => {
                            set_hfParams({ ...hfParmas, mergeTime: str })
                        }} />
                    </Space>
                </Col>
            </Row>
        </Modal>}

        {/* 指派 */}
        {assignVisible && <AssignUser
            assignType={assignType}
            initialValues={assignData}
            visible={assignVisible}
            onClose={() => {
                setAssignData({})
                setAssignVisible(false)
            }}
            onChange={() => {
                setAssignData({})
                setAssignVisible(false)
                getGameServerList.refresh()
            }}
        />}
    </Card>
}

export default GameServer