package com.mosty.yjzl.controller;

import com.mosty.base.model.dto.yjzl.TbZdxlFgdwBddxlrwAppendDTO;
import com.mosty.base.model.dto.yjzl.TbZdxlFgdwBddxlrwHandleDTO;
import com.mosty.base.model.entity.yjzl.zddw.TbZdxlFgdwBddxlrw;
import com.mosty.base.model.entity.yjzl.zddw.TbZdxlFgxlrw;
import com.mosty.base.model.vo.yjzl.TbZdxlFgdwBddxlrwVO;
import com.mosty.base.utils.DatePlusUtils;
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.TbZdxlFgdwBddxlrwJlService;
import com.mosty.yjzl.service.TbZdxlFgdwBddxlrwService;
import com.mosty.yjzl.service.TbZdxlFgxlrwService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

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

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

    /**
     * 指导巡逻方格巡逻任务表Service
     */
    private final TbZdxlFgxlrwService tbZdxlFgxlrwService;

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

    /**
     * 查询未选中的必到点返回信息列表（根据方格巡逻任务ID）
     * @param fgxlrwId 方格巡逻任务ID
     * @return ResponseResult 返回信息列表
     */
    @ApiOperation(value = "查询未选中的必到点返回信息列表（根据方格巡逻任务ID）")
    @GetMapping("/selectUnSelectedVoListByFgxlrwId/{fgxlrwId}")
    @JwtSysUser
    @Log(title = "指导巡逻-方格点位必到点巡逻任务接口-查询未选中的必到点返回信息列表（根据方格巡逻任务ID）", businessType = BusinessType.OTHER)
    public ResponseResult<List<TbZdxlFgdwBddxlrwVO>> selectUnSelectedVoListByFgxlrwId(@PathVariable("fgxlrwId") String fgxlrwId) {
        return ResponseResult.success(tbZdxlFgdwBddxlrwService.selectUnSelectedVoListByFgxlrwId(fgxlrwId));
    }

    /**
     * 追加列表
     * @param dto 追加DTO对象
     * @param bindResult 校验对象
     * @return ResponseResult 操作条数
     */
    @ApiOperation(value = "追加列表")
    @PostMapping("/appendList")
    @JwtSysUser
    @Log(title = "指导巡逻-方格点位必到点巡逻任务接口-追加列表", businessType = BusinessType.INSERT)
    public ResponseResult<Integer> appendList(@RequestBody @Valid TbZdxlFgdwBddxlrwAppendDTO dto, BindingResult bindResult) {
        try {
            //基础信息校验
            String message = SpringValidUtils.getErrorsMsg(bindResult);
            if (StringUtils.isNotBlank(message)) {
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + message);
            }

            //校验方格巡逻任务信息
            TbZdxlFgxlrw fgxlrw = tbZdxlFgxlrwService.selectById(dto.getFgxlrwId());
            if(ObjectUtils.isEmpty(fgxlrw)){
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "方格巡逻任务信息不存在，请刷新页面后重新选择");
            }

            //校验当前日期与任务日期是否相等
            if(!DatePlusUtils.getSystemDateString().equals(DatePlusUtils.getDateString(fgxlrw.getRwRq()))){
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "任务日期不是今日，无法再追加必到点");
            }

            //查询已有的方格必到点巡逻任务信息
            Map<String, TbZdxlFgdwBddxlrw> baseMap = new HashMap<>();
            List<TbZdxlFgdwBddxlrw> baseList = tbZdxlFgdwBddxlrwService.selectListByFgxlrwId(dto.getFgxlrwId());
            if(CollectionUtils.isNotEmpty(baseList)){
                baseMap = baseList.stream().collect(Collectors.toMap(TbZdxlFgdwBddxlrw::getBddId, Function.identity(), (key1, key2) -> key2));
            }

            //校验追加的必到点是否已经生成任务
            Map<String, TbZdxlFgdwBddxlrw> finalBaseMap = baseMap;
            List<TbZdxlFgdwBddxlrwHandleDTO> appendHandleList = dto.getBddList().stream().filter(handleDto -> !finalBaseMap.containsKey(handleDto.getBddId())).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(appendHandleList)){
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "选择的必到点都已生成任务，无需再追加");
            }

            //保存
            List<TbZdxlFgdwBddxlrw> resultList = tbZdxlFgdwBddxlrwService.appendList(appendHandleList, dto.getFgxlrwId());
            if(CollectionUtils.isNotEmpty(resultList)){
                //创建记录信息
                tbZdxlFgdwBddxlrwJlService.createListByBddxlrwList(resultList);
                //返回结果
                return ResponseResult.success(appendHandleList.size());
            }
            return ResponseResult.fail(MessageUtils.getSaveFailMsg());
        } catch (Exception e) {
            return ResponseResult.fail(MessageUtils.getSaveServerErrorMsg());
        }
    }

}
