import hocAuth from "@/hocs/auth";
import { CommonComponent } from "@/types/typings";
import { Text, View } from "@tarojs/components";
import { useEffect, useState } from "react";
import { auth } from "@/services";
import { Button, Dialog, Image, Popup, Toast } from "@nutui/nutui-react-taro";
import dayjs from "dayjs";
import Taro from "@tarojs/taro";
import { buildUrl, uploadFile } from "@/utils";
import { globalStore } from "@/store/global-store";
import { APP_VERSION } from "@/constant";
import { CustomTabBar, Icon } from "@/components";

// 示例：通过连续点击标题触发后门
let clickCount = 0;
let lastClickTime = 0;

export default hocAuth(function Page(props: CommonComponent) {
  const { user, userRoleVO } = props;
  console.log("userRoleVO", userRoleVO);
  const setUserRoleVO = globalStore((state: any) => state.setUserRoleVO);

  const [visible, setVisible] = useState(false);
  const [employeeVO, setEmployeeVO] = useState<AuthAPI.EmployeeVO>();
  const [userRoleVOList, setUserRoleVOList] = useState<AuthAPI.UserRoleVO[]>();

  const [roleSlug, setRoleSlug] = useState<BusinessAPI.RoleVO["slug"]>(
    userRoleVO.slug,
  );

  const [channel, setChannel] = useState<BusinessAPI.ChannelVO>();

  const [enableDebug, setEnableDebug] = useState<boolean>(false);
  const onTitleClick = () => {
    const now = Date.now();
    if (now - lastClickTime < 1000) {
      // 1秒内连续点击
      clickCount++;
      if (clickCount >= 5) {
        // 打开调试
        Taro.setEnableDebug({
          enableDebug: !enableDebug,
        });
        setEnableDebug(!enableDebug);
        clickCount = 0;
      }
    } else {
      clickCount = 1;
    }
    lastClickTime = now;
  };

  const initChannel = async () => {
    const { data } = await auth.channel.selectChannelByDomain({
      domain: "operation.erp.qilincloud168.com",
    });

    setChannel(data.data);
  };

  const init = async (user: AuthAPI.UserVO) => {
    let platformId = "1991353387274342401";
    const {
      data: { data: employeeVO },
    } = await auth.user.userEmployee({
      employeeShowQry: {
        userId: user.userId,
        //@ts-ignore
        platformId: platformId,
      },
    });

    if (employeeVO) {
      setEmployeeVO(employeeVO);
      const userRoleVOList =
        employeeVO.userRoleList?.filter(
          //@ts-ignore
          (item) => item.platformId === platformId,
        ) || [];
      setUserRoleVOList(userRoleVOList);

      let userRoleVO = Taro.getStorageSync("userRoleVO");
      if (!userRoleVO) {
        userRoleVO = userRoleVOList?.[0]!;
        Taro.setStorageSync("userRoleVO", userRoleVO);
      }

      setUserRoleVO(userRoleVO);
    }
  };

  useEffect(() => {
    if (user) {
      init(user).then();
      initChannel().then();
    }
  }, [user]);

  if (!employeeVO) {
    return;
  }

  // 处理角色切换
  const handleRoleSelect = (userRoleVO: AuthAPI.UserRoleVO) => {
    setRoleSlug(userRoleVO.slug);
  };

  // 选择图片函数
  const chooseImage = async () => {
    return new Promise((resolve, reject) => {
      Taro.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album"],
        success: (res) => {
          resolve(res.tempFilePaths[0]);
        },
        fail: (res) => {
          reject(new Error(`选择图片失败: ${res.errMsg}`));
        },
      });
    });
  };
  // 处理头像上传
  const handleAvatarUpload = async () => {
    try {
      const imagePath = await chooseImage();

      if (imagePath) {
        Taro.showLoading({ title: "上传中..." });

        // 上传文件
        const uploadResult = await uploadFile(imagePath as any);

        if (uploadResult?.url) {
          // 更新用户头像
          const updateRes = await auth.user.userEmployeeUpdateAvatar({
            employeeId: employeeVO.employeeId,
            avatar: uploadResult.url,
          });

          if (updateRes.data.success) {
            // 更新本地用户信息
            setEmployeeVO((prev) => ({
              ...prev!,
              avatar: uploadResult.url,
            }));

            Toast.show("toast", {
              icon: "success",
              content: "头像更新成功",
            });
          } else {
            Toast.show("toast", {
              icon: "fail",
              content: "更新失败",
            });
          }
        }

        Taro.hideLoading();
      }
    } catch (err) {
      console.error("头像上传失败:", err);
      Taro.hideLoading();
      Toast.show("toast", {
        icon: "fail",
        content: "上传失败",
      });
    }
  };

  // 确认切换角色
  const handleConfirmSwitch = () => {
    const userRoleVO = userRoleVOList?.find((item) => item.slug === roleSlug);
    if (userRoleVO) {
      Taro.setStorageSync("userRoleVO", userRoleVO);
      setUserRoleVO(userRoleVO);
      setVisible(false);

      Toast.show("toast", {
        icon: "success",
        title: "提示",
        content: "切换成功，正在跳转工作台...",
      });

      setTimeout(() => {
        Taro.reLaunch({
          url: buildUrl("/pages/main/index/index"),
        });
      }, 1000);
    }
  };

  return (
    <>
      <View className="flex flex-1 flex-col px-2.5 pt-2.5 pb-16">
        {/* 个人信息卡片 */}
        <View className="mb-2.5 rounded-xl bg-white p-2.5 shadow-sm">
          <View className="flex items-start">
            {/* 头像区域 */}
            <View className="relative mr-2.5" onClick={handleAvatarUpload}>
              {employeeVO?.avatar ? (
                <View className="flex h-16 w-16 items-center justify-center rounded-full text-2xl shadow-md">
                  <Image
                    src={employeeVO?.avatar}
                    mode={"aspectFill"}
                    className={"h-full w-full overflow-hidden rounded-full"}
                  />
                </View>
              ) : (
                <View className="flex h-16 w-16 items-center justify-center rounded-full bg-gray-200 text-2xl">
                  {employeeVO.name.slice(0, 1)}
                </View>
              )}

              <View className="bg-primary absolute right-0 bottom-0 flex h-6 w-6 items-center justify-center rounded-full text-white">
                <Icon
                  name="camera"
                  className={"text-xs"}
                  color={"#fff"}
                  size={12}
                />
              </View>
            </View>
            {/* 用户信息 */}
            <View className="flex-1">
              <View className="flex items-center justify-between">
                <View className="text-sm font-bold">{employeeVO.name}</View>
                <View
                  className="flex items-center"
                  onClick={() => {
                    setVisible(true);
                  }}
                >
                  <View className={"text-primary text-sm"}>
                    {userRoleVO?.name || "请选择身份"}
                  </View>
                  <Icon name="chevron-down" className={"ml-1"} size={12} />
                </View>
              </View>
              <View className="text-neutral-darker mt-2 text-xs">
                <View>员工ID: {employeeVO.number}</View>
                <View className={"mt-1"}>
                  最后登录: {dayjs(user.lastLoginAt).format("YYYY-MM-DD HH:mm")}
                </View>
              </View>
            </View>
          </View>
        </View>
        {/* 功能菜单区 */}
        <View className="mb-2.5 overflow-hidden rounded-lg bg-white shadow-sm">
          {/* 账户设置 */}
          <View className="border-b border-gray-100 p-2.5">
            <View className="px-2 py-1 text-base font-medium text-gray-500">
              账户设置
            </View>
            <View className="flex items-center justify-between p-2.5">
              <View className="flex items-center">
                <Icon name="key" className="text-primary mr-2.5" />
                <View className={"text-sm"}>修改密码</View>
              </View>
              <Icon
                name="chevron-right"
                size={16}
                color={"var(--color-gray-400)"}
              />
            </View>
            <View
              className="flex items-center justify-between p-2.5"
              onClick={() => {
                Dialog.open("dialog", {
                  title: "确认登出",
                  content: "确定要退出当前账户吗？",
                  confirmText: "确认",
                  cancelText: "取消",
                  onConfirm: async () => {
                    Taro.showLoading({
                      title: "正在登出...",
                      mask: true,
                    });

                    await auth.userAuth.logout().then(() => {
                      Taro.removeStorageSync("user");
                      Taro.removeStorageSync("userRoleVO");
                      Taro.removeStorageSync("saToken");
                    });

                    Taro.redirectTo({
                      url: buildUrl("/pages/public/login/index"),
                      success: () => {
                        Taro.hideLoading();
                        Dialog.close("dialog");
                      },
                    });
                  },
                  onCancel: () => {
                    Dialog.close("dialog");
                  },
                });
              }}
            >
              <View className="flex items-center">
                <Icon
                  name="arrow-right-from-bracket"
                  className="text-primary mr-2.5"
                />
                <View className={"text-sm"}>账户登出</View>
              </View>
              <Icon
                name="chevron-right"
                size={16}
                color={"var(--color-gray-400)"}
              />
            </View>
          </View>
          {/* 帮助与支持 */}
          <View className="p-2">
            <View className="px-2 py-1 text-base font-medium text-gray-500">
              帮助与支持
            </View>
            <View className="flex items-center justify-between p-2.5">
              <View className="flex items-center">
                <Icon name="circle-question" className="text-primary mr-2.5" />
                <View className={"text-sm"}>使用指南</View>
              </View>
              <Icon
                name="chevron-right"
                size={16}
                color={"var(--color-gray-400)"}
              />
            </View>
            <View className="flex items-center justify-between p-2.5">
              <View className="flex items-center">
                <Icon name="comment-dots" className="text-primary mr-2.5" />
                <View className={"text-sm"}>联系客服</View>
              </View>
              <Icon
                name="chevron-right"
                size={16}
                color={"var(--color-gray-400)"}
              />
            </View>
            <View className="flex items-center justify-between p-2.5">
              <View className="flex items-center">
                <Icon name="circle-info" className="text-primary mr-2.5" />
                <View className={"text-sm"}>隐私政策</View>
              </View>
              <Icon
                name="chevron-right"
                size={16}
                color={"var(--color-gray-400)"}
              />
            </View>
          </View>
        </View>
      </View>

      <View
        className="flex w-full flex-col py-4 text-center"
        onClick={onTitleClick}
      >
        <Text className="text-neutral-darker text-xs">
          版本号：{APP_VERSION}
        </Text>
        <Text className="text-neutral-darker mt-1 text-xs">
          © {dayjs().format("YYYY")} {channel?.technicalSupport} 版权所有
        </Text>
      </View>
      {process.env.TARO_ENV === "weapp" && <CustomTabBar />}

      {/* 选择身份 */}
      <Popup
        duration={150}
        style={{
          minHeight: "auto",
        }}
        className={"w-full"}
        closeable
        destroyOnClose
        visible={visible}
        title="选择身份"
        onClose={async () => {
          if (visible) {
            setVisible(false);
          }
        }}
      >
        <View className={"mb-4 flex flex-col px-2.5"}>
          {userRoleVOList?.map((item) => (
            <View
              key={item.roleId}
              className={`role-item rounded-lg p-3 ${item?.slug === roleSlug ? "bg-primary/10 border-primary border" : ""}`}
              onClick={() => handleRoleSelect(item)}
            >
              <View className="flex items-center justify-between">
                <View>
                  <View className="font-medium">{item.name}</View>
                  <View className="text-neutral-darker text-xs">
                    {item.description || "暂无描述"}
                  </View>
                </View>
              </View>
            </View>
          ))}
        </View>

        <View className={"p-3"}>
          <Button
            type={"primary"}
            block
            size={"large"}
            onClick={handleConfirmSwitch}
          >
            确认切换
          </Button>
        </View>
      </Popup>
    </>
  );
});
