package com.gxwebsoft.house.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.bszx.entity.BszxBm;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.house.entity.HouseLikeLog;
import com.gxwebsoft.house.entity.HouseViewsLog;
import com.gxwebsoft.house.service.HouseInfoService;
import com.gxwebsoft.house.entity.HouseInfo;
import com.gxwebsoft.house.param.HouseInfoParam;
import com.gxwebsoft.house.util.SortSceneUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.house.service.HouseLikeLogService;
import com.gxwebsoft.house.service.HouseViewsLogService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 房源信息表控制器
 *
 * @author 科技小王子
 * @since 2025-03-05 13:47:14
 */
@Tag(name = "房源信息表管理")
@RestController
@RequestMapping("/api/house/house-info")
public class HouseInfoController extends BaseController {
    @Resource
    private HouseInfoService houseInfoService;
    @Resource
    private HouseLikeLogService houseLikeLogService;
    @Resource
    private HouseViewsLogService houseViewsLogService;

    @Operation(summary = "分页查询房源信息表")
    @GetMapping("/page")
    public ApiResult<PageResult<HouseInfo>> page(HouseInfoParam param) {
        // 标准化排序参数，解决URL编码问题
        if (param.getSortScene() != null) {
            String normalizedSortScene = SortSceneUtil.normalizeSortScene(param.getSortScene());
            param.setSortScene(normalizedSortScene);
        }

        // 使用关联查询
        return success(houseInfoService.pageRel(param));
    }


    @PreAuthorize("hasAuthority('house:houseInfo:list')")
    @Operation(summary = "查询全部房源信息表")
    @GetMapping()
    public ApiResult<List<HouseInfo>> list(HouseInfoParam param) {
        // 使用关联查询
        return success(houseInfoService.listRel(param));
    }

    @Operation(summary = "根据id查询房源信息表")
    @GetMapping("/{id}")
    public ApiResult<HouseInfo> get(@PathVariable("id") Integer id) {
      HouseInfo byIdRel = houseInfoService.getByIdRel(id);
      Integer loginUserId = getLoginUserId();
      if(loginUserId != null) {
        // 是否喜欢
        HouseLikeLog log = houseLikeLogService.getByIdRel(id, loginUserId);
        byIdRel.setLiked(log != null);
        // 添加浏览记录
        houseViewsLogService.add(byIdRel, loginUserId);
      }
      // 使用关联查询
      return success(byIdRel);
    }

    @PreAuthorize("hasAuthority('house:houseInfo:save')")
    @Operation(summary = "添加房源信息表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody HouseInfo houseInfo) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
         houseInfo.setUserId(loginUser.getUserId());
        }
        if (houseInfoService.save(houseInfo)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('house:houseInfo:update')")
    @Operation(summary = "修改房源信息表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody HouseInfo houseInfo) {
        if (houseInfoService.updateById(houseInfo)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('house:houseInfo:remove')")
    @Operation(summary = "删除房源信息表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (houseInfoService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('house:houseInfo:save')")
    @Operation(summary = "批量添加房源信息表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<HouseInfo> list) {
        if (houseInfoService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('house:houseInfo:update')")
    @Operation(summary = "批量修改房源信息表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<HouseInfo> batchParam) {
        if (batchParam.update(houseInfoService, "house_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('house:houseInfo:remove')")
    @Operation(summary = "批量删除房源信息表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (houseInfoService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @Operation(summary = "获取海报地址")
    @GetMapping("/generatePoster/{id}")
    public ApiResult<?> generatePoster(@PathVariable("id") Integer id) throws Exception {
      final HouseInfo houseInfo = houseInfoService.getOne(new LambdaQueryWrapper<HouseInfo>().eq(HouseInfo::getHouseId, id).last("limit 1"));
      return success("生成房源海报",houseInfoService.generatePoster(houseInfo));
    }

}
