package com.propertyManagement.web.controller.business.api;

import com.propertyManagement.business.domain.WxComment;
import com.propertyManagement.business.domain.bo.WxCommentBo;
import com.propertyManagement.business.domain.vo.LoginWxUser;
import com.propertyManagement.business.domain.vo.WxCommentVo;
import com.propertyManagement.business.mapper.WxCommentMapper;
import com.propertyManagement.business.service.IWxCommentService;
import com.propertyManagement.business.support.util.AuthUtil;
import com.propertyManagement.common.annotation.RepeatSubmit;
import com.propertyManagement.common.core.controller.BaseController;
import com.propertyManagement.common.core.domain.R;
import com.propertyManagement.common.core.validate.AddGroup;
import com.propertyManagement.common.enums.RepairsState;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 表扬与投诉
 *
 * @author liushuai
 * @date 2025-05-14
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/comment")
public class ApiWxCommentController extends BaseController {

    private final IWxCommentService iWxCommentService;
    private final WxCommentMapper wxCommentMapper;

    /**
     * 查询用户历史工单列表
     */
    @GetMapping("/userListAll")
    public R<List<WxCommentVo>> list(WxCommentBo bo) {
        LoginWxUser wxUser = AuthUtil.getWxUser();
        bo.setCommunityId(wxUser.getCommunityId());
        bo.setUserId(wxUser.getId());
        return R.ok(iWxCommentService.queryList(bo));
    }

    /**
     * 查询用户历史工单状态统计
     */
    @GetMapping("/userCountAll")
    public R<Map<Integer, Long>> userCountAll() {
        return R.ok(iWxCommentService.userCountAll());
    }


    /**
     * 获取表扬与投诉详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<WxCommentVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iWxCommentService.queryById(id));
    }

    /**
     * 新增表扬与投诉
     */
    @RepeatSubmit()
    @PostMapping("/add")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody WxCommentBo bo) {
        return toAjax(iWxCommentService.add(bo));
    }

    /**
     * 取消表扬或投诉
     *
     * @param id 主键
     */
    @PutMapping("/cancel/{id}")
    public R<Void> cancel(@NotNull(message = "主键不能为空")
                          @PathVariable Long id) {
        WxComment wxComment = wxCommentMapper.selectById(id);
        if (wxComment == null) {
            return R.fail("取消失败，工单不存在");
        }
        if (!wxComment.getState().equals(RepairsState.ONE.getCode())) {
            return R.fail("取消失败，工单状态错误");
        }
        wxComment.setState(3);
        wxComment.setCloseTime(new Date());
        wxCommentMapper.updateById(wxComment);
        return toAjax(true);
    }
}
