package com.mosty.yjzl.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.model.dto.qwzx.TbQwJlDto;
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.utils.UUIDGenerator;
import com.mosty.common.token.UserInfo;
import com.mosty.yjzl.mapper.TbZdxlFgdwBddMapper;
import com.mosty.yjzl.mapper.TbZdxlFgdwBddxlrwJlMapper;
import com.mosty.yjzl.mapper.TbZdxlFgdwBddxlrwMapper;
import com.mosty.yjzl.remote.TbQwzxAdaptRemoteService;
import com.mosty.yjzl.service.TbZdxlFgdwBddxlrwJlService;
import com.mosty.yjzl.service.TbZdxlFgdwBddxlrwService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhangzhao
 * @description 指导巡逻方格点位必到点巡逻任务记录表Service实现类
 * @modifier zhangzhao
 * @modifiedTime 2025/09/07 19:57
 * @since 2025/09/07 19:57
 */
@Service
@AllArgsConstructor
public class TbZdxlFgdwBddxlrwJlServiceImpl extends ServiceImpl<TbZdxlFgdwBddxlrwJlMapper, TbZdxlFgdwBddxlrwJl> implements TbZdxlFgdwBddxlrwJlService {

    /**
     * 指导巡逻方格点位必到点巡逻任务表Service
     */
    private final TbZdxlFgdwBddxlrwService tbZdxlFgdwBddxlrwService;
    private final TbQwzxAdaptRemoteService tbQwzxAdaptRemoteService;
    private final TbZdxlFgdwBddxlrwMapper tbZdxlFgdwBddxlrwMapper;
    private final TbZdxlFgdwBddMapper tbZdxlFgdwBddMapper;

    @Override
    public TbZdxlFgdwBddxlrwJl selectById(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        return this.baseMapper.selectOne(new QueryWrapper<TbZdxlFgdwBddxlrwJl>()
                .eq(TbZdxlFgdwBddxlrwJl.ID_FIELD, id)
                .eq("xt_sjzt", "1")
                .eq("xt_scbz", "0")
        );
    }

    @Override
    public TbZdxlFgdwBddxlrwJl selectByBddxlrwIdAndDkSx(String bddxlrwId, int dkSx) {
        if(StringUtils.isBlank(bddxlrwId)){
            return null;
        }
        return this.baseMapper.selectOne(new QueryWrapper<TbZdxlFgdwBddxlrwJl>()
                .eq(TbZdxlFgdwBddxlrwJl.BDDXLRW_ID_FIELD, bddxlrwId)
                .eq(TbZdxlFgdwBddxlrwJl.DK_SX_FIELD, dkSx)
                .eq("xt_sjzt", "1")
                .eq("xt_scbz", "0")
        );
    }

    @Override
    public List<TbZdxlFgdwBddxlrwJl> selectListByBddxlrwId(String bddxlrwId) {
        if(ObjectUtils.isEmpty(bddxlrwId)){
            return null;
        }

        return this.baseMapper.selectList(new QueryWrapper<TbZdxlFgdwBddxlrwJl>()
                .eq(TbZdxlFgdwBddxlrwJl.BDDXLRW_ID_FIELD, bddxlrwId)
                .eq("xt_sjzt", "1")
                .eq("xt_scbz", "0")
                .orderByAsc(TbZdxlFgdwBddxlrwJl.DK_SX_FIELD)
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int createListByFgxlrwId(String fgxlrwId) {
        if(StringUtils.isBlank(fgxlrwId)){
            return -1;
        }

        List<TbZdxlFgdwBddxlrw> bddxlrwList = tbZdxlFgdwBddxlrwService.selectListByFgxlrwId(fgxlrwId);
        if(CollectionUtils.isEmpty(bddxlrwList)){
            return -2;
        }

        return this.createListByBddxlrwList(bddxlrwList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int createListByBddxlrwList(List<TbZdxlFgdwBddxlrw> bddxlrwList) {
        if(CollectionUtils.isEmpty(bddxlrwList)){
            return -1;
        }

        //循环组装数据
        List<TbZdxlFgdwBddxlrwJl> saveList = new ArrayList<>();
        for(TbZdxlFgdwBddxlrw bbdxlrw : bddxlrwList){
            if(ObjectUtils.isEmpty(bbdxlrw.getXlghDkcs())){
                continue;
            }

            for(int i = 1 ; i <= bbdxlrw.getXlghDkcs() ; i++){
                TbZdxlFgdwBddxlrwJl entity = new TbZdxlFgdwBddxlrwJl();
                entity.setId(UUIDGenerator.getUUID());
                entity.setBddxlrwId(bbdxlrw.getId());
                entity.setDkSx(i);
                entity.setXtSjly("1");
                saveList.add(entity);
            }
        }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String clockIn(TbZdxlFgdwBddxlrwJl baseEntity, TbZdxlFgdwBddxlrwJlClockInDTO dto, UserInfo user, Date dksj) {
        if(ObjectUtils.isEmpty(baseEntity) || ObjectUtils.isEmpty(dto) || ObjectUtils.isEmpty(user)){
            return null;
        }

        boolean start = ObjectUtils.isEmpty(baseEntity.getDkKsSj());
        if(start){
            //开始
            baseEntity.setDkKsSj(dksj);
            baseEntity.setDkKsFj(dto.getDkFj());
            baseEntity.setDkKsJd(dto.getDkJd());
            baseEntity.setDkKsWd(dto.getDkWd());
            baseEntity.setDkrXm(user.getUserName());
            baseEntity.setSfzh(user.getIdEntityCard());
        }else{
            //结束
            baseEntity.setDkJsSj(dksj);
            baseEntity.setDkJsFj(dto.getDkFj());
            baseEntity.setDkJsJd(dto.getDkJd());
            baseEntity.setDkJsWd(dto.getDkWd());
        }

        int resultInt = this.baseMapper.updateById(baseEntity);
        if(resultInt > 0){
            //保存成功后，同步必到点状态
            tbZdxlFgdwBddxlrwService.clockInByJl(baseEntity, start);
            //返回
            return baseEntity.getId();
        }
        return null;
    }

    @Override
    public List<TbZdxlFgdwBddxlrwJlVo> getRwjlByXfbbId(String xfbbId) {
        List<TbQwJlDto> jlDtos = this.tbQwzxAdaptRemoteService.getJlxxByBbid(xfbbId);
        List<String> sfzhList = jlDtos.stream().map(TbQwJlDto::getSfzh).collect(Collectors.toList());
        List<TbZdxlFgdwBddxlrwJl> list = this.baseMapper.selectList(
                new LambdaQueryWrapper<TbZdxlFgdwBddxlrwJl>()
                        .in(TbZdxlFgdwBddxlrwJl::getSfzh,sfzhList)
                        .orderByDesc(TbZdxlFgdwBddxlrwJl::getXtCjsj)
                        .last("limit 100")
        );
        List<TbZdxlFgdwBddxlrwJlVo> vos = new ArrayList<>();
        list.forEach(xlrwjl -> {
            TbZdxlFgdwBddxlrwJlVo vo = new TbZdxlFgdwBddxlrwJlVo();
            BeanUtils.copyProperties(xlrwjl,vo);
            TbZdxlFgdwBddxlrw tbZdxlFgdwBddxlrw = this.tbZdxlFgdwBddxlrwMapper.selectById(xlrwjl.getBddxlrwId());
            if(Objects.nonNull(tbZdxlFgdwBddxlrw)){
                TbZdxlFgdwBdd tbZdxlFgdwBdd = this.tbZdxlFgdwBddMapper.selectById(tbZdxlFgdwBddxlrw.getBddId());
                if(Objects.nonNull(tbZdxlFgdwBdd)){
                    vo.setBddMc(tbZdxlFgdwBdd.getBddMc());
                    vo.setBddDz(tbZdxlFgdwBdd.getBddDz());
                }
            }
            vos.add(vo);
        });
        return vos;
    }

    @Override
    public IPage<TbZdxlFgdwBddxlrwJlVo> getPageList(BddxlrwJlQuery query) {
        if(StringUtils.isNotEmpty(query.getSsbmdm())){
            query.setSsbmdm(query.getSsbmdm().replaceAll("(00)+$", ""));
        }
        IPage<TbZdxlFgdwBddxlrwJl> page = this.baseMapper.selectPage(
                new Page<>(query.getPageCurrent(),query.getPageSize()),
                new LambdaQueryWrapper<TbZdxlFgdwBddxlrwJl>()
                        .like(StringUtils.isNotEmpty(query.getSsbmdm()),TbZdxlFgdwBddxlrwJl::getSsbmdm,query.getSsbmdm())
                        .like(StringUtils.isNotEmpty(query.getDkrXm()),TbZdxlFgdwBddxlrwJl::getDkrXm,query.getDkrXm())
                        .between(StringUtils.isNotEmpty(query.getKssj()),TbZdxlFgdwBddxlrwJl::getDkKsSj,query.getKssj(),query.getJssj())
                        .orderByDesc(TbZdxlFgdwBddxlrwJl::getXtCjsj)
        );
        List<TbZdxlFgdwBddxlrwJlVo> vos = new ArrayList<>();
        if(!CollectionUtils.isEmpty(page.getRecords())){
            page.getRecords().forEach(xlwjl -> {
                TbZdxlFgdwBddxlrwJlVo vo = new TbZdxlFgdwBddxlrwJlVo();
                BeanUtils.copyProperties(xlwjl,vo);
                TbZdxlFgdwBddxlrw tbZdxlFgdwBddxlrw = this.tbZdxlFgdwBddxlrwMapper.selectById(xlwjl.getBddxlrwId());
                if(Objects.nonNull(tbZdxlFgdwBddxlrw)){
                    TbZdxlFgdwBdd tbZdxlFgdwBdd = this.tbZdxlFgdwBddMapper.selectById(tbZdxlFgdwBddxlrw.getBddId());
                    if(Objects.nonNull(tbZdxlFgdwBdd)){
                        vo.setBddMc(tbZdxlFgdwBdd.getBddMc());
                        vo.setBddDz(tbZdxlFgdwBdd.getBddDz());
                    }
                }
                vos.add(vo);
            });
        }
        IPage<TbZdxlFgdwBddxlrwJlVo>  voIPage = new Page<>(query.getPageCurrent(),query.getPageSize());
        voIPage.setRecords(vos);
        voIPage.setTotal(page.getTotal());
        return voIPage;
    }


}
