package com.mosty.yjzl.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mosty.base.model.dto.yjzl.TbZdxlFgdwBddSaveDTO;
import com.mosty.base.model.dto.yjzl.TbZdxlFgdwBddUpdateDTO;
import com.mosty.base.model.entity.yjzl.zddw.TbZdxlFgdwBdd;
import com.mosty.base.model.query.yjzl.TbZdxlFgdwBddQuery;
import com.mosty.base.model.vo.yjzl.TbZdxlFgdwBddVO;
import com.mosty.base.model.vo.yjzl.TbZdxlFgdwVO;
import com.mosty.base.utils.MessageUtils;
import com.mosty.base.utils.spring.SpringValidUtils;
import com.mosty.common.base.domain.ResponseResult;
import com.mosty.common.base.entity.log.BusinessType;
import com.mosty.common.base.entity.log.Log;
import com.mosty.common.token.JwtSysUser;
import com.mosty.yjzl.service.TbZdxlFgdwBddService;
import com.mosty.yjzl.service.TbZdxlFgdwService;
import com.mosty.yjzl.utils.TbZdxlFgxlrwUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author zhangzhao
 * @description 指导巡逻方格点位必到点接口
 * @modifier zhangzhao
 * @modifiedTime 2025/09/06 12:00
 * @since 2025/09/06 12:00
 */
@Api(tags = {"指导巡逻-方格点位必到点接口"})
@RestController
@AllArgsConstructor
@RequestMapping("/tbZdxlFgdwBdd")
public class TbZdxlFgdwBddController {

    /**
     * 指导巡逻方格点位必到点表Service
     */
    private final TbZdxlFgdwBddService tbZdxlFgdwBddService;

    /**
     * 指导巡逻方格点位表Service
     */
    private final TbZdxlFgdwService tbZdxlFgdwService;

    /**
     * 查询单条（根据主键ID）
     * @param id 主键ID
     * @return ResponseResult 实体信息
     */
    @ApiOperation(value = "查询单条（根据主键ID）")
    @GetMapping("{id}")
    @JwtSysUser
    @Log(title = "指导巡逻-方格点位必到点接口-查询单条（根据主键ID）", businessType = BusinessType.OTHER)
    public ResponseResult<TbZdxlFgdwBdd> selectById(@PathVariable("id") String id) {
        return ResponseResult.success(tbZdxlFgdwBddService.selectById(id));
    }

    /**
     * 查询单条（根据必到点巡逻任务ID）
     * @param bddxlrwId 必到点巡逻任务ID
     * @return ResponseResult 实体信息
     */
    @ApiOperation(value = "查询单条（根据必到点巡逻任务ID）")
    @GetMapping("/selectByBddxlrwId/{bddxlrwId}")
    @JwtSysUser
    @Log(title = "指导巡逻-方格点位必到点接口-查询单条（根据必到点巡逻任务ID）", businessType = BusinessType.OTHER)
    public ResponseResult<TbZdxlFgdwBdd> selectByBddxlrwId(@PathVariable("bddxlrwId") String bddxlrwId) {
        return ResponseResult.success(tbZdxlFgdwBddService.selectByBddxlrwId(bddxlrwId));
    }

    /**
     * 查询分页
     * @param query 实体查询对象
     * @return ResponseResult 实体信息分页列表
     */
    @ApiOperation(value = "查询分页")
    @GetMapping("/selectPage")
    @JwtSysUser
    @Log(title = "指导巡逻-方格点位必到点接口-查询分页", businessType = BusinessType.OTHER)
    public ResponseResult<IPage<TbZdxlFgdwBddVO>> selectPage(TbZdxlFgdwBddQuery query) {
        return ResponseResult.success(tbZdxlFgdwBddService.selectPage(query));
    }

    /**
     * 查询列表
     * @param query 实体查询对象
     * @return ResponseResult 实体信息列表
     */
    @ApiOperation(value = "查询列表")
    @GetMapping("/selectList")
    @JwtSysUser
    @Log(title = "指导巡逻-方格点位必到点接口-查询列表", businessType = BusinessType.OTHER)
    public ResponseResult<List<TbZdxlFgdwBddVO>> selectList(TbZdxlFgdwBddQuery query) {
        return ResponseResult.success(tbZdxlFgdwBddService.selectList(query));
    }

    /**
     * 保存单条
     * @param dto 保存DTO对象
     * @param bindResult 校验对象
     * @return ResponseResult 实体主键ID
     */
    @ApiOperation(value = "保存单条")
    @PostMapping("save")
    @JwtSysUser
    @Log(title = "指导巡逻-方格点位必到点接口-保存单条", businessType = BusinessType.INSERT)
    public ResponseResult<String> save(@RequestBody @Valid TbZdxlFgdwBddSaveDTO dto, BindingResult bindResult) {
        try {
            //基础信息校验
            String message = SpringValidUtils.getErrorsMsg(bindResult);
            if (StringUtils.isNotBlank(message)) {
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + message);
            }

            //校验点位是否在方格内
            TbZdxlFgdwVO fgdwVO = tbZdxlFgdwService.selectById(dto.getFgdwId());
            if(ObjectUtils.isEmpty(fgdwVO)){
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "方格信息不存在，请退出页面后重新选择");
            }
            if(ObjectUtils.isEmpty(fgdwVO.getX1()) || ObjectUtils.isEmpty(fgdwVO.getY1()) || ObjectUtils.isEmpty(fgdwVO.getX2()) || ObjectUtils.isEmpty(fgdwVO.getY2())){
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "方格信息不准确，请选择其他方格");
            }
            boolean isInGeometry = TbZdxlFgxlrwUtils.isInGeometry(fgdwVO, dto.getJd(), dto.getWd());
            if(!isInGeometry){
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "点位不在方格内，请重新选点");
            }

            //保存
            String resultId = tbZdxlFgdwBddService.saveEntity(dto);
            if(StringUtils.isNotBlank(resultId)){
                return ResponseResult.success(resultId);
            }
            return ResponseResult.fail(MessageUtils.getSaveFailMsg());
        } catch (Exception e) {
            return ResponseResult.fail(MessageUtils.getSaveServerErrorMsg());
        }
    }

    /**
     * 修改单条
     * @param dto 修改DTO对象
     * @param bindResult 校验对象
     * @return ResponseResult 实体主键ID
     */
    @ApiOperation(value = "修改单条")
    @PostMapping("update")
    @JwtSysUser
    @Log(title = "指导巡逻-方格点位必到点接口-修改单条", businessType = BusinessType.UPDATE)
    public ResponseResult<String> update(@RequestBody @Valid TbZdxlFgdwBddUpdateDTO dto, BindingResult bindResult){
        try {
            //基础信息校验
            String message = SpringValidUtils.getErrorsMsg(bindResult);
            if (StringUtils.isNotBlank(message)) {
                return ResponseResult.fail(MessageUtils.getEditFailMsg() + message);
            }

            //校验数据是否存在
            TbZdxlFgdwBdd baseEntity = tbZdxlFgdwBddService.selectById(dto.getId());
            if(ObjectUtils.isEmpty(baseEntity)){
                return ResponseResult.fail(MessageUtils.getEditDataNotFoundMsg());
            }

            //校验点位是否在方格内
            TbZdxlFgdwVO fgdwVO = tbZdxlFgdwService.selectById(dto.getFgdwId());
            if(ObjectUtils.isEmpty(fgdwVO)){
                return ResponseResult.fail(MessageUtils.getEditFailMsg() + "方格信息不存在，请退出页面后重新选择");
            }
            if(ObjectUtils.isEmpty(fgdwVO.getX1()) || ObjectUtils.isEmpty(fgdwVO.getY1()) || ObjectUtils.isEmpty(fgdwVO.getX2()) || ObjectUtils.isEmpty(fgdwVO.getY2())){
                return ResponseResult.fail(MessageUtils.getEditFailMsg() + "方格信息不准确，请选择其他方格");
            }
            boolean isInGeometry = TbZdxlFgxlrwUtils.isInGeometry(fgdwVO, dto.getJd(), dto.getWd());
            if(!isInGeometry){
                return ResponseResult.fail(MessageUtils.getEditFailMsg() + "点位不在方格内，请重新选点");
            }

            //修改
            String resultId = tbZdxlFgdwBddService.updateEntity(dto);
            if(StringUtils.isNotBlank(resultId)){
                return ResponseResult.success(resultId);
            }
            return ResponseResult.fail(MessageUtils.getEditFailMsg());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(MessageUtils.getEditServerErrorMsg());
        }
    }

    /**
     * 注销单条
     * @param id 主键ID
     * @return ResponseResult 注销条数
     */
    @ApiOperation(value = "注销单条")
    @DeleteMapping("{id}")
    @JwtSysUser
    @Log(title = "指导巡逻-方格点位必到点接口-注销单条", businessType = BusinessType.DELETE)
    public ResponseResult<Integer> cancelById(@PathVariable("id") String id) {
        try {
            //如果传入的ID为空，返回失败
            if(StringUtils.isBlank(id)){
                return ResponseResult.fail(MessageUtils.getCancelFailMsg() + MessageUtils.message("id.bnwk"));
            }

            //如果该实体已经被注销，则返回成功
            TbZdxlFgdwBdd entity = tbZdxlFgdwBddService.selectById(id);
            if(entity == null){
                return ResponseResult.success(0);
            }

            return ResponseResult.success(tbZdxlFgdwBddService.cancelEntity(entity));
        } catch (Exception e) {
            return ResponseResult.fail(MessageUtils.getCancelServerErrorMsg());
        }
    }

}
