import { useAjax } from "@/Hook/useAjax"
import { GetAssignUser, delAssignUserApi, getAssignUserApi } from "@/services/gameData/roleOperate"
import { Button, Drawer, Input, Popconfirm, Select, Space, Table, Tag, message } from "antd"
import React, { useEffect, useState } from "react"
import { columnsChangeLog } from "./tableConfig"
import { getRoleUserListApi } from "@/services/gameData"
import Assign from "./assign"


interface Props {
    data: any
    visible?: boolean
    onClose?: () => void
    onChange?: () => void
}
const ChangeLog: React.FC<Props> = ({ data, visible, onClose, onChange }) => {

    /******************************/
    const [gsList, setGsList] = useState<any[]>([])
    const [customerList, setCustomerList] = useState<any[]>([])
    const [operateList, setOperateList] = useState<any[]>([])
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
    const [queryForm, setQueryForm] = useState<GetAssignUser>({ pageNum: 1, pageSize: 20 })
    const [assignvisible, setAssignVisible] = useState<boolean>(false)
    const [id, setId] = useState<number>()
    const [startTime, setStartTime] = useState<string>()
    const getAssignUser = useAjax((params) => getAssignUserApi(params))
    const delAssignUser = useAjax((params) => delAssignUserApi(params))
    const getRoleUserList = useAjax((params) => getRoleUserListApi(params))
    /******************************/

    useEffect(() => {
        const getList = async () => {
            // 游戏GS
            let gs = await getRoleUserList.run({ authType: 'GS' })
            setGsList(gs ? Object.keys(gs)?.map(key => ({ userId: key, nickname: gs[key] })) : [])
            // 运营
            let operate = await getRoleUserList.run({ authType: 'OPERATE' })
            setOperateList(operate ? Object.keys(operate)?.map(key => ({ userId: key, nickname: operate[key] })) : [])
            // 客服
            let customer = await getRoleUserList.run({ authType: 'CUSTOMER' })
            setCustomerList(customer ? Object.keys(customer)?.map(key => ({ userId: key, nickname: customer[key] })) : [])
        }
        getList()
    }, [])

    useEffect(() => {
        getAssignUser.run({
            ...queryForm,
            gameId: data.role_reg_game_id,
            roleId: data.role_id,
            serverId: data.server_id,
            userId: data.association_user_id,
            regAgentId: data.agent_id
        })
    }, [queryForm])


    const del = (ids: any[]) => {
        delAssignUser.run(ids.toString()).then(res => {
            if (res) {
                onChange?.()
                setSelectedRowKeys([])
                getAssignUser.refresh()
                message.success('删除成功')
            }
        })
    }

    const update = (data: any) => {
        setId(data.id)
        setStartTime(data.startTime)
        setAssignVisible(true)
    }

    return <Drawer
        title="变更记录"
        visible={visible}
        onClose={onClose}
        width={'90%'}
    >
        <Space style={{ width: '100%', marginBottom: 10 }}>
            <Select
                showSearch
                style={{ width: 120 }}
                allowClear
                placeholder={'请选择运营'}
                value={queryForm?.operUserId}
                onChange={(e) => setQueryForm({ ...queryForm, operUserId: e, pageNum: 1 })}
                filterOption={(input, option) =>
                    (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
            >
                {operateList.map((item: any) => <Select.Option value={item.userId} key={item.userId}>{item.nickname}</Select.Option>)}
            </Select>
            <Select
                showSearch
                style={{ width: 120 }}
                allowClear
                placeholder={'请选择客服'}
                value={queryForm?.customerServiceId}
                onChange={(e) => setQueryForm({ ...queryForm, customerServiceId: e, pageNum: 1 })}
                filterOption={(input, option) =>
                    (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
            >
                {customerList.map((item: any) => <Select.Option value={item.userId} key={item.userId}>{item.nickname}</Select.Option>)}
            </Select>
            <Select
                showSearch
                style={{ width: 120 }}
                allowClear
                value={queryForm?.gsId}
                onChange={(e) => setQueryForm({ ...queryForm, gsId: e, pageNum: 1 })}
                placeholder={'请选择游戏GS'}
                filterOption={(input, option) =>
                    (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
            >
                {gsList.map((item: any) => <Select.Option value={item.userId} key={item.userId}>{item.nickname}</Select.Option>)}
            </Select>
            <Input placeholder="备注" allowClear value={queryForm?.remark} onChange={(e) => setQueryForm({ ...queryForm, remark: e.target.value, pageNum: 1 })} />
        </Space>
        <Table
            dataSource={getAssignUser?.data?.records}
            columns={columnsChangeLog(update, del)}
            loading={getAssignUser.loading}
            scroll={{ x: 380, y: 300 }}
            className="uuTable"
            rowKey={'id'}
            pagination={
                {
                    total: getAssignUser?.data?.total || 0,//总共多少条数据,服务器给,设置后分页自动计算页数
                    current: getAssignUser?.data?.current || 1,//当前页数,需state控制配合翻页
                    pageSize: getAssignUser?.data?.size || 20,
                    defaultCurrent: 1,//默认初始的当前页数
                    pageSizeOptions: ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100'],
                    showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                    showSizeChanger: true, //手动开启条数筛选器，默认超过50条开启
                    size: 'small',//设置分页尺寸
                    onChange: (page: number, pageSize: number) => {
                        setQueryForm({ ...queryForm, pageNum: page, pageSize })
                    },
                    showLessItems: true
                }
            }
            rowSelection={{
                selectedRowKeys,
                onChange: (selectedRowKeys: React.Key[]) => {
                    setSelectedRowKeys(selectedRowKeys)
                },
            }}
        />

        {/* 指派 */}
        {assignvisible && <Assign id={id} startTime={startTime} visible={assignvisible} data={[data]} onClose={() => setAssignVisible(false)} onChange={() => { setAssignVisible(false); getAssignUser?.refresh(); }}/>}
    </Drawer>
}

export default React.memo(ChangeLog)