package com.mosty.yjzl.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mosty.base.model.dto.yjzl.TbZdxlFgdwBddxlrwJlClockInDTO;
import com.mosty.base.model.entity.yjzl.zddw.TbZdxlFgdwBdd;
import com.mosty.base.model.entity.yjzl.zddw.TbZdxlFgdwBddxlrw;
import com.mosty.base.model.entity.yjzl.zddw.TbZdxlFgdwBddxlrwJl;
import com.mosty.base.model.query.yjzl.BddxlrwJlQuery;
import com.mosty.base.model.vo.yjzl.TbZdxlFgdwBddxlrwJlVo;
import com.mosty.base.model.vo.yjzl.TbZdxlFgdwVO;
import com.mosty.base.utils.MessageUtils;
import com.mosty.base.utils.PositionUtil;
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.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.yjzl.service.TbZdxlFgdwBddService;
import com.mosty.yjzl.service.TbZdxlFgdwBddxlrwJlService;
import com.mosty.yjzl.service.TbZdxlFgdwBddxlrwService;
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.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author zhangzhao
 * @description 指导巡逻方格点位必到点巡逻任务记录接口
 * @modifier zhangzhao
 * @modifiedTime 2025/09/07 19:55
 * @since 2025/09/07 19:55
 */
@Api(tags = {"指导巡逻-方格点位必到点巡逻任务记录接口"})
@RestController
@AllArgsConstructor
@RequestMapping("/tbZdxlFgdwBddxlrwJl")
public class TbZdxlFgdwBddxlrwJlController {

    /**
     * 指导巡逻方格点位必到点巡逻任务记录表Service
     */
    private final TbZdxlFgdwBddxlrwJlService tbZdxlFgdwBddxlrwJlService;

    /**
     * 指导巡逻方格点位必到点巡逻任务表Service
     */
    private final TbZdxlFgdwBddxlrwService tbZdxlFgdwBddxlrwService;

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

    private final TbZdxlFgdwBddService tbZdxlFgdwBddService;

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

    /**
     * 创建列表（根据方格巡逻任务ID）
     * @param fgxlrwId 方格巡逻任务ID
     * @return ResponseResult 实体信息列表
     */
    @ApiOperation(value = "创建列表（根据方格巡逻任务ID）")
    @GetMapping("/createListByFgxlrwId")
    @JwtSysUser
    @Log(title = "指导巡逻-方格点位必到点接口-创建列表（根据方格巡逻任务ID）", businessType = BusinessType.OTHER)
    public ResponseResult<Integer> createListByFgxlrwId(String fgxlrwId) {
        return ResponseResult.success(tbZdxlFgdwBddxlrwJlService.createListByFgxlrwId(fgxlrwId));
    }

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

            TbZdxlFgdwBddxlrwJl baseEntity = tbZdxlFgdwBddxlrwJlService.selectById(dto.getId());
            if(ObjectUtils.isEmpty(baseEntity)){
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "打卡记录不存在，请退出页面重新进入");
            }

            //打卡时间
            Date dksj = new Date();

            //当前位置是否在方格内
            TbZdxlFgdwBddxlrw bddxlrw = tbZdxlFgdwBddxlrwService.selectById(baseEntity.getBddxlrwId());
            if(ObjectUtils.isEmpty(bddxlrw)){
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "必到点巡逻任务不存在，请退出页面重新进入");
            }

            TbZdxlFgdwVO fgdw = tbZdxlFgdwService.selectByBddId(bddxlrw.getBddId());
            if(ObjectUtils.isEmpty(bddxlrw)){
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "方格信息不存在，请退出页面重新进入");
            }

//            boolean inFgdw = TbZdxlFgxlrwUtils.isInGeometry(fgdw, dto.getDkJd(), dto.getDkWd());
//            if(!inFgdw){
//                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "您不在方格内，请查看您的定位信息");
//            }
            long jl = PositionUtil.getDistance(dto.getDkJd().doubleValue(), dto.getDkWd().doubleValue(),fgdw.getX1().doubleValue(),fgdw.getY1().doubleValue());
            if(jl > 100L){
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "您的位置在100米以外，无法打卡");
            }

            //校验上一次打卡情况
//            int lastSx = baseEntity.getDkSx() - 1;
//            if(lastSx > 0){
//                TbZdxlFgdwBddxlrwJl lastEntity = tbZdxlFgdwBddxlrwJlService.selectByBddxlrwIdAndDkSx(baseEntity.getBddxlrwId(), lastSx);
//                if(ObjectUtils.isNotEmpty(lastEntity) && ObjectUtils.isEmpty(lastEntity.getDkJsSj())){
//                    return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "请完成上一次打卡后，再进行本次打卡");
//                }
//            }

            //如果是打结束卡，需要进行以下验证
            UserInfo user = UserInfoManager.get();
            if(ObjectUtils.isNotEmpty(baseEntity.getDkKsSj())){
                //开始和结束是否是同一个人
//                if(!baseEntity.getDkrXm().equals(user.getUserName())){
//                    return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "您不是此记录的打卡人，不能进行打卡");
//                }
                TbZdxlFgdwBdd tbZdxlFgdwBdd = this.tbZdxlFgdwBddService.selectById(bddxlrw.getBddId());
                Integer jgsj = 10;
                if(Objects.nonNull(tbZdxlFgdwBdd)){
                    jgsj = tbZdxlFgdwBdd.getDkjgsj();
                }
                //是否待满10分钟
                if(dksj.getTime()-baseEntity.getDkKsSj().getTime() < jgsj){
                    return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "请在开始"+jgsj+"分后，再打卡结束");
                }
            }

            //打卡
            String resultId = tbZdxlFgdwBddxlrwJlService.clockIn(baseEntity, dto, user, dksj);
            if(StringUtils.isNotBlank(resultId)){
                return ResponseResult.success(resultId);
            }
            return ResponseResult.fail(MessageUtils.getSaveFailMsg());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(MessageUtils.getSaveServerErrorMsg());
        }
    }

    @ApiOperation(value = "警组打卡记录")
    @GetMapping("/getRwjlByXfbbId")
    @JwtSysUser
    @Log(title = "警组打卡记录", businessType = BusinessType.OTHER)
    public ResponseResult<List<TbZdxlFgdwBddxlrwJlVo>> getRwjlByXfbbId(String xfbbId) {
        return ResponseResult.success(tbZdxlFgdwBddxlrwJlService.getRwjlByXfbbId(xfbbId));
    }

    @ApiOperation(value = "警组打卡记录分页")
    @GetMapping("/getPageList")
    @JwtSysUser
    @Log(title = "警组打卡记录分页", businessType = BusinessType.OTHER)
    public ResponseResult<IPage<TbZdxlFgdwBddxlrwJlVo>> getPageList(BddxlrwJlQuery query) {
        return ResponseResult.success(tbZdxlFgdwBddxlrwJlService.getPageList(query));
    }

}
