/** @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 {
	addTencentOSSConfig,
	deleteTencentConfig,
	getAllTencentOSsConfig,
	getTencentConfigDetailById,
	initTencentOSS,
	setTencentShutdown,
	updateTencentConfig,
} from "@/api/oss/tencent";
import useStore from "@/utils/store/useStore.tsx";
import { observer } from "mobx-react";

type TencentOssConfigItem = {
	id: number;
	userId: number;
	endpoint: number;
	secretId: string;
	secretKey: string;
	appId: string;
	region: string;
	createdTime: string;
	updateTime: string;
	status: string;
};

const TencentSettings: React.FC = observer(() => {
	const [form] = Form.useForm();
	const actionRef = useRef<ActionType>();
	const [open, setOpen] = useState(false);
	const [configs, setConfigs] = useState<TencentOssConfigItem[]>([]);
	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<TencentOssConfigItem>[] = [
		{
			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",
			copyable: true,
			tooltip: "endpoint",
			ellipsis: true,
		},
		{
			disable: true,
			title: "密钥ID",
			dataIndex: "secretId",
			copyable: true,
			tooltip: "secret Id",
			ellipsis: true,
		},
		{
			disable: true,
			title: "密钥值",
			dataIndex: "secretKey",
			tooltip: "secret Key",
			copyable: true,
			ellipsis: true,
		},
		{
			disable: true,
			title: "appId",
			dataIndex: "appId",
			tooltip: "appId",
			copyable: true,
			ellipsis: true,
		},
		{
			disable: true,
			title: "地域",
			dataIndex: "region",
			tooltip: "region",
			copyable: true,
			ellipsis: 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: TencentOssConfigItem, _: 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: "关闭" },
					]}
				/>,
			],
		},
	];

	async function init(id: any) {
		initTencentOSS(userId, id).then((res: any) => {
			if (res && res.success) {
				message.open({
					content: "开启成功",
					type: "success",
				});
				getAllConfigs().then();
			} else {
				message.open({
					content: res.data,
					type: "error",
				});
			}
		});
	}
	async function getConfigDetail(id: any) {
		getTencentConfigDetailById(id).then((res: any) => {
			if (res && res.success && res.data) {
				setConfigDetail(res.data);
			}
		});
	}
	async function shutdown(id: any) {
		setTencentShutdown(userId, id).then((res: any) => {
			if (res && res.success) {
				message.open({
					content: res.data,
					type: "success",
				});
				getAllConfigs().then();
			} else {
				message.open({
					content: res.data,
					type: "error",
				});
			}
		});
	}

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

	const showDrawer = () => {
		setOpen(true);
	};

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

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

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

	useEffect(() => {
		getAllConfigs().then();
	}, []);
	const AddTencentOssConfigDrawer = () => {
		return (
			<>
				<Drawer
					title="创建连接配置"
					width={720}
					onClose={onClose}
					open={open}
					styles={{
						body: {
							paddingBottom: 80,
						},
					}}
					extra={
						<Space>
							<Button onClick={onClose}>取消</Button>
							<Button onClick={addTencentConfig} type="primary">
								提交
							</Button>
						</Space>
					}>
					<Form layout="vertical" form={form}>
						<Row gutter={16}>
							<Col span={12}>
								<Form.Item
									name="secretId"
									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>
						<Row gutter={16}>
							<Col span={12}>
								<Form.Item
									name="appId"
									label="appId"
									rules={[{ required: true, message: "请输入appID!" }]}>
									<Input placeholder="请输入appID！" />
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item
									name="region"
									label="地区"
									rules={[{ required: true, message: "请输入地区!" }]}>
									<Input placeholder="请输入地区！" />
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</Drawer>
			</>
		);
	};
	return (
		<>
			<div style={{ height: "65vh" }}>
				<ProTable<TencentOssConfigItem>
					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,
								secretId: originRow.secretId,
								secretKey: originRow.secretKey,
								appId: originRow.appId,
								region: originRow.region,
							};
							updateTencentConfig(updateForm).then((res: any) => {
								if (res && res.success) {
									message.open({
										content: "修改成功！",
										type: "success",
									});
									getAllConfigs().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",
									});
									getAllConfigs().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="腾讯云COS配置"
					bordered={false}
					toolBarRender={() => [
						<Button
							key="button"
							icon={<PlusOutlined />}
							onClick={() => {
								showDrawer();
							}}
							type="primary">
							新建
						</Button>,
					]}
				/>
				<AddTencentOssConfigDrawer />
				<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>secretId: </h4>{" "}
						<span style={{ marginLeft: 10 }}>{configDetail.secretId} </span>
					</Flex>
					<Flex vertical={false} align={"center"}>
						<h4>secretKey: </h4>{" "}
						<span style={{ marginLeft: 10 }}>{configDetail.secretKey}</span>
					</Flex>
					<Flex vertical={false} align={"center"}>
						<h4>appId: </h4>{" "}
						<span style={{ marginLeft: 10 }}>{configDetail.appId}</span>
					</Flex>
					<Flex vertical={false} align={"center"}>
						<h4>region: </h4>{" "}
						<span style={{ marginLeft: 10 }}>{configDetail.region}</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 TencentSettings;
