import * as React from 'react';
import {
	Table,
	Button,
	Space,
	Modal,
	Form,
	Row,
	Col,
	InputNumber,
	Switch,
	Select,
	message,
	Input,
	PageHeader,
} from 'antd';
import { ColumnProps } from 'antd/lib/table';
import { FormItemProps } from 'antd/lib/form';
import {
	useWarnRules,
	WarnRuleProps,
	useDeleteRule,
	useAddRule,
	useSwitchRuleStatus,
	useUpdateRules,
} from '../../hooks/warn';
import { useDeviceList } from '../../hooks/device';
const { Option } = Select;
const { Search } = Input;

const adminWarns: React.FC = (props) => {
	const [addState, setAddState] = React.useState({
		modalVisible: false,
	});
	const [searchState, setSearchState] = React.useState({
		page: 1,
		sn: '',
	});
	React.useEffect(() => {
		requestRules(searchState);
	}, [searchState]);
	const [form] = Form.useForm();
	const [updateForm] = Form.useForm();
	const { state: rulesState, request: requestRules } = useWarnRules();
	const { state: deleteState, request: requestDelete } = useDeleteRule();
	const { state: addRuleState, request: requestAddRule } = useAddRule();
	const { state: updateState, request: requestUpdateRules } = useUpdateRules();
	const [updateModalState, handleUpdateModalState] = React.useState({
		visible: false,
		valuses: {},
	});

	const {
		state: switchStatusState,
		request: requestSwitchStatus,
	} = useSwitchRuleStatus();
	const {
		state: deviceListState,
		request: requestDeviceList,
	} = useDeviceList();
	React.useEffect(() => {
		requestDeviceList({ pageSize: 1000, page: 1, filter: '', status: 1 });
	}, []);
	const FormInputData: FormItemProps[] = [
		{
			name: 'alarm_count',
			label: '连续报警次数',
			rules: [
				{
					required: true,
				},
			],
			children: (
				<InputNumber
					min={0}
					style={{ width: '100%' }}
					placeholder='请输入'></InputNumber>
			),
		},
		{
			name: 'continue_period',
			label: '持续周期',
			rules: [
				{
					required: true,
				},
			],
			children: (
				<InputNumber
					min={0}
					style={{ width: '100%' }}
					placeholder='请输入'></InputNumber>
			),
		},
		{
			name: 'is_on',
			label: '状态',
			valuePropName: 'checked',
			initialValue: true,
			children: (
				<Switch
					checkedChildren='启用'
					unCheckedChildren='停止'
					defaultChecked={true}></Switch>
			),
		},
		{
			name: 'silence_period',
			label: '静默时间',
			rules: [
				{
					required: true,
				},
			],
			children: (
				<InputNumber
					style={{ width: '100%' }}
					placeholder='请输入'></InputNumber>
			),
		},
	];

	const colums: ColumnProps<WarnRuleProps>[] = [
		{
			title: '设备',
			key: 'device_name',
			dataIndex: 'device_name',
		},
		{
			title: '设备唯一编码',
			key: 'sn',
			dataIndex: 'sn',
		},
		{
			title: '持续周期(分)',
			key: 'continue_period',
			dataIndex: 'continue_period',
		},
		{
			title: '静默时间(分)',
			key: 'silence_period',
			dataIndex: 'silence_period',
		},
		{
			title: '状态',
			key: 'is_on_text',
			dataIndex: 'is_on_text',
		},
		{
			title: '操作',
			render: (record) => {
				return (
					<Space>
						<Button onClick={() => handleSwitchOnRule(record)}>
							{record.is_on ? '停止' : '启用'}
						</Button>
						<Button
							onClick={() => {
								handleUpdateModalState((preState) => ({
									...preState,
									visible: true,
									valuses: record,
								}));
								updateForm.setFieldsValue(record);
								updateForm.setFields([{ name: 'id', value: '1' }]);
							}}>
							配置
						</Button>
						<Button danger onClick={() => handleDelete(record)}>
							删除
						</Button>
					</Space>
				);
			},
		},
	];
	const handleSwitchOnRule = (record) => {
		Modal.confirm({
			title: '提示',
			content: record.is_on ? '确认停止此警告规则' : '确认启用此警告规则',
			okText: '确认',
			cancelText: '取消',
			okButtonProps: {
				loading: switchStatusState.loading,
			},
			onOk: () => {
				requestSwitchStatus({
					id: record.id,
					is_on: !record.is_on,
				})
					.then(() => {
						message.success('启停规则成功');
						requestRules(searchState);
					})
					.catch((error) => {
						message.error(error.message);
					});
			},
		});
	};
	const handleDelete = (record: WarnRuleProps) => {
		Modal.confirm({
			title: '提示',
			content: `是否删除此告警规则`,
			okText: '确认',
			okButtonProps: {
				loading: deleteState.loading,
			},
			cancelText: '取消',
			onOk: () => {
				requestDelete({ id: record.id })
					.then(() => {
						message.success('删除规则成功');
						requestRules(searchState);
					})
					.catch((error) => {
						message.error(error.message);
					});
			},
		});
	};
	const handleUpdateRule = () => {
		updateForm.validateFields().then((data: any) => {
			requestUpdateRules({
				...updateModalState.valuses,
				...data,
			})
				.then(() => {
					message.success('修改规则成功');
					handleUpdateModalState((preState) => ({
						...preState,
						visible: false,
						valuses: {},
					}));
					requestRules(searchState);
				})
				.catch((error) => {
					message.error(error.message);
				});
		});
	};

	/**
	 * @description 切换新增modal 可见性
	 */
	const onSwitchAddModalVisible = () => {
		setAddState((preState) => ({
			...preState,
			modalVisible: !preState.modalVisible,
		}));
	};
	const onSubmit = () => {
		form.validateFields().then((data) => {
			requestAddRule(data as any)
				.then((data) => {
					message.success('规则添加成功');
					onSwitchAddModalVisible();
				})
				.catch((error) => {
					message.error(error.message);
				});
		});
	};
	return (
		<>
			<PageHeader title='告警配置'></PageHeader>
			<Row justify='end'>
				<Button onClick={onSwitchAddModalVisible}>新增</Button>
			</Row>
			<Row gutter={[0, 24]}>
				<Col span={4}>
					<Search
						placeholder='请输入设备唯编号'
						onSearch={(sn) => {
							setSearchState((preState) => ({ ...preState, page: 1, sn }));
						}}></Search>
				</Col>
			</Row>
			<Table
				loading={rulesState.loading}
				rowKey={(record) => record.id}
				columns={colums}
				dataSource={rulesState.dataSource}
				pagination={{
					hideOnSinglePage: true,
					total: rulesState.total,
					current: rulesState.page,
					onChange: (page) => {
						setSearchState((preState) => ({ ...preState, page }));
					},
				}}></Table>
			<Modal
				title='告警规则'
				destroyOnClose
				visible={addState.modalVisible}
				onOk={onSubmit}
				onCancel={onSwitchAddModalVisible}>
				<Form form={form}>
					<Form.Item
						name='sn'
						label='设备'
						required
						labelCol={{ span: 6 }}
						rules={[
							{
								required: true,
							},
						]}
						children={
							<Select style={{ width: '100%' }} placeholder='请选择设备'>
								{deviceListState.dataSource.map((element) => {
									return (
										<Option key={element.id} value={element.sn}>
											{element.name}
										</Option>
									);
								})}
							</Select>
						}></Form.Item>
					{FormInputData.map((element) => {
						return (
							<Form.Item
								key={element.name as string}
								{...element}
								labelCol={{ span: 6 }}></Form.Item>
						);
					})}
				</Form>
			</Modal>

			<Modal
				title='告警规则'
				visible={updateModalState.visible}
				okButtonProps={{ loading: updateState.loading }}
				onOk={handleUpdateRule}
				onCancel={() => {
					handleUpdateModalState((preState) => ({
						...preState,
						visible: false,
						valuses: {},
					}));
				}}>
				<Form form={updateForm}>
					<Form.Item
						name='sn'
						label='设备'
						labelCol={{ span: 6 }}
						children={
							<Select
								disabled
								style={{ width: '100%' }}
								placeholder='请选择设备'>
								{deviceListState.dataSource.map((element) => {
									return (
										<Option key={element.id} value={element.sn}>
											{element.name}
										</Option>
									);
								})}
							</Select>
						}></Form.Item>
					{FormInputData.map((element) => {
						return (
							<Form.Item
								key={element.name as string}
								{...element}
								labelCol={{ span: 6 }}></Form.Item>
						);
					})}
				</Form>
			</Modal>
		</>
	);
};
export default adminWarns;
