import { useEffect, useState, useCallback } from "react";
import MyInput from "@/components/mui/MyInput";
import MySelect from "@/components/mui/MySelect";
import MyButton from "@/components/mui/MyButton";
import style from "./index.module.css";
import useMyRequest from "@/hooks/useMyRequest";
import { urlToken } from "@/api/fileserver/raysyncApi";
import * as tus from "tus-js-client";
import { useDropzone } from "react-dropzone";
import {
	getPublicEnv,
	getPublicProject,
	getDataFileToken,
} from "@/api/project_api";
import classNames from "classnames";
import { getTokenInfo } from "@/utils/util";

type IAddEnvironmentProps = {
	// addOpen: boolean;
};

const AddEnvironment = (props: IAddEnvironmentProps) => {
	// const { addOpen } = props;
	let tokenInfo = getTokenInfo();
	const [publicPrijectId, setPublicPrijectId] = useState("");
	const [publicZoneId, setPublicZoneId] = useState("");
	const [fileToken, setFileToken] = useState("");
	const [taskType, setTaskType] = useState<"BATCH" | "FLOW">("BATCH");
	const [];
	const [name, setName] = useState("");
	const [baseEnvId, setBaseEnvId] = useState("");
	const [envList, setEnvList] = useState<Array<any>>([]);
	const [nameHelper, setNameHelper] = useState({
		error: false,
		text: "30字符以内，仅限字母、数字、中文",
	});
	const [desc, setDesc] = useState("");
	const onDrop = useCallback(
		(acceptedFiles: any) => {
			console.log(acceptedFiles);
			const fileInfo = acceptedFiles[0];
			const { fileName, path, size, file } = fileInfo;
			const url =
				"https://fileserver.cloudam.cn" +
				"/parallelupload/" +
				urlToken(fileToken, publicPrijectId);
			let headers = {
				username: publicPrijectId,
				token: tokenInfo?.access_token || "",
				filetoken: fileToken,
				share: false,
				project: true,
			};
			let upload = new tus.Upload(fileInfo, {
				endpoint: url,
				parallelUploads: 1,
				chunkSize: 5 * 1024 * 1024,
				metadata: {
					filepath: "/",
				},
				retryDelays: [0, 3000, 5000, 10000, 20000],
				headers: headers,
				onError: function (error: string) {
					console.log("Failed because: " + error);
				},
				onProgress: function (bytesUploaded: number, bytesTotal: number) {
					console.log(bytesUploaded);
					console.log(bytesTotal);
					// var percentage = (bytesUploaded / bytesTotal) * 100;
					// const json = {
					//   name: upload.file.name,
					//   bytesUploaded: bytesUploaded,
					//   bytesTotal: bytesTotal,
					//   percentage: percentage,
					//   startTime: timeId,
					//   isSuspend: false,
					//   endTime: new Date().getTime(),
					//   bytesUploaded2: bytesUploaded,
					//   id: timeId,
					//   statusMsg: "正在上传",
					//   upload,
					//   dir: "/ProjectData/",
					// };
					// uploadInfoStore?.setUploadInfo(item.id, {
					//   ...item,
					//   info: json,
					// });
				},
				onSuccess: function () {
					console.log("3154");
					// const json = {
					//   id: timeId,
					//   percentage: 100,
					//   startTime: timeId,
					//   endTime: new Date().getTime() + 1000,
					//   statusMsg: "上传成功",
					//   upload,
					// };
					// uploadInfoStore?.setUploadInfoList(item.id, json);

					// callBack && callBack(upload, filepath);
				},
			});
			upload.start();
		},
		[fileToken, publicPrijectId, tokenInfo?.access_token]
	);
	const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

	const { run: getPublicEnvFn } = useMyRequest(getPublicEnv, {
		onSuccess: (res: any) => {
			console.log(res);
			let arr = res.map((item: any) => {
				return {
					label: item.title,
					value: item.id,
				};
			});
			setEnvList(arr);
		},
	});

	const { run: getPublicProjectFn } = useMyRequest(getPublicProject, {
		onSuccess: (res: any) => {
			console.log(res);
			setPublicPrijectId(res[0].id);
			setPublicZoneId(res[0].zoneId);
			getDataFileTokenFn({ id: res[0].id });
		},
	});

	const { run: getDataFileTokenFn } = useMyRequest(getDataFileToken, {
		onSuccess: (res: any) => {
			console.log(res);
			setFileToken(res.data);
		},
	});

	useEffect(() => {
		getPublicProjectFn();
	}, [getPublicProjectFn]);

	useEffect(() => {
		getPublicEnvFn({ taskType });
	}, [getPublicEnvFn, taskType]);

	const handleNameChange = (e: any) => {
		console.log(e);
	};

	const handleDescChange = (e: any) => {
		console.log(e);
	};

	return (
		<div className={style.addEnvironment}>
			<div className={style.left}></div>
			<div className={style.right}>
				<div className={style.title}>
					{taskType === "BATCH" ? "批式环境信息" : "流式环境信息"}
				</div>
				<div className={style.content}>
					<div className={style.form}>
						<div className={style.label}>
							环境名称<span className={style.required}>*</span>
						</div>
						<div
							className={classNames({
								[style.formItem]: true,
								[style.formItemHaveHelperText]: nameHelper.text,
							})}
						>
							<MyInput
								value={name}
								onChange={handleNameChange}
								error={nameHelper.error}
								helperText={nameHelper.text}
								placeholder="给环境起个名称"
							></MyInput>
						</div>
						<div className={style.label}>
							描述<span className={style.required}>*</span>
						</div>
						<div className={style.formItem}>
							<MyInput
								value={desc}
								id="desc"
								// label="项目描述"
								multiline
								rows={4}
								placeholder="请输入项目描述"
								onChange={handleDescChange}
							/>
							<span
								style={{
									position: "absolute",
									fontSize: "14px",
									bottom: "7px",
									right: "12px",
									color: desc.length >= 300 ? "#d32f2f" : "#C2C6CC",
								}}
							>
								{desc.length}/300
							</span>
						</div>
						<div className={style.label}>
							基础环境<span className={style.required}>*</span>
						</div>
						<div className={style.formItem}>
							<MySelect
								options={envList}
								fullWidth
								value={baseEnvId}
							></MySelect>
						</div>
						<div className={style.label}>
							上传环境压缩包<span className={style.zipText}>（.zip）</span>
							<span className={style.required}>*</span>
							<span className={style.download}>下载模板</span>
						</div>
						<div className={style.formItem}>
							<div className={style.uploadBox} {...getRootProps()}>
								<input {...getInputProps()} />
								<span>点击选择环境包或将文件</span>
								<span>拖到此处上传</span>
							</div>
						</div>
					</div>
					<div className={style.codeBox}>
						<div className={style.codeTitle}>
							{taskType === "BATCH" ? "Shell脚本" : "Python脚本"}
						</div>
						<div className={style.code}></div>
					</div>
				</div>
				<div className={style.button}>
					<MyButton text="开始构建"></MyButton>
				</div>
			</div>
		</div>
	);
};
export default AddEnvironment;
