/** @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, { useEffect, useRef, useState } from "react";
import {
	addAliOSSConfig,
	deleteAliConfig,
	getAliConfigDetailById,
	getAllAliOSSConfig,
	initAliOSS,
	setAliShutdown,
	updateAliConfig,
} from "@/api/oss/ali";
import useStore from "@/utils/store/useStore.tsx";
import { observer } from "mobx-react";

const AliSettings: React.FC = observer(() => {
	const [form] = Form.useForm();
	const actionRef = useRef<ActionType>();
	const [open, setOpen] = useState(false);
	const [openModal, setOpenModal] = useState(false);
	const [configs, setConfigs] = useState<any>([]);
	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<any[]>[] = [
		{
			dataIndex: "index",
			valueType: "indexBorder",
			width: 48,
		},
		{
			title: "ID",
			valueType: "text",
			dataIndex: "id",
			copyable: true,
			ellipsis: true,
			tooltip: "Id",
			editable: false,
		},
		{
			disable: true,
			title: "服务地址",
			dataIndex: "endpoint",
			tooltip: "endpoint",
			ellipsis: true,
			copyable: true,
		},
		{
			disable: true,
			title: "密钥ID",
			dataIndex: "accessKeyId",
			tooltip: "access key id",
			ellipsis: true,
			copyable: true,
		},
		{
			disable: true,
			title: "密钥值",
			dataIndex: "accessKeySecret",
			tooltip: "access key secret",
			ellipsis: true,
			copyable: true,
		},
		{
			title: "创建时间",
			dataIndex: "createdTime",
			valueType: "dateTime",
			sorter: 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: any, record: any, _, 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: "关闭" },
					]}
				/>,
			],
		},
	];
	async function getAllConfig() {
		getAllAliOSSConfig(userId).then((res: any) => {
			if (res && res.success && res.data) {
				setConfigs(res.data);
			}
		});
	}
	async function getConfigDetail(id: any) {
		getAliConfigDetailById(id).then((res: any) => {
			if (res && res.success && res.data) {
				setConfigDetail(res.data);
			}
		});
	}
	async function init(id: any) {
		initAliOSS(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) {
		setAliShutdown(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,
		};
		deleteAliConfig(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 addConfigs() {
		const fieldsValue = form.getFieldsValue();
		const AliOssConfig = {
			userId: userId,
			...fieldsValue,
		};
		addAliOSSConfig(AliOssConfig).then((res: any) => {
			if (res && res.success) {
				onClose();
				getAllConfig().then(() => {
					message
						.open({
							content: "新增成功",
							type: "success",
						})
						.then();
				});
			} else {
				message.open({
					content: res.data,
					type: "error",
				});
			}
		});
	}
	const showDrawer = () => {
		setOpen(true);
	};
	const onClose = () => {
		setOpen(false);
	};
	useEffect(() => {
		getAllConfig().then();
	}, []);
	const AddAliOssConfigDrawer = () => {
		return (
			<>
				<Drawer
					title="创建连接配置"
					width={720}
					onClose={onClose}
					open={open}
					styles={{
						body: {
							paddingBottom: 80,
						},
					}}
					extra={
						<Space>
							<Button onClick={onClose}>取消</Button>
							<Button onClick={addConfigs} 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="accessKeyId"
									label="密钥ID"
									rules={[{ required: true, message: "请输入密钥ID!" }]}>
									<Input placeholder="请输入密钥ID！" />
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item
									name="accessKeySecret"
									label="密钥值"
									rules={[{ required: true, message: "请输入密钥值!" }]}>
									<Input placeholder="请输入密钥值！" />
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</Drawer>
			</>
		);
	};
	return (
		<>
			<div style={{ minHeight: "65vh" }}>
				<ProTable
					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,
								accessKeyId: originRow.accessKeyId,
								accessKeySecret: originRow.accessKeySecret,
							};
							updateAliConfig(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="阿里云OSS配置"
					bordered={false}
					toolBarRender={() => [
						<Button
							key="button"
							icon={<PlusOutlined />}
							onClick={() => {
								showDrawer();
							}}
							type="primary">
							新建
						</Button>,
					]}
				/>
				<AddAliOssConfigDrawer />
				<Modal
					title={<p>配置详情</p>}
					loading={loading}
					footer={false}
					open={openModal}
					afterClose={() => {
						setConfigDetail({});
					}}
					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>accessKeyId: </h4>{" "}
						<span style={{ marginLeft: 10 }}>{configDetail.accessKeyId} </span>
					</Flex>
					<Flex vertical={false} align={"center"}>
						<h4>accessKeySecret: </h4>{" "}
						<span style={{ marginLeft: 10 }}>{configDetail.accessKeySecret}</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 AliSettings;
