import icon_usb from "../assets/icon_usb.svg";
import icon_bluetooth from "../assets/icon_bluetooth.svg";
import icon_charging from "../assets/icon-charging.svg";
import icon_avatar from "../assets/icon_avatar.svg";
import icon_logout from "../assets/icon_logout.svg";
import {
  UndoOutlined
} from '@ant-design/icons';
import check_mark from "../assets/check_mark.svg";
import { useState, useEffect } from "react";
import { Dropdown, MenuProps, message, Popover } from "antd";
import { logout } from "../services/user/user";
import { useNavigate } from "react-router";
import { useAppDispatch, useAppSelector } from "../utils/hooks";
import { updateUser } from "../store/features/contextSlice";
import "./bluetooth.scss";
import { update } from "../services/ktj/org";
export default function Header() {
	const navigate = useNavigate();
	const dispatch = useAppDispatch();
	const deviceInfo = useAppSelector(store => store.context.device);
	// const deviceState = useAppSelector(store => store.context.device);
	const userInfo = useAppSelector(store => store.context.user.loginUser);
	const [power, setPower] = useState(deviceInfo.power.toFixed())//deviceInfo.power.toFixed()
	const [powerColor, setPowerColor] = useState('bluetooth-battery')
	//获取当前websocet的状态

	const showBlueImg = () => {
		if (deviceInfo.isConnected && deviceInfo.connectedType === "BLE_CHANNEL") {
			return (
				<Popover content={getBtBlueContent()} title="" trigger="click">
					<section className="bg-white rounded-md h-9 w-10 flex justify-center items-center mr-3">
						<img src={icon_bluetooth} alt="" className="h-6" />
					</section>
				</Popover>
			);
		}
		return null;
	};
	const showUsbImg = () => {
		if (deviceInfo.isConnected && deviceInfo.connectedType === "UART_CHANNEL") {
			return (
				<Popover content={getBtContent()} title="" trigger="click">
					<section className="bg-white rounded-md h-9 w-10 flex justify-center items-center mr-3">
						<img src={icon_usb} alt="" className="h-6" />
					</section>
				</Popover>
			);
		}
		return null;
	};

	useEffect(() => {
		if (userInfo.nickname || userInfo.account) {
			let name = userInfo.nickname || userInfo.account
			setNickname(name);
		} else {
			const user = localStorage.getItem("user");
			if (user) {
				let userData = JSON.parse(user || "");
				setNickname(userData.nickname || userData.account);
			}
		}
	}, [userInfo.nickname, userInfo.account]);

	useEffect(() => {
		if(deviceInfo.power > 20){
			setPowerColor('bluetooth-battery')
		}
		if(deviceInfo.power <= 20){
			setPowerColor('bluetooth-battery-red')
		}
		if(deviceInfo.flag === 1){
			setPowerColor('bluetooth-battery-green')
		}
	}, [deviceInfo.power])

	//同步科天健基础数据
	const onSyncKTJData = () => {
		update()
	}

	const [messageApi, contextHolder] = message.useMessage();
	const [nickname, setNickname] = useState<string>();
	const items: MenuProps["items"] = [
		{
			key: "1",
			icon: <UndoOutlined style={{color:"rgb(62 99 203)",fontSize:"18px"}}/>,
			label: "同步数据",
			onClick: () => onSyncKTJData(),
		},
		{
			key: "2",
			label: "退出登录",
			icon: <img src={icon_logout} alt="icon" className="w-5" />,
			onClick: () => {
				logout({}).then(res => {
					if (res.status !== 0) {
						messageApi.error(res.data.info);
					} else {
						localStorage.setItem("user", "");
						dispatch(
							updateUser({
								loginFlag: false,
								loginUser: {},
							})
						);
						navigate("/login");
					}
				});
			},
		},
	];

	const getBtBlueContent = () => {
		return (
			<div>
				<div>
					<div className="bluetooth_c">
						<img src={check_mark} alt="" className="ext-base ml-2 h-4" />
						<div className="ml-[10px]">蓝牙已连接</div>
					</div>
					<div className="pl-[15px]">
						<div className="mt-[1rem] ml-[1.6rem]">sn码：{deviceInfo.sn}</div>
					</div>
				</div>
			</div>
		);
	};

	//设备已连接
	const getBtContent = () => {
		return (
			<div>
				<div>
					<div className="bluetooth_c">
						<img src={check_mark} alt="" className="ext-base ml-2 h-4" />
						<div className="ml-[10px]">设备已连接</div>
					</div>
					<div className="pl-[15px]">
						<div className="mt-[1rem] ml-[1.6rem]">sn码：{deviceInfo.sn}</div>
					</div>
				</div>
			</div>
		);
	};

	return (
		<>
			{contextHolder}
			<div className="bg-[--bgColor] h-full flex justify-end items-center">
				{deviceInfo.isConnected && (
					<>
						<section className=" rounded-md h-9 mr-4 flex items-center bg-white gap-2 pl-4">
							<span className="w-[94px]">温度：{deviceInfo.temperature.toFixed(1)}℃ </span>
							<span className="w-[120px]">X轴倾斜：{deviceInfo.inclinatorX}</span>
							<span className="w-[120px]">Y轴倾斜：{deviceInfo.inclinatorY}</span>
						</section>
						<section className="bg-white rounded-md h-9 w-12 relative  mr-3 flex justify-center items-center">
							
							<div className={`${powerColor} flex justify-center items-center`}>
								<div className="power-process" style={{width: `${power}%`}}>
									<div style={{"position": "relative","top": "-1.6rem"}}>{power}%</div>
								</div>
								{deviceInfo.flag === 1 && 
									<div className="power-charging">
										<img
											src={icon_charging}
											width="15"
											alt=""
										/>
									</div>
								}
								{/* <div className='power-value'>{power}%</div> */}
							</div>
							{/* <p className="text-primary text-xs">{deviceInfo.power.toFixed()}%</p> */}
						</section>
					</>
				)}
				{showBlueImg()}
				{showUsbImg()}
				<div className="mr-8 flex items-center min-w-[5rem]">
					<Dropdown menu={{ items }} trigger={["click"]}>
						<section className="flex items-center">
							<img src={icon_avatar} alt="" className="h-8" />
							<p className="text-base ml-2">{nickname || "未登录"}</p>
						</section>
					</Dropdown>
				</div>
			</div>
		</>
	);
}
