import { useAjax } from "@/Hook/useAjax"
import { getRoleUserListApi } from "@/services/gameData"
import { addAssignUserApi, editAssignUserApi } from "@/services/gameData/roleOperate"
import { Col, DatePicker, Form, Input, Modal, Row, Select, Space, message } from "antd"
import React, { useEffect, useState } from "react"
import moment from "moment"

interface Props {
    data: any[]
    id?: number,
    startTime?: string,
    visible?: boolean
    onClose?: () => void
    onChange?: () => void
}
const Assign: React.FC<Props> = ({ startTime, id, visible, data, onClose, onChange }) => {

    /******************************************/
    const [gsList, setGsList] = useState<any[]>([])
    const [customerList, setCustomerList] = useState<any[]>([])
    const [operateList, setOperateList] = useState<any[]>([])
    const [form] = Form.useForm()
    const getRoleUserList = useAjax((params) => getRoleUserListApi(params))
    const addAssignUser = useAjax((params) => addAssignUserApi(params))
    const editAssignUser = useAjax((params) => editAssignUserApi(params))
    /******************************************/

    useEffect(() => {
        if (data?.length === 1) {
            const { customer_service_id, oper_user_id, gsId } = data[0]
            console.log('----->', startTime)
            let time = startTime ? moment(startTime) : undefined
            form.setFieldsValue({ startTime: time, operUserId: oper_user_id?.toString(), customerServiceId: customer_service_id?.toString(), gsId: gsId?.toString() })
        }
    }, [data])

    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()
    }, [])

    const handleOk = async () => {
        let validate = await form.validateFields()
        const { startTime, ...par } = validate
        let params: any = { startTime: moment(startTime).format('YYYY-MM-DD'), ...par }
        let roleInfoAndAgentParamList = data.map(item => {
            return {
                gameId: item.role_reg_game_id,
                roleId: item.role_id,
                serverId: item.server_id,
                userId: item.association_user_id,
                regAgentId: item.agent_id
            }
        })
        params.roleInfoAndAgentParamList = roleInfoAndAgentParamList
        if (id) {
            params.id = id
            editAssignUser.run(params).then(res => {
                if (res) {
                    message.success('更新成功')
                    onChange?.()
                }
            })
        } else {
            addAssignUser.run(params).then(res => {
                if (res) {
                    message.success('指派成功')
                    onChange?.()
                }
            })
        }
    }

    return <Modal
        title={<Space>
            <strong>指派</strong>
            <span style={{ color: 'red' }}>操作有延时，请勿重复提交!!!</span>
        </Space>}
        visible={visible}
        onCancel={onClose}
        onOk={handleOk}
        confirmLoading={addAssignUser.loading}
    >
        <Form
            name="basicExportAssign"
            form={form}
            layout="vertical"
            autoComplete="off"
        >
            <Row gutter={[20, 0]}>
                <Col span={12}>
                    <Form.Item label="开始时间" name="startTime" rules={[{ required: true, message: '请选择开始时间' }]}>
                        <DatePicker style={{ width: '100%' }} />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="运营" name="operUserId">
                        <Select
                            maxTagCount={1}
                            showSearch
                            style={{ width: '100%' }}
                            allowClear
                            placeholder={'请选择运营'}
                            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>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="客服" name="customerServiceId">
                        <Select
                            maxTagCount={1}
                            showSearch
                            style={{ width: '100%' }}
                            allowClear
                            placeholder={'请选择客服'}
                            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>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="游戏GS" name="gsId">
                        <Select
                            maxTagCount={1}
                            showSearch
                            style={{ width: '100%' }}
                            allowClear
                            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>
                    </Form.Item>
                </Col>
                <Col span={24}>
                    <Form.Item label="备注" name="remark">
                        <Input.TextArea placeholder="请输入备注" />
                    </Form.Item>
                </Col>
            </Row>
        </Form>
    </Modal>
}

export default React.memo(Assign)