package com.hrs.controller.landlord;

import com.hrs.model.entity.House;
import com.hrs.model.entity.User;
import com.hrs.service.HouseService;
import com.hrs.service.impl.HouseServiceImpl;
import com.hrs.util.ImageUploadUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
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 javax.servlet.http.Part;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;


/**   
* Copyright: Copyright (c) 2026 chinasofti
* 
* @ClassName: HouseAddController.java
* @Description: 添加房源控制器
*
* @version: v1.0.0
* @author: 李鑫
* @date: 2026年4月13日 上午8:55:45 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     李鑫           v1.0.0               新建文件
*/
@WebServlet("/landlord/house/add")
@MultipartConfig(
    maxFileSize = 5 * 1024 * 1024,
    maxRequestSize = 25 * 1024 * 1024
)
public class HouseAddController extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // 获取登录用户
        HttpSession session = request.getSession(false);
        if (session == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null || !"1".equals(loginUser.getRoleType())) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        request.setAttribute("loginUser", loginUser);
        request.getRequestDispatcher("/jsp/landlord/house_add.jsp").forward(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        
        // 获取登录用户
        HttpSession session = request.getSession(false);
        if (session == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null || !"1".equals(loginUser.getRoleType())) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        // 获取表单参数
        String title = request.getParameter("title");
        String area = request.getParameter("area");
        String address = request.getParameter("address");
        String houseType = request.getParameter("houseType");
        String rentPriceStr = request.getParameter("rentPrice");
        String rentType = request.getParameter("rentType");
        String facility = request.getParameter("facility");
        String description = request.getParameter("description");
        
        // 验证必填项
        if (title == null || title.trim().isEmpty()) {
            request.setAttribute("error", "房源标题不能为空");
            doGet(request, response);
            return;
        }
        
        if (rentPriceStr == null || rentPriceStr.trim().isEmpty()) {
            request.setAttribute("error", "租金不能为空");
            doGet(request, response);
            return;
        }
        
        // 处理图片上传
        Collection<Part> parts = request.getParts();
        String imgUrl = ImageUploadUtil.saveMultipleImages(parts, request);
        
        // 生成房源编号
        String houseNo = generateHouseNo();
        
        // 创建房源对象
        House house = new House();
        house.setLandlordId(loginUser.getId());
        house.setHouseNo(houseNo);
        house.setTitle(title);
        house.setArea(area);
        house.setAddress(address);
        house.setHouseType(houseType);
        house.setRentPrice(new BigDecimal(rentPriceStr));
        house.setRentType(rentType);
        house.setFacility(facility);
        house.setDescription(description);
        house.setImgUrl(imgUrl);
        house.setStatus("0");  // 默认待审核状态
        
        // 使用Service层添加房源
        HouseService houseService = new HouseServiceImpl();
        HouseService.AddHouseResult result = houseService.addHouse(house);
        
        if (result.isSuccess()) {
            String encodedMsg = URLEncoder.encode(result.getMessage(), "UTF-8");
            response.sendRedirect(request.getContextPath() + "/landlord/house/list?msg=" + encodedMsg);
        } else {
            request.setAttribute("error", result.getMessage());
            doGet(request, response);
        }
    }
    
    /**
     * 生成房源编号
     */
    private String generateHouseNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return "H" + sdf.format(new Date());
    }
}