import React, { useState } from 'react';
import moment from 'moment';
import {
	Table,
	Row,
	Space,
	Input,
	Button,
	Modal,
	Form,
	DatePicker,
	message,
	PageHeader,
	Badge,
	Typography,
} from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import { ColumnProps } from 'antd/lib/table';
import { FormItemProps } from 'antd/lib/form';
import Upload from '../../compontens/upload';
import {
	useProjectSchedule,
	useAddProcess,
	useDeleteProcess,
	IscheduleProps,
	ScheduleStaus,
	useUpdateProcess,
} from '../../hooks/process';
const { Text } = Typography;
const inputsDatas: FormItemProps[] = [
	{
		name: 'name',
		label: '进度名',
		children: <Input placeholder='请输入进度名' maxLength={8}></Input>,
	},
	{
		name: 'expectStartTime',
		label: '期待开始时间',
		children: <DatePicker style={{ width: '100%' }}></DatePicker>,
	},
	{
		name: 'expectEndTime',
		label: '期待结束时间',
		children: <DatePicker style={{ width: '100%' }}></DatePicker>,
	},
];

const AdminProcess: React.FC = (props) => {
	const [form] = Form.useForm();
	const [updateForm] = Form.useForm();

	const [processState, requestProcess] = useProjectSchedule();
	const { state: addState, request: requestAddProcess } = useAddProcess();
	const { state: deleteState, request: requestDelete } = useDeleteProcess();
	const {
		state: updateState,
		request: requestUpdateProcess,
	} = useUpdateProcess();
	const [updateModalState, handleChangeUpdateModal] = useState<{
		visible: boolean;
		values?: IscheduleProps;
	}>({
		visible: false,
	});
	const [modalState, setModalState] = React.useState({
		modalVisible: false,
	});
	const handleSwitchModalVisible = () => {
		setModalState((preState) => ({
			...preState,
			modalVisible: !preState.modalVisible,
		}));
	};
	React.useEffect(() => {
		requestProcess();
	}, []);
	const handleSubmit = () => {
		form.validateFields().then((data: any) => {
			requestAddProcess({
				...data,
				expectStartTime: data.expectStartTime.unix(),
				expectEndTime: data.expectEndTime.unix(),
			})
				.then(() => {
					message.success('新增进度成功', 1, () => {
						setModalState((preState) => ({ ...preState, modalVisible: false }));
					});
					requestProcess();
				})
				.catch((error) => {
					message.error(error.message);
				});
		});
	};

	const handleDelete = (record) => {
		Modal.confirm({
			title: '提示',
			content: '确认删除此进度?',
			okButtonProps: { loading: deleteState.loading },
			onOk: () => {
				requestDelete({ id: record.id })
					.then(() => {
						message.success('删除工程');
						requestProcess();
					})
					.catch((error) => {
						message.error(error.message);
					});
			},
		});
	};
	const columns: ColumnProps<IscheduleProps>[] = [
		{
			title: '进度名',
			key: 'name',
			dataIndex: 'name',
		},
		{
			title: '期望开始时间',
			key: 'expect_start_time',
			dataIndex: 'expect_start_time',
		},
		{
			title: '期望结束时间',
			key: 'expect_end_time',
			dataIndex: 'expect_end_time',
		},
		{
			title: '实际结束时间',
			key: 'expect_end_time',
			dataIndex: 'expect_end_time',
		},
		{
			title: '状态',
			key: 'status',
			dataIndex: 'status',
			render: (dataValue) => {
				return <Text>{ScheduleStaus[dataValue]}</Text>;
			},
		},
		{
			title: '操作',
			render: (record) => {
				return (
					<Space>
						<Button
							disabled={record.status !== 0}
							type='primary'
							onClick={() => {
								updateForm.resetFields();
								updateForm.setFields([
									{
										name: 'status',
										value: 2,
									},
								]);
								handleChangeUpdateModal({ visible: true, values: record });
							}}>
							开工
						</Button>
						<Button
							disabled={record.status !== 2}
							type='primary'
							onClick={() => {
								updateForm.resetFields();
								updateForm.setFields([
									{
										name: 'status',
										value: 1,
									},
								]);
								handleChangeUpdateModal({ visible: true, values: record });
							}}>
							完工
						</Button>
						<Button
							danger
							icon={<DeleteOutlined></DeleteOutlined>}
							onClick={() => {
								handleDelete(record);
							}}>
							删除
						</Button>
					</Space>
				);
			},
		},
	];
	const handleSubmitUpdate = (data) => {
		const isDoing = updateForm.getFieldValue('status') === 2;
		const time = data.reality_time.unix();
		requestUpdateProcess({
			id: updateModalState.values?.id as number,
			image: data.image ? data.image[0] : '',
			reality_end_time: isDoing ? undefined : time,
			reality_start_time: isDoing ? time : undefined,
		})
			.then(() => {
				message.success('进度更新已成功', 1, () => {
					handleChangeUpdateModal({ visible: false, values: undefined });
					requestProcess();
				});
			})
			.catch((error) => {
				message.error(error.message);
			});
	};
	return (
		<div>
			<PageHeader title='进度管理'></PageHeader>
			<Row gutter={[0, 30]} justify='end'>
				<Button type='primary' onClick={handleSwitchModalVisible}>
					新增
				</Button>
			</Row>
			<Table
				loading={processState.loading}
				rowKey={(record) => record.id}
				bordered
				columns={columns}
				dataSource={processState.data.list}
				pagination={false}></Table>
			<Modal
				destroyOnClose
				title='配置'
				onCancel={handleSwitchModalVisible}
				visible={modalState.modalVisible}
				onOk={handleSubmit}
				okButtonProps={{ loading: addState.loading }}>
				<Form labelCol={{ span: 6 }} form={form}>
					{inputsDatas.map((element) => {
						return (
							<Form.Item
								required
								{...element}
								rules={[{ required: true, message: `请设置${element.label}` }]}
								key={element.name as string}></Form.Item>
						);
					})}
				</Form>
			</Modal>
			<Modal
				visible={updateModalState.visible}
				title='是否修改当前当前进度'
				onOk={() => {
					updateForm.submit();
				}}
				okButtonProps={{ loading: updateState.loading }}
				onCancel={() => {
					handleChangeUpdateModal({ visible: false, values: undefined });
				}}>
				<Form
					form={updateForm}
					onFinish={handleSubmitUpdate}
					labelCol={{ span: 4 }}
					wrapperCol={{ span: 10 }}>
					<Form.Item
						name='status'
						label='状态'
						children={
							<span>{ScheduleStaus[updateForm.getFieldValue('status')]}</span>
						}></Form.Item>
					<Form.Item
						name='reality_time'
						label='时间'
						initialValue={moment()}
						children={<DatePicker></DatePicker>}></Form.Item>
					{updateForm.getFieldValue('status') !== 2 && (
						<Form.Item
							name='image'
							label='完工图'
							children={<Upload limit={1}></Upload>}></Form.Item>
					)}
				</Form>
			</Modal>
		</div>
	);
};
export default AdminProcess;
