import { Form, Input, message, Modal, Select } from "antd"
import React, { useEffect, useState } from "react"
import dayjs from "dayjs"
import { randomString } from "@/utils/utils"
import { useAjax } from "@/Hook/useAjax"
import { getProjectGroupsAllListApi } from "@/pages/weComTask/API/groupManage"

/**
 * 设置名称
 * @returns 
 */
interface Props {
    visible?: boolean,
    onClose?: () => void,
    onChange?: (data: any) => void
    loading?: boolean
    projectName?: string
}
const SubmitModal: React.FC<Props> = (props) => {

    /********************/
    const { visible, onClose, onChange, loading, projectName } = props
    const [form] = Form.useForm()
    const [groupList, setGroupList] = useState<{ label: string, value: number }[]>([])

    const getProjectGroupsAllList = useAjax(() => getProjectGroupsAllListApi())
    /********************/

    useEffect(() => {
        getProjectGroupsAllList.run().then(res => {
            setGroupList(res?.data?.map(item => ({ label: item.name, value: item.id })) || [])
        })
    }, [])

    const handleOk = () => {
        form.validateFields().then((values) => {
            const params = JSON.parse(JSON.stringify(values))
            onChange?.(params)
        }).catch(() => {
            form.submit()
        });
    }


    return <Modal
        title={<strong style={{ fontSize: 20 }}>{projectName ? projectName + '任务修改' : ''}提交</strong>}
        open={visible}
        confirmLoading={loading}
        onCancel={onClose}
        maskClosable={false}
        onOk={handleOk}
    >
        <Form
            name="basicSubmit"
            form={form}
            labelCol={{ span: 4 }}
            autoComplete="off"
            scrollToFirstError={{
                behavior: 'smooth',
                block: 'center'
            }}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
            colon={false}
            labelAlign="left"
            initialValues={{
                projectName: projectName || '任务' + dayjs().format('MMDDHHmmss') + '_' + randomString(true, 3, 5)
            }}
        >
            <Form.Item label={<strong>任务名称</strong>} name="projectName" rules={[{ required: true, message: '请输入任务名称!' }]}>
                <Input placeholder="请输入任务名称" />
            </Form.Item>
            <Form.Item label={<strong>项目组</strong>} name="projectGroupId">
                <Select
                    placeholder='请选择项目组'
                    allowClear
                    options={groupList}
                    showSearch
                    filterOption={(input, option) =>
                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                />
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(SubmitModal)