package com.hrs.controller.user;

import com.hrs.dao.CollectionDao;
import com.hrs.dao.impl.CollectionDaoImpl;
import com.hrs.model.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**   
* Copyright: Copyright (c) 2026 chinasofti
* 
* @ClassName: CollectionDeleteController.java
* @Description: 取消收藏控制器/支持两种删除方式:
*
* @version: v1.0.0
* @author: 李鑫
* @date: 2026年4月13日 上午9:03:05 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     李鑫           v1.0.0               新建文件
*/
@WebServlet("/user/collection/delete")
public class CollectionDeleteController extends HttpServlet {
    
    private CollectionDao collectionDao = new CollectionDaoImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // 获取来源参数
        String from = request.getParameter("from");
        String idStr = request.getParameter("id");
        String houseIdStr = request.getParameter("houseId");
        
        // 判断是否是AJAX请求
        String ajax = request.getParameter("ajax");
        
        // 1. 获取登录用户
        HttpSession session = request.getSession(false);
        if (session == null) {
            if ("true".equals(ajax)) {
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter out = response.getWriter();
                out.print("{\"success\":false,\"msg\":\"未登录\"}");
                return;
            } else {
                response.sendRedirect(request.getContextPath() + "/user/login");
                return;
            }
        }
        
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null || !"0".equals(loginUser.getRoleType())) {
            if ("true".equals(ajax)) {
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter out = response.getWriter();
                out.print("{\"success\":false,\"msg\":\"未登录\"}");
                return;
            } else {
                response.sendRedirect(request.getContextPath() + "/user/login");
                return;
            }
        }
        
        boolean success = false;
        
        // 2. 根据ID删除（从收藏列表删除）
        if (idStr != null && !idStr.trim().isEmpty()) {
            Long id = Long.parseLong(idStr);
            success = collectionDao.deleteById(id);
        }
        // 3. 根据房源ID删除（从详情页删除）
        else if (houseIdStr != null && !houseIdStr.trim().isEmpty()) {
            Long houseId = Long.parseLong(houseIdStr);
            success = collectionDao.delete(loginUser.getId(), houseId);
        }
        
        // 4. 处理返回结果
        if ("true".equals(ajax)) {
            // AJAX请求：返回JSON
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            if (success) {
                out.print("{\"success\":true,\"msg\":\"取消收藏成功\"}");
            } else {
                out.print("{\"success\":false,\"msg\":\"取消收藏失败\"}");
            }
        } else {
            // 普通请求：页面跳转
            if (success) {
                // 根据来源参数决定跳转位置
                if ("detail".equals(from) && houseIdStr != null) {
                    // 从详情页删除，跳回详情页
                    String encodedMsg = URLEncoder.encode("取消收藏成功", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/user/house/detail?id=" + houseIdStr + "&msg=" + encodedMsg);
                } else if ("list".equals(from)) {
                    // 从收藏列表删除，跳回收藏列表
                    String encodedMsg = URLEncoder.encode("取消收藏成功", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/user/collection/list?msg=" + encodedMsg);
                } else {
                    // 默认跳回收藏列表
                    String encodedMsg = URLEncoder.encode("取消收藏成功", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/user/collection/list?msg=" + encodedMsg);
                }
            } else {
                if ("detail".equals(from) && houseIdStr != null) {
                    String encodedError = URLEncoder.encode("取消收藏失败", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/user/house/detail?id=" + houseIdStr + "&error=" + encodedError);
                } else {
                    String encodedError = URLEncoder.encode("取消收藏失败", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/user/collection/list?error=" + encodedError);
                }
            }
        }
    }
}