package com.mosty.yjzl.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.model.dto.yjzl.TbZdxlFgdwBddxlrwHandleDTO;
import com.mosty.base.model.entity.yjzl.zddw.*;
import com.mosty.base.model.vo.yjzl.TbZdxlFgdwBddxlrwVO;
import com.mosty.base.utils.Constant;
import com.mosty.base.utils.MathUtils;
import com.mosty.base.utils.UUIDGenerator;
import com.mosty.yjzl.mapper.TbZdxlFgdwBddxlrwMapper;
import com.mosty.yjzl.service.TbZdxlFgdwBddService;
import com.mosty.yjzl.service.TbZdxlFgdwBddxlrwService;
import com.mosty.yjzl.service.TbZdxlFgmrpzService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhangzhao
 * @description 指导巡逻方格点位必到点巡逻任务表Service实现类
 * @modifier zhangzhao
 * @modifiedTime 2025/09/06 19:49
 * @since 2025/09/06 19:49
 */
@Service
@AllArgsConstructor
public class TbZdxlFgdwBddxlrwServiceImpl extends ServiceImpl<TbZdxlFgdwBddxlrwMapper, TbZdxlFgdwBddxlrw> implements TbZdxlFgdwBddxlrwService {

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

    /**
     * 指导巡逻方格默认配置表Service
     */
    private final TbZdxlFgmrpzService tbZdxlFgmrpzService;

    @Override
    public TbZdxlFgdwBddxlrw selectById(String id) {
        if(ObjectUtils.isEmpty(id)){
            return null;
        }

        //查询已配置的任务数据
        return this.baseMapper.selectOne(new QueryWrapper<TbZdxlFgdwBddxlrw>()
                .eq(TbZdxlFgdwBddxlrw.ID_FIELD, id)
                .eq("xt_sjzt", "1")
                .eq("xt_scbz", "0")
        );
    }

    @Override
    public List<TbZdxlFgdwBddxlrw> selectListByFgxlrwId(String fgxlrwId) {
        if(ObjectUtils.isEmpty(fgxlrwId)){
            return null;
        }

        //查询已配置的任务数据
        return this.baseMapper.selectList(new QueryWrapper<TbZdxlFgdwBddxlrw>()
                .eq(TbZdxlFgdwBddxlrw.FGXLRW_ID_FIELD, fgxlrwId)
                .eq("xt_sjzt", "1")
                .eq("xt_scbz", "0")
        );
    }

    @Override
    public List<TbZdxlFgdwBddxlrwVO> selectVoListByYxfFgxlrwId(String fgxlrwId) {
        if(ObjectUtils.isEmpty(fgxlrwId)){
            return null;
        }

        //查询已配置的任务数据
        List<TbZdxlFgdwBddxlrw> entityList = this.baseMapper.selectList(new QueryWrapper<TbZdxlFgdwBddxlrw>()
                .eq(TbZdxlFgdwBddxlrw.FGXLRW_ID_FIELD, fgxlrwId)
                .eq("xt_sjzt", "1")
                .eq("xt_scbz", "0")
        );

        //组装并返回数据
        return this.buildAllInfoList(entityList, null, fgxlrwId);
    }

    @Override
    public List<TbZdxlFgdwBddxlrwVO> selectVoListByFgxlrwId(String fgxlrwId) {
        if(ObjectUtils.isEmpty(fgxlrwId)){
            return null;
        }

        //查询已配置的任务数据
        List<TbZdxlFgdwBddxlrw> entityList = this.baseMapper.selectList(new QueryWrapper<TbZdxlFgdwBddxlrw>()
                .eq(TbZdxlFgdwBddxlrw.FGXLRW_ID_FIELD, fgxlrwId)
                .eq("xt_sjzt", "1")
                .eq("xt_scbz", "0")
        );
        //查询所有必到点
        List<TbZdxlFgdwBdd> bddList = tbZdxlFgdwBddService.selectListByFgxlrwId(fgxlrwId);

        //组装并返回数据
        return this.buildAllInfoList(entityList, bddList, fgxlrwId);
    }

    @Override
    public List<TbZdxlFgdwBddxlrwVO> selectUnSelectedVoListByFgxlrwId(String fgxlrwId) {
        //查询已配置的任务数据
        List<TbZdxlFgdwBddxlrw> entityList = this.baseMapper.selectList(new QueryWrapper<TbZdxlFgdwBddxlrw>()
                .eq(TbZdxlFgdwBddxlrw.FGXLRW_ID_FIELD, fgxlrwId)
                .eq("xt_sjzt", "1")
                .eq("xt_scbz", "0")
        );
        //查询所有必到点
        List<TbZdxlFgdwBdd> bddList = tbZdxlFgdwBddService.selectListByFgxlrwId(fgxlrwId);

        //筛选出未选择的必到点
        Map<String, TbZdxlFgdwBddxlrw> entityMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(entityList)){
            entityMap = entityList.stream().collect(Collectors.toMap(TbZdxlFgdwBddxlrw::getBddId, Function.identity(), (key1, key2) -> key2));
        }
        List<TbZdxlFgdwBdd> unSelectedBddList;
        if(MapUtils.isEmpty(entityMap)){
            unSelectedBddList = bddList;
        }else{
            Map<String, TbZdxlFgdwBddxlrw> finalEntityMap = entityMap;
            unSelectedBddList = bddList.stream().filter(bdd -> !finalEntityMap.containsKey(bdd.getId())).collect(Collectors.toList());
        }

        return this.buildAllInfoList(null, unSelectedBddList, fgxlrwId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int handleList(List<TbZdxlFgdwBddxlrwHandleDTO> handleList, String fgxlrwId) {
        if(CollectionUtils.isEmpty(handleList)){
            return -1;
        }

        //筛选数据
        List<TbZdxlFgdwBddxlrwHandleDTO> saveDtoList = handleList.stream().filter(dto -> ObjectUtils.isEmpty(dto.getId())).collect(Collectors.toList());
        List<TbZdxlFgdwBddxlrwHandleDTO> updateDtoList = handleList.stream().filter(dto -> ObjectUtils.isNotEmpty(dto.getId())).collect(Collectors.toList());
        List<TbZdxlFgdwBddxlrw> saveList = new ArrayList<>(), updateList = new ArrayList<>();
        Map<String, TbZdxlFgdwBddxlrwHandleDTO> updateIdMap;
        List<String> cancelIdList = new ArrayList<>();

        //组装保存列表
        if(CollectionUtils.isNotEmpty(saveDtoList)){
            for(TbZdxlFgdwBddxlrwHandleDTO dto : saveDtoList){
                TbZdxlFgdwBddxlrw entity = BeanUtil.copyProperties(dto, TbZdxlFgdwBddxlrw.class);
                //组装参数
                entity.setId(UUIDGenerator.getUUID());
                entity.setXtSjly("1");
                saveList.add(entity);
            }
        }

        //组装修改列表
        if(CollectionUtils.isNotEmpty(updateDtoList)){
            for(TbZdxlFgdwBddxlrwHandleDTO dto : saveDtoList){
                TbZdxlFgdwBddxlrw entity = new TbZdxlFgdwBddxlrw();
                entity.setId(dto.getId());
                entity.setXlghDkcs(dto.getXlghDkcs());
                updateList.add(entity);
            }
            //组装删除列表
            List<TbZdxlFgdwBddxlrw> baseList = this.selectListByFgxlrwId(fgxlrwId);
            if(CollectionUtils.isNotEmpty(baseList)){
                updateIdMap = updateDtoList.stream().collect(Collectors.toMap(TbZdxlFgdwBddxlrwHandleDTO::getId, Function.identity(), (key1, key2) -> key2));
                Map<String, TbZdxlFgdwBddxlrwHandleDTO> finalUpdateIdMap = updateIdMap;
                cancelIdList = baseList.stream().map(TbZdxlFgdwBddxlrw::getId).filter(id -> !finalUpdateIdMap.containsKey(id)).collect(Collectors.toList());
            }
        }

        //保存、修改或删除信息
        int resultInt = 0;
        if(CollectionUtils.isNotEmpty(saveList)){
            boolean success = this.saveBatch(saveList);
            if(success){
                resultInt += saveList.size();
            }
        }
        if(CollectionUtils.isNotEmpty(updateList)){
            boolean success = this.updateBatchById(updateList);
            if(success){
                resultInt += updateList.size();
            }
        }
        if(CollectionUtils.isNotEmpty(cancelIdList)){
            resultInt += this.baseMapper.deleteBatchIds(cancelIdList);
        }
        return resultInt;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<TbZdxlFgdwBddxlrw> handleListByFgxlrwList(List<TbZdxlFgxlrw> fgxlrwList) {
        if(CollectionUtils.isEmpty(fgxlrwList)){
            return null;
        }

        //逻辑流程由原来的所有必到点都需要下发任务，改为用户选择的点位下发记录
        List<TbZdxlFgdwBddxlrw> resultList = new ArrayList<>();
        for(TbZdxlFgxlrw fgxlrw : fgxlrwList){
            //查询是否已经保存了必到点的巡逻任务，如果已经保存，则不做处理，直接生成记录即可，
            List<TbZdxlFgdwBddxlrw> baseList = this.selectListByFgxlrwId(fgxlrw.getId());
            if(CollectionUtils.isEmpty(baseList)){
                //如果没有保存，则需要根据必到点生成必到点巡逻任务
                baseList = new ArrayList<>();
                List<TbZdxlFgdwBdd> bddList = tbZdxlFgdwBddService.selectListByFgxlrwId(fgxlrw.getId());
                List<TbZdxlFgdwBddxlrwVO> bbdXlrwVoList = this.buildAllInfoListByBddList(bddList, fgxlrw.getId(),true);
                if(CollectionUtils.isNotEmpty(bbdXlrwVoList)){
                    for(TbZdxlFgdwBddxlrwVO vo : bbdXlrwVoList){
                        TbZdxlFgdwBddxlrw saveEntity = BeanUtil.copyProperties(vo, TbZdxlFgdwBddxlrw.class);
                        saveEntity.setId(UUIDGenerator.getUUID());
                        saveEntity.setXtSjly("1");
                        baseList.add(saveEntity);
                    }
                    this.saveBatch(baseList);
                }
            }
            resultList.addAll(baseList);
        }

        return resultList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<TbZdxlFgdwBddxlrw> appendList(List<TbZdxlFgdwBddxlrwHandleDTO> appendHandleList, String fgxlrwId) {
        if(CollectionUtils.isEmpty(appendHandleList) || StringUtils.isBlank(fgxlrwId)){
            return null;
        }

        List<TbZdxlFgdwBddxlrw> saveList = new ArrayList<>();
        for(TbZdxlFgdwBddxlrwHandleDTO dto : appendHandleList){
            TbZdxlFgdwBddxlrw entity = BeanUtil.copyProperties(dto, TbZdxlFgdwBddxlrw.class);
            //组装参数
            entity.setId(UUIDGenerator.getUUID());
            entity.setXtSjly("1");
            if(StringUtils.isBlank(entity.getFgxlrwId())){
                entity.setFgxlrwId(fgxlrwId);
            }
            saveList.add(entity);
        }

        boolean success = this.saveBatch(saveList);
        if(success){
            return saveList;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String clockInByJl(TbZdxlFgdwBddxlrwJl jl, boolean start) {
        if(ObjectUtils.isEmpty(jl) || ObjectUtils.isEmpty(jl.getBddxlrwId())){
            return null;
        }

        TbZdxlFgdwBddxlrw baseEntity = this.selectById(jl.getBddxlrwId());
        if(ObjectUtils.isEmpty(baseEntity)){
            return null;
        }

        TbZdxlFgdwBddxlrw updateEntity = new TbZdxlFgdwBddxlrw();
        updateEntity.setId(baseEntity.getId());

        //修改开始状态
        if(Constant.DICT_ITEM_D_BZ_SF_NO.equals(baseEntity.getSfKs())){
            updateEntity.setSfKs(Constant.DICT_ITEM_D_BZ_SF_YES);
        }

        //判断是否修改结束状态
        if(baseEntity.getXlghDkcs().equals(jl.getDkSx()) && !start){
            //规划打卡次数与记录打卡相同，则表示是最后一次打卡，如果是结束打卡，则可以将状态改为结束
            updateEntity.setSfJs(Constant.DICT_ITEM_D_BZ_SF_YES);
        }

        //结束打卡，增加次数
        if(!start){
            int newSjDkCs = baseEntity.getXlsjDkcs() + 1;
            if(newSjDkCs > baseEntity.getXlghDkcs()){
                newSjDkCs = baseEntity.getXlghDkcs();
            }
            updateEntity.setXlsjDkcs(newSjDkCs);
        }

        int resultInt = this.baseMapper.updateById(updateEntity);
        if(resultInt > 0){
            return baseEntity.getId();
        }
        return null;
    }


    /**
     * 组装全量信息列表（根据实体列表、必到点列表）
     * @param entityList 实体列表
     * @param bddList 必到点列表
     * @param fgxlrwId 方格巡逻任务ID
     * @return 全量信息列表
     */
    private List<TbZdxlFgdwBddxlrwVO> buildAllInfoList(List<TbZdxlFgdwBddxlrw> entityList, List<TbZdxlFgdwBdd> bddList, String fgxlrwId){
        if(CollectionUtils.isEmpty(entityList) && CollectionUtils.isEmpty(bddList)){
            return null;
        }

        boolean hasEntityList = CollectionUtils.isNotEmpty(entityList);

        //组装实体数据
        Map<String, TbZdxlFgdwBddxlrw> entityMap = new HashMap<>();
        List<TbZdxlFgdwBddxlrwVO> allInfoVoList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(entityList)){
            List<TbZdxlFgdwBddxlrwVO> entityAllInfoList = this.buildAllInfoListByEntityList(entityList);
            if(CollectionUtils.isNotEmpty(entityAllInfoList)){
                allInfoVoList.addAll(entityAllInfoList);
            }
            entityMap = entityList.stream().collect(Collectors.toMap(TbZdxlFgdwBddxlrw::getBddId, Function.identity(), (key1, key2) -> key2));
        }

        //组装必到点数据
        if(CollectionUtils.isNotEmpty(bddList)){
            Map<String, TbZdxlFgdwBddxlrw> finalEntityMap = entityMap;
            List<TbZdxlFgdwBdd> bddNotCreateList = bddList.stream().filter(bdd -> !finalEntityMap.containsKey(bdd.getId())).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(bddNotCreateList)){
                List<TbZdxlFgdwBddxlrwVO> bddAllInfoList = this.buildAllInfoListByBddList(bddNotCreateList, fgxlrwId, hasEntityList);
                if(CollectionUtils.isNotEmpty(bddAllInfoList)){
                    allInfoVoList.addAll(bddAllInfoList);
                }
            }
        }

        return allInfoVoList;
    }

    /**
     * 组装全量信息列表（根据必到点列表）
     * @param bddList 必到点列表
     * @param fgxlrwId 方格巡逻任务ID
     * @return 全量信息列表
     */
    private List<TbZdxlFgdwBddxlrwVO> buildAllInfoListByBddList(List<TbZdxlFgdwBdd> bddList, String fgxlrwId, boolean hasEntityList){
        if(CollectionUtils.isEmpty(bddList) || StringUtils.isBlank(fgxlrwId)){
            return null;
        }

        TbZdxlFgmrpz mrpz = tbZdxlFgmrpzService.selectDefault();
        if(ObjectUtils.isEmpty(mrpz)){
            return null;
        }

        List<TbZdxlFgdwBddxlrwVO> allInfoVOList = new ArrayList<>();
        for(TbZdxlFgdwBdd bdd : bddList){
            TbZdxlFgdwBddxlrwVO vo = new TbZdxlFgdwBddxlrwVO();

            vo.setBddMc(bdd.getBddMc());
            if(Objects.nonNull(bdd.getDkjgsj())){
                vo.setDkjgsj(bdd.getDkjgsj());
            }else{
                vo.setDkjgsj(10);
            }
            vo.setBddId(bdd.getId());
            vo.setFgxlrwId(fgxlrwId);
            vo.setXlghDkcs(mrpz.getFgDkcs());
            vo.setXlsjDkcs(0);
            vo.setSfKs(Constant.DICT_ITEM_D_BZ_SF_NO);
            vo.setSfJs(Constant.DICT_ITEM_D_BZ_SF_NO);
            //如果此方格巡逻任务没有生成必到点生成巡逻任务，说明是刚导入，则默认设置为勾选
            vo.setSelected(!hasEntityList);

            allInfoVOList.add(vo);
        }

        return allInfoVOList;
    }

    /**
     * 组装全量信息列表（根据实体列表）
     * @param entityList 实体列表
     * @return 全量信息列表
     */
    private List<TbZdxlFgdwBddxlrwVO> buildAllInfoListByEntityList(List<TbZdxlFgdwBddxlrw> entityList){
        List<TbZdxlFgdwBddxlrwVO> allInfoVOList = new ArrayList<>();
        //组装返回数据
        for(TbZdxlFgdwBddxlrw entity : entityList){
            TbZdxlFgdwBddxlrwVO resultVO = this.buildAllInfoByEntity(entity);
            allInfoVOList.add(resultVO);
        }
        //返回列表
        if(CollectionUtils.isEmpty(allInfoVOList)){
            return null;
        }
        return allInfoVOList;
    }

    /**
     * 组装全量信息（根据实体信息）
     * @param entity 实体信息
     * @return 全量信息
     */
    private TbZdxlFgdwBddxlrwVO buildAllInfoByEntity(TbZdxlFgdwBddxlrw entity){
        TbZdxlFgdwBddxlrwVO resultVO = BeanUtil.copyProperties(entity, TbZdxlFgdwBddxlrwVO.class);

        //组装必到点信息
        if(ObjectUtils.isNotEmpty(resultVO.getBddId())){
            TbZdxlFgdwBdd bdd = tbZdxlFgdwBddService.selectById(resultVO.getBddId());
            if(ObjectUtils.isNotEmpty(bdd)){
                resultVO.setBddMc(bdd.getBddMc());
                resultVO.setDkjgsj(bdd.getDkjgsj());
            }
        }

        //实体信息是默认需要选中的
        resultVO.setSelected(true);

        //计算进度
        resultVO.setBddProgress(MathUtils.percentage(entity.getXlsjDkcs(), entity.getXlghDkcs()));

        return resultVO;
    }

}
