/** @format */
import { PlusOutlined } from "@ant-design/icons";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { ProTable, TableDropdown } from "@ant-design/pro-components";
import { Button, Col, Drawer, Flex, Form, Input, message, Modal, Row, Space } from "antd";
import React, { ReactNode, useEffect, useRef, useState } from "react";
import {
	addMinioOSSConfig,
	deleteMinioConfig,
	getAllMinioConfig,
	getMinioConfigDetailById,
	initMinioOSS,
	setMinioShutdown,
	updateMinioConfig,
} from "@/api/oss/minio";
import useStore from "@/utils/store/useStore.tsx";
import { observer } from "mobx-react";

type MinioOssConfigItem = {
	id: number;
	userId: number;
	endpoint: string;
	accessKey: string;
	secretKey: string;
	createdTime: string;
	updateTime: string;
	status: string;
};

const MinioSettings: React.FC = observer(() => {
	const [form] = Form.useForm();
	const actionRef = useRef<ActionType>();
	const [open, setOpen] = useState(false);
	const [configs, setConfigs] = useState<MinioOssConfigItem[]>([]);
	const [openModal, setOpenModal] = useState(false);
	const [loading, setLoading] = useState<boolean>(true);
	const [configDetail, setConfigDetail] = useState<any>({} as any);
	const userStore = useStore("user");
	const userId: any = userStore.getUserId();
	const columns: ProColumns<MinioOssConfigItem>[] = [
		{
			dataIndex: "index",
			valueType: "indexBorder",
			width: 48,
			editable: false,
		},
		{
			title: "ID",
			dataIndex: "id",
			copyable: true,
			ellipsis: true,
			tooltip: "Id",
			editable: false,
		},
		{
			disable: true,
			title: "服务地址",
			dataIndex: "endpoint",
			tooltip: "endpoint",
			copyable: true,
			ellipsis: true,
		},
		{
			disable: true,
			title: "密钥ID",
			dataIndex: "accessKey",
			tooltip: "access key",
			ellipsis: true,
			copyable: true,
		},
		{
			disable: true,
			title: "密钥值",
			dataIndex: "secretKey",
			tooltip: "secret key",
			ellipsis: true,
			copyable: true,
		},

		{
			title: "创建时间",
			dataIndex: "createdTime",
			valueType: "dateTime",
			sorter: true,
			hideInSearch: true,
			editable: false,
		},
		{
			title: "更新时间",
			dataIndex: "updateTime",
			valueType: "dateTime",
			sorter: true,
			editable: false,
		},
		{
			disable: true,
			title: "状态",
			dataIndex: "status",
			search: true,
			valueEnum: {
				true: { text: "开启", status: "Success" },
				false: { text: "关闭", status: "Error" },
			},
			editable: false,
		},
		{
			title: "操作",
			valueType: "option",
			key: "option",
			// eslint-disable-next-line @typescript-eslint/ban-ts-comment
			// @ts-expect-error
			render: (text: ReactNode, record: any, _: number, action: any) => [
				<a
					key="editable"
					onClick={() => {
						action?.startEditable?.(record.id);
					}}>
					编辑
				</a>,
				<a
					target="_blank"
					rel="noopener noreferrer"
					key="view"
					onClick={() => {
						getConfigDetail(record.id).then(() => {
							setOpenModal(true);
							setLoading(false);
						});
					}}>
					查看
				</a>,
				<TableDropdown
					key="actionGroup"
					onSelect={(key: string) => {
						if (key === "open") {
							init(record.id).then();
						} else if (key === "close") {
							shutdown(record.id).then();
						}
					}}
					menus={[
						{ key: "open", name: "开启" },
						{ key: "close", name: "关闭" },
					]}
				/>,
			],
		},
	];
	const showDrawer = () => {
		setOpen(true);
	};

	const onClose = () => {
		setOpen(false);
	};

	async function getConfigDetail(id: any) {
		getMinioConfigDetailById(id).then((res: any) => {
			if (res && res.success && res.data) {
				setConfigDetail(res.data);
			}
		});
	}

	async function init(id: any) {
		initMinioOSS(userId, id).then((res: any) => {
			if (res && res.success) {
				message.open({
					content: "开启成功",
					type: "success",
				});
				getAllConfig().then();
			} else {
				message.open({
					content: res.data,
					type: "error",
				});
			}
		});
	}

	async function shutdown(id: any) {
		setMinioShutdown(userId, id).then((res: any) => {
			if (res && res.success) {
				message.open({
					content: res.data,
					type: "success",
				});
				getAllConfig().then();
			} else {
				message.open({
					content: res.data,
					type: "error",
				});
			}
		});
	}

	async function deleteConfig(id: any) {
		const form: any = {
			id: id,
			isDeleted: 1,
		};
		deleteMinioConfig(form).then((res: any) => {
			if (res && res.success) {
				message.open({
					content: "删除成功",
					type: "success",
				});
				getAllConfig().then();
			} else {
				message.open({
					content: res.data,
					type: "error",
				});
			}
		});
	}

	async function getAllConfig() {
		getAllMinioConfig(userId).then((res: any) => {
			if (res && res.success && res.data) {
				setConfigs(res.data);
			}
		});
	}

	async function addMinioConfig() {
		const fieldsValue = form.getFieldsValue();
		const MinioOssConfig = {
			userId: userId,
			...fieldsValue,
		};
		addMinioOSSConfig(MinioOssConfig).then((res: any) => {
			if (res && res.success) {
				message.open({
					content: "新增成功",
					type: "success",
				});
				getAllConfig().then(() => {
					onClose();
				});
			} else {
				message.open({
					content: res.data,
					type: "error",
				});
			}
		});
	}

	useEffect(() => {
		getAllConfig().then();
	}, []);
	const AddMinioOssConfigDrawer = () => {
		return (
			<>
				<Drawer
					title="创建连接配置"
					width={"45%"}
					onClose={onClose}
					open={open}
					styles={{
						body: {
							paddingBottom: 80,
						},
					}}
					extra={
						<Space>
							<Button onClick={onClose}>取消</Button>
							<Button onClick={addMinioConfig} type="primary">
								提交
							</Button>
						</Space>
					}>
					<Form layout="vertical" form={form}>
						<Row gutter={16}>
							<Col span={12}>
								<Form.Item
									name="endpoint"
									label="服务地址"
									rules={[{ required: true, message: "请输入服务地址！" }]}>
									<Input placeholder="请输入服务地址！" />
								</Form.Item>
							</Col>
						</Row>
						<Row gutter={16}>
							<Col span={12}>
								<Form.Item
									name="accessKey"
									label="密钥ID"
									rules={[{ required: true, message: "请输入密钥ID!" }]}>
									<Input placeholder="请输入密钥ID！" />
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item
									name="secretKey"
									label="密钥值"
									rules={[{ required: true, message: "请输入密钥值!" }]}>
									<Input placeholder="请输入密钥值！" />
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</Drawer>
			</>
		);
	};
	return (
		<>
			<div style={{ minHeight: "65vh" }}>
				<ProTable<MinioOssConfigItem>
					columns={columns}
					dataSource={configs}
					actionRef={actionRef}
					cardBordered={true}
					editable={{
						type: "multiple",
						onSave: async (__: any, originRow: any, _: any) => {
							const updateForm: any = {
								id: originRow.id,
								endpoint: originRow.endpoint,
								accessKey: originRow.accessKey,
								secretKey: originRow.secretKey,
							};
							updateMinioConfig(updateForm).then((res: any) => {
								if (res && res.success) {
									message.open({
										content: "修改成功！",
										type: "success",
									});
									getAllConfig().then();
								} else {
									message.open({
										content: res.data,
										type: "error",
									});
								}
							});
						},
						onDelete: async (row: any) => {
							deleteConfig(row).then((res: any) => {
								if (res && res.success) {
									message.open({
										content: "删除成功",
										type: "success",
									});
									getAllConfig().then();
								} else {
									message.open({
										content: res.data,
										type: "error",
									});
								}
							});
						},
					}}
					columnsState={{
						persistenceKey: "pro-table-singe-demos",
						persistenceType: "localStorage",
						defaultValue: {
							option: { fixed: "right", disable: true },
						},
					}}
					rowKey="id"
					search={false}
					options={{
						setting: {
							listsHeight: 400,
						},
					}}
					pagination={
						{
							pageSize: 5,
						} as any
					}
					dateFormatter="string"
					headerTitle="MinIO配置"
					bordered={false}
					toolBarRender={() => [
						<Button
							key="button"
							icon={<PlusOutlined />}
							onClick={() => {
								showDrawer();
							}}
							type="primary">
							新建
						</Button>,
					]}
				/>
				<AddMinioOssConfigDrawer />
				<Modal
					title={<p>配置详情</p>}
					loading={loading}
					footer={false}
					afterClose={() => {
						setConfigDetail({});
					}}
					open={openModal}
					onCancel={() => setOpenModal(false)}>
					<Flex vertical={false} align={"center"}>
						<h4>ID:</h4> <span style={{ marginLeft: 10 }}>{configDetail.id}</span>
					</Flex>
					<Flex vertical={false} align={"center"}>
						<h4>endpoint: </h4>{" "}
						<span style={{ marginLeft: 10 }}>{configDetail.endpoint}</span>
					</Flex>
					<Flex vertical={false} align={"center"}>
						<h4>accessKey: </h4>{" "}
						<span style={{ marginLeft: 10 }}>{configDetail.accessKey} </span>
					</Flex>
					<Flex vertical={false} align={"center"}>
						<h4>secretKey: </h4>{" "}
						<span style={{ marginLeft: 10 }}>{configDetail.secretKey}</span>
					</Flex>
					<Flex vertical={false} align={"center"}>
						<h4>status: </h4>{" "}
						<span style={{ marginLeft: 10 }}>{configDetail.status}</span>
					</Flex>
					<Flex vertical={false} align={"center"}>
						<h4>createdTime: </h4>{" "}
						<span style={{ marginLeft: 10 }}>{configDetail.createdTime}</span>
					</Flex>
					<Flex vertical={false} align={"center"}>
						<h4>updateTime: </h4>{" "}
						<span style={{ marginLeft: 10 }}>{configDetail.updateTime}</span>
					</Flex>
				</Modal>
			</div>
		</>
	);
});

export default MinioSettings;
