import { localGet, localSet } from "@/utils/index";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "@/routers";
import { HOME_URL, STORE_HEAD_IMAGE_PATH } from "@/config";
import { getDetail, checkMenuPermissions } from "@/api/modules/homeEntry";
import { getUserByPhone } from "@/api/modules/newLoginApi";

/**
 * @description 判断是否有操作权限
 * @returns {Boolean} 是否有权限
 */
export async function usePermission(tip?: string) {
  let type = true;
  // if (localGet("createdId") || localGet("geeker-user").userInfo.storeId) {
  //   //   return type;
  //   // }
  let params = {
    phone: localGet("iphone") || localGet("geeker-user").userInfo.phone
  };
  const res: any = await getUserByPhone(params);
  if (res.data && res.data.storeId) {
    localSet("createdId", res.data.storeId);
    const resD: any = await getDetail({
      id: res.data.storeId
    });
    if (resD.data && resD.data.storeApplicationStatus != 1) {
      return false;
    }
    if (resD.data && resD.data.commissionRate) {
      localSet("commissionRate", resD.data.commissionRate);
    }
    if (resD.data && resD.data.businessSection) {
      localSet("businessSection", resD.data.businessSection);
    }
    if (resD.data && resD.data.storeName) {
      localSet("storeName", resD.data.storeName);
    }
  } else {
    type = false;
    if (tip) {
      ElMessage.warning(`请完成商家入驻后再进行${tip}`);
    }
    return type;
  }
  if (!localGet("businessSection") && !localGet("geeker-user").userInfo.businessSection) {
    type = false;
    if (tip) {
      ElMessage.warning(`请完成商家入驻后重新登录再进行${tip}`);
    }
    return type;
  }
  return type;
}

/**
 * @description 检查菜单访问权限（新方法）
 * @returns {Object} 返回合同管理、食品经营许可证、其他资质证明的权限状态
 */
export async function checkMenuAccessPermission(): Promise<{
  contractManagement: boolean;
  foodBusinessLicense: boolean;
  entertainmentBusinessLicense: boolean;
}> {
  try {
    // 调用单个API，返回两个字段
    const res: any = await checkMenuPermissions({
      storeId: localGet("createdId")
    });

    if (res) {
      const data = res || {};
      // 解析合同管理权限
      let contractPermission = false;
      if (data.expirationTime !== undefined) {
        const value = data.expirationTime;
        contractPermission = value == "0";
      }

      // 解析食品经营许可证权限
      let foodPermission = false;
      if (data.foodLicenceExpirationTime !== undefined) {
        const value = data.foodLicenceExpirationTime;
        foodPermission = value == "0";
      }

      // 解析其他资质证明权限
      let entertainmentPermission = false;
      if (data.entertainmentLicenceExpirationTime !== undefined) {
        const value = data.entertainmentLicenceExpirationTime;
        entertainmentPermission = value == "0";
      }

      const userInfo = localGet("geeker-user")?.userInfo || {};
      const businessSection = Number(userInfo.businessSection || localGet("businessSection") || 0);
      const mealsFlag = Number(userInfo.mealsFlag || localGet("mealsFlag") || 0);

      // 食品经营许可证逻辑：
      // - 特色美食(1) 和 酒吧(2)：正常显示
      // - KTV(3)、洗浴汗蒸(4)、按摩足疗(5)、丽人美发(6)、运动健身(7)：仅提供餐食时显示
      if ([1, 2].includes(businessSection)) {
        // 酒吧和特色美食无条件参与食品经营许可证逻辑
      } else if ([3, 4, 5, 6, 7].includes(businessSection)) {
        // KTV等业态需要提供餐食才参与
        if (mealsFlag !== 1) {
          foodPermission = false;
        }
      }
      // 只有酒吧(businessSection=2) 和 KTV(businessSection=3) 才需要展示其他资质证明相关逻辑
      if (![2, 3].includes(businessSection)) {
        entertainmentPermission = false;
      }

      return {
        contractManagement: contractPermission,
        foodBusinessLicense: foodPermission,
        entertainmentBusinessLicense: entertainmentPermission
      };
    }

    // 如果API调用失败或返回格式不正确，默认返回都为 false（不做限制）
    return {
      contractManagement: false,
      foodBusinessLicense: false,
      entertainmentBusinessLicense: false
    };
  } catch (error) {
    console.error("检查菜单权限失败:", error);
    // 如果API调用失败，默认返回都为 false（不做限制）
    return {
      contractManagement: false,
      foodBusinessLicense: false,
      entertainmentBusinessLicense: false
    };
  }
}

/**
 * @description 检查菜单项是否可以点击
 * @param {string} path 菜单路径
 * @returns {Promise<Object>} 返回包含 canClick、contractManagement、foodBusinessLicense、entertainmentBusinessLicense 的对象
 */
export async function checkMenuClickPermission(path?: string): Promise<{
  canClick: boolean;
  contractManagement: boolean;
  foodBusinessLicense: boolean;
  entertainmentBusinessLicense: boolean;
}> {
  // 页面路径常量
  const CONTRACT_MANAGEMENT_PATH = "/licenseManagement/contractManagement"; // 合同管理
  const FOOD_BUSINESS_LICENSE_PATH = "/licenseManagement/foodBusinessLicense"; // 食品经营许可证
  const ENTERTAINMENT_LICENSE_PATH = "/licenseManagement/entertainmentLicense"; // 其他资质证明

  // 调用权限检查方法，获取两个权限状态
  const permissions = await checkMenuAccessPermission();
  const { contractManagement, foodBusinessLicense, entertainmentBusinessLicense } = permissions;

  // 如果全部为 false，不做限制，所有页面都可以点击
  if (!contractManagement && !foodBusinessLicense && !entertainmentBusinessLicense) {
    return {
      canClick: true,
      contractManagement: false,
      foodBusinessLicense: false,
      entertainmentBusinessLicense: false
    };
  }

  // 如果至少有一个为 true，需要检查权限
  // 只有当用户尝试访问已到期的特定页面时，才阻止访问
  let canClick = true;
  if (path) {
    // 检查当前路径是否是已到期的页面
    let isBlocked = false;
    const messages: string[] = [];

    // 检查合同管理页面
    if (path === CONTRACT_MANAGEMENT_PATH && contractManagement) {
      isBlocked = true;
      // 暂时关闭三个权限检查
      // messages.push("合同已到期，请上传最新合同。");
    }
    // 检查食品经营许可证页面
    if (path === FOOD_BUSINESS_LICENSE_PATH && foodBusinessLicense) {
      isBlocked = true;
      // 暂时关闭三个权限检查
      // messages.push("食品经营许可证已到期，请上传最新许可证。");
    }
    // 检查其他资质证明页面
    if (path === ENTERTAINMENT_LICENSE_PATH && entertainmentBusinessLicense) {
      isBlocked = true;
      // 暂时关闭三个权限检查
      // messages.push("其他资质证明已到期，请上传最新许可证。");
    }

    // 如果被阻止，显示提示信息
    if (isBlocked && messages.length) {
      ElMessage.warning({
        // message: messages.join('\n'),
        message: messages.join("<br>"),
        dangerouslyUseHTMLString: true
      });
      canClick = false;
    }
  }

  return {
    canClick,
    contractManagement,
    foodBusinessLicense,
    entertainmentBusinessLicense
  };
}

/**
 * @description 除首页外，点击其他菜单时检查是否已上传头图；未上传则弹框引导去上传头图页（参考商家端）
 * @param path 菜单路径
 * @returns {Promise<boolean>} true 表示可继续跳转，false 表示已拦截（弹框中选择去上传或暂不上传）
 */
export async function checkHeadImageBeforeNavigate(path: string): Promise<boolean> {
  if (!path || path === HOME_URL || path === STORE_HEAD_IMAGE_PATH) {
    return true;
  }
  const storeId = localGet("createdId") || localGet("geeker-user")?.userInfo?.storeId;
  if (!storeId) {
    return true;
  }
  try {
    const res: any = await getDetail({ id: storeId });
    const headImgStatus = res?.data?.headImgStatus;
    // 与商家端一致：headImgStatus === 2 表示未上传头图
    if (headImgStatus !== 2) {
      return true;
    }
    await ElMessageBox.confirm("请先上传头图后再进行下一步操作", "未上传头图", {
      confirmButtonText: "去上传头图",
      cancelButtonText: "暂不上传",
      type: "warning"
    });
    router.push(STORE_HEAD_IMAGE_PATH);
    return false;
  } catch (err: any) {
    if (err === "cancel" || err?.message === "cancel") {
      return false;
    }
    return true;
  }
}
