import { localGet, localSet } from "@/utils/index";
import { ElMessage } from "element-plus";
import { getUserByPhone, getDetail, checkMenuPermissions } from "@/api/modules/homeEntry";

/**
 * @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;
}> {
  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";
      }

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

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

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

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

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

  // 如果至少有一个为true，需要检查权限
  // 构建允许访问的路径列表
  const allowedPaths: string[] = [];
  if (contractManagement) {
    allowedPaths.push(CONTRACT_MANAGEMENT_PATH);
  }
  if (foodBusinessLicense) {
    allowedPaths.push(FOOD_BUSINESS_LICENSE_PATH);
  }

  // 检查当前路径是否在允许访问的列表中
  const canClick = allowedPaths.includes(path);

  // 如果不可点击，根据权限状态显示相应的提示信息
  if (!canClick) {
    let message = "";

    // 如果两者都为true，显示两行提示
    if (contractManagement && foodBusinessLicense) {
      message = "合同已到期，请上传最新合同。\n经营许可证已到期，请上传最新许可证。";
    } else if (contractManagement) {
      // 只有合同管理为true
      message = "合同已到期，请上传最新合同。";
    } else if (foodBusinessLicense) {
      // 只有食品经营许可证为true
      message = "经营许可证已到期，请上传最新许可证。";
    }

    if (message) {
      ElMessage.warning(message);
    }
  }

  return {
    canClick,
    contractManagement,
    foodBusinessLicense
  };
}
