import React, { useEffect, useState } from 'react';
import { Button, DatePicker, DatePickerProps, Form, Input, message, Modal, Select, Skeleton, Spin } from 'antd';
import moment from 'moment'
import { cancelMeeting, getMeetingData, saveAppointmentEdit, saveMeeting } from './service';
import { isNotEmpty } from '@/utils/CommonUtils';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { dateTimeFormatter, echoDateTimeFormatter } from '@/utils/DateUtils';

interface MeetingReservationProps {
    modalVisible: boolean;
    onCancel: () => void;
    onSubmit?: () => void;
    roomList?: any[];//评标室列表 带问号的参数可不传
    status: string;//状态 0-新建 1-编辑 2-查看
    meetId?: string;//预约id
}
const layout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 14 },
};
export const validateMessages = {
    required: '请填写此项',
};
export const range = (start: number, end: number) => {
    const result = [];
    for (let i = start; i < end; i++) {
        result.push(i);
    }
    return result;
};
//不可选天
export function disabledDate(current: any) {
    return current && current < moment().startOf('day');
}
//不可选小时
export const disabledDateTime = () => ({
    disabledHours: () => [...range(0, 7), ...range(19, 24)],
});
//不可选小时（额外不可选）
export const otherDisabledDateTime = (current: any, disabledMap: any, type: string) => {
    let otherHour: any[] = range(0, 24);
    if (current) {
        otherHour = [];
        if (Object.keys(disabledMap).length != 0) {
            const time = moment(current).format("yyyy-MM-DD");
            disabledMap[time] && (otherHour = [...disabledMap[time][type]]);
        }
    }
    return ({
        disabledHours: () => [...range(0, 7), ...range(19, 24), ...otherHour],
    })
};
//时间选择框日期格式化
export const dateFormat: DatePickerProps['format'] = value => value?.startOf('hour').format('YYYY-MM-DD HH:mm:ss');
/**
 * 评标室预约管理-会议室预约弹窗
 * @param props 
 * @returns 
 */
const MeetingReservation: React.FC<MeetingReservationProps> = (props) => {
    const { modalVisible, onCancel, onSubmit, roomList, status, meetId } = props;
    const [form] = Form.useForm();
    const { Option } = Select;
    const { confirm } = Modal;
    const { TextArea } = Input;
    //loading
    const [loading, setLoading] = useState<boolean>(false);
    //初始化
    const [skeleing, setSkeleing] = useState<boolean>(false);
    //窗口状态 0-新建 1-编辑 2-查看
    const [modalStatus, setModalStatus] = useState<string | undefined>(status);
    //评标室类型 meeting-会议室 eval-评标室
    const [meetType, setMeetType] = useState<string>("meeting");
    //会议室预约是否可修改 true-不可修改 false-可修改
    const [isEditMeet, setIsEditMeet] = useState<boolean>(false);
    //存一份预约数据
    const [meetingData, setMeetingData] = useState<any>();

    const onFinish = (values: any) => {
        if (values.reserveStartDate < moment().format(dateTimeFormatter)) {
            message.info("开始时间不可早于当前时间");
            return;
        }
        const params = JSON.parse(JSON.stringify(values));//深拷贝
        params.reserveStartDate = moment(params.reserveStartDate).format(dateTimeFormatter);
        params.reserveEndDate = moment(params.reserveEndDate).format(dateTimeFormatter);
        setLoading(true);
        if (meetType == "meeting") {//会议室保存
            saveMeeting(params).then(res => {
                if (res?.code == 200) {
                    message.success("保存成功");
                    onSubmit && onSubmit();
                }
            }).finally(() => {
                setLoading(false);
            })
        } else {
            saveAppointmentEdit({ ...meetingData, ...params }).then(res => {//评标室保存
                if (res?.code == 200) {
                    message.success("保存成功");
                    onSubmit && onSubmit();
                }
            }).finally(() => {
                setLoading(false);
            })
        }
    };

    //获取预约信息
    const getMeetData = () => {
        setSkeleing(true);
        getMeetingData(meetId).then(res => {
            if (res?.code == 200) {
                setSkeleing(false);
                const data = res?.data;
                const isEdit: boolean = data.reserveType == "meeting" ? data.reserveStartDate <= moment().format(dateTimeFormatter) : data.status != 0;
                setIsEditMeet(isEdit);
                setMeetingData(data);
                setMeetType(data.reserveType);//变更窗口类型
                if (data.reserveType == "meeting") {
                    data.reserveStartDate = echoDateTimeFormatter(data.reserveStartDate);
                    data.reserveEndDate = echoDateTimeFormatter(data.reserveEndDate);
                }
                form.setFieldsValue(data);
            }
        })
    }
    //取消预约
    const cancelMeet = () => {
        confirm({
            title: "请与评标场所使用人员确认后再进行取消，以免影响评标/会议的正常开展！",
            icon: <ExclamationCircleOutlined />,
            centered: true,
            okText: '确认',
            content: '',
            async onOk() {
                await cancelMeeting(meetId).then(res => {
                    if (res?.code == 200) {
                        message.success("取消预约成功");
                        onSubmit && onSubmit();
                    }
                })
            },
            onCancel() { },
        });
    }

    const editMeeting = () => {
        if (meetType == "eval") {//评标室预约修改
            const data = JSON.parse(JSON.stringify(meetingData));//深拷贝
            data.reserveStartDate = echoDateTimeFormatter(data.reserveStartDate);
            data.reserveEndDate = echoDateTimeFormatter(data.reserveEndDate);
            form.setFieldsValue(data);
        }
        setModalStatus("1");
    }
    useEffect(() => {
        if (isNotEmpty(meetId)) {
            getMeetData();
        }
    }, [meetId])

    return (
        <Modal
            destroyOnClose
            title={skeleing ? null : meetType == "meeting" ? "会议室预约" : "详情"}
            visible={modalVisible}
            onCancel={() => onCancel()}
            centered
            width={600}
            footer={skeleing ? [<Skeleton.Button active />] : [
                <Button key="close" onClick={onCancel}>
                    返回
                </Button>,
                <Button key="save" type="primary" onClick={() => form.submit()} hidden={meetType == undefined || modalStatus == "2"}>
                    保存
                </Button>,
                <Button key="edit" onClick={() => editMeeting()} hidden={meetType == undefined || modalStatus == "1" || modalStatus == "0" || isEditMeet}>
                    修改预约
                </Button>,
                <Button type="primary" key="cancel" hidden={modalStatus == "0"} onClick={() => cancelMeet()}>
                    取消预约
                </Button>,
            ]}
        >
            <Spin spinning={loading}>
                <Skeleton loading={skeleing} active>
                    <Form {...layout} form={form} name="control-hooks" onFinish={onFinish} validateMessages={validateMessages}>
                        {meetType == "meeting" ? (
                            <>
                                <Form.Item name="id" label="会议id" hidden>
                                    <Input />
                                </Form.Item>
                                <Form.Item name="areaId" label="评标室" rules={[{ required: !(modalStatus == "2") }]}>
                                    <Select
                                        placeholder="选择评标室"
                                        allowClear
                                        disabled={modalStatus == "2"}
                                    >
                                        {roomList?.map(item => (<Option value={item.id} key={item.id}>{item.areaName}</Option>))}
                                    </Select>
                                </Form.Item>
                                <Form.Item name="meetingName" label="会议名称" rules={[{ required: !(modalStatus == "2") }]}>
                                    <TextArea placeholder="会议名称" disabled={modalStatus == "2"} autoSize maxLength={50} />
                                </Form.Item>
                                <Form.Item name="numberInMeeting" label="会议人数" rules={[{ required: !(modalStatus == "2") }]}>
                                    <Input type="number" placeholder="会议人数" suffix="人" disabled={modalStatus == "2"} maxLength={5} />
                                </Form.Item>
                                <Form.Item name="reserveStartDate" label="会议开始时间" rules={[{ required: !(modalStatus == "2") }]}>
                                    <DatePicker showTime={{ defaultValue: moment().hour(7) }} showNow={false} disabledDate={disabledDate} disabledTime={disabledDateTime} showMinute={false} showSecond={false} format={dateFormat} style={{ width: '100%' }} disabled={modalStatus == "2"} />
                                </Form.Item>
                                <Form.Item name="reserveEndDate" label="会议结束时间" rules={[{ required: !(modalStatus == "2") }]}>
                                    <DatePicker showTime={{ defaultValue: moment().hour(7) }} showNow={false} disabledDate={disabledDate} disabledTime={disabledDateTime} showMinute={false} showSecond={false} format={dateFormat} style={{ width: '100%' }} disabled={modalStatus == "2"} />
                                </Form.Item>
                                <Form.Item name="reserveBy" label="预约人" rules={[{ required: !(modalStatus == "2") }]}>
                                    <Input placeholder="预约人" disabled={modalStatus == "2"} maxLength={50} />
                                </Form.Item>
                                <Form.Item name="reserveContactNumber" label="预约人联系方式" rules={[{ required: !(modalStatus == "2") }]}>
                                    <Input placeholder="预约人联系方式" disabled={modalStatus == "2"} maxLength={50} />
                                </Form.Item>
                            </>
                        ) : (
                            <>
                                <Form.Item name="projectName" label="项目名称">
                                    <TextArea readOnly bordered={false} autoSize />
                                </Form.Item>
                                <Form.Item name="projectNum" label="项目编号">
                                    <Input readOnly bordered={false} />
                                </Form.Item>
                                <Form.Item name="sectionNames" label="标段名称">
                                    <TextArea readOnly bordered={false} autoSize />
                                </Form.Item>
                                {modalStatus == "2" ? (
                                    <>
                                        <Form.Item name="reserveStartDate" label="预计开始时间">
                                            <Input readOnly bordered={false} />
                                        </Form.Item>
                                        <Form.Item name="reserveEndDate" label="预计结束时间">
                                            <Input readOnly bordered={false} />
                                        </Form.Item>
                                    </>
                                ) : (
                                    <>
                                        <Form.Item name="reserveStartDate" label="预计开始时间" rules={[{ required: true }]}>
                                            <DatePicker showTime={{ defaultValue: moment().hour(7) }} showNow={false} disabledDate={disabledDate} disabledTime={disabledDateTime} showMinute={false} showSecond={false} format={dateFormat} style={{ width: '100%' }} />
                                        </Form.Item>
                                        <Form.Item name="reserveEndDate" label="预计结束时间" rules={[{ required: true }]}>
                                            <DatePicker showTime={{ defaultValue: moment().hour(7) }} showNow={false} disabledDate={disabledDate} disabledTime={disabledDateTime} showMinute={false} showSecond={false} format={dateFormat} style={{ width: '100%' }} />
                                        </Form.Item>
                                    </>
                                )}
                                <Form.Item name="reserveBy" label="预约人">
                                    <Input readOnly bordered={false} />
                                </Form.Item>
                                <Form.Item name="reserveContactNumber" label="预约人联系方式">
                                    <Input readOnly bordered={false} />
                                </Form.Item>
                            </>
                        )}
                    </Form>
                </Skeleton>
            </Spin>
        </Modal>
    );
};

export default MeetingReservation;
