package com.mosty.yjzl.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.yjzl.TbZdyFgrwDkDto;
import com.mosty.base.model.dto.yjzl.TbZdyFgrwDto;
import com.mosty.base.model.entity.qwzx.TbQwXfbb;
import com.mosty.base.model.entity.yjzl.zddw.*;
import com.mosty.base.model.query.yjzl.TbZdyFgrwQuery;
import com.mosty.base.model.query.yjzl.TbZdyFgrwlqQuery;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.yjzl.TbZdxlFgdwVO;
import com.mosty.base.model.vo.yjzl.TbZdyFgrwVO;
import com.mosty.base.utils.*;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.yjzl.mapper.*;
import com.mosty.yjzl.remote.TbBaseAdaptRemoteService;
import com.mosty.yjzl.remote.TbQwzxAdaptRemoteService;
import com.mosty.yjzl.service.TbZdyFgrwService;
import lombok.AllArgsConstructor;
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.util.CollectionUtils;

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

@Service
@AllArgsConstructor
public class TbZdyFgrwServiceImpl extends ServiceImpl<TbZdyFgrwMapper, TbZdyFgrw> implements TbZdyFgrwService {

    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
    private final TbZdyFgrwlqMapper tbZdyFgrwlqMapper;
    private final TbZdyFgbxdMapper tbZdyFgbxdMapper;
    private final TbZdxlFgdwMapper tbZdxlFgdwMapper;
    private final TbZdyFgrwlqdkMapper tbZdyFgrwlqdkMapper;
    private final TbQwzxAdaptRemoteService tbQwzxAdaptRemoteService;
    @Override
    public Boolean addTbZdyrw(TbZdyFgrwDto dto) {
        UserInfo user = UserInfoManager.get();
        TbZdyFgrw fgrw = new TbZdyFgrw();
        BeanUtils.copyProperties(dto,fgrw);
        fgrw.setId(UUIDGenerator.getUUID());
        fgrw.setFgrwzt("01");
        if(Objects.isNull(dto.getXfrq())){
            fgrw.setXfrq(new Date());
        }
        TbZdxlFgdw tbZdxlFgdw = this.tbZdxlFgdwMapper.selectById(dto.getFgId());
        if(Objects.nonNull(tbZdxlFgdw)){
            fgrw.setFgmc(tbZdxlFgdw.getMc1());
            fgrw.setXfbm(tbZdxlFgdw.getSsbm());
            fgrw.setXfbmdm(tbZdxlFgdw.getSsbmdm());
        }
        if(StringUtils.isEmpty(dto.getSsbmdm())){
            dto.setSsbmdm(user.getDeptCode());
        }
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(dto.getSsbmdm());
        if(Objects.nonNull(dept)){
            fgrw.setSsbm(dept.getDeptname());
            fgrw.setSsbmdm(dept.getDeptcode());
            fgrw.setSsxgajdm(dept.getFxjcode());
            fgrw.setSsxgaj(dept.getFxjname());
            fgrw.setSssgaj(dept.getDszname());
            fgrw.setSssgajdm(dept.getDszcode());
        }
        this.baseMapper.insert(fgrw);
        if(!CollectionUtils.isEmpty(dto.getDtoList())){
            dto.getDtoList().forEach(tbZdyFgbxdDto -> {
                TbZdyFgbxd bxd = new TbZdyFgbxd();
                BeanUtils.copyProperties(tbZdyFgbxdDto,bxd);
                bxd.setId(UUIDGenerator.getUUID());
                bxd.setFgrwid(fgrw.getId());
                this.tbZdyFgbxdMapper.insert(bxd);
            });
        }
        return true;
    }

    @Override
    public Boolean editTbZdyrw(TbZdyFgrwDto dto) {
        UserInfo user = UserInfoManager.get();
        TbZdyFgrw fgrw = new TbZdyFgrw();
        BeanUtils.copyProperties(dto,fgrw);
        if(Objects.isNull(dto.getXfrq())){
            fgrw.setXfrq(new Date());
        }
        TbZdxlFgdw tbZdxlFgdw = this.tbZdxlFgdwMapper.selectById(dto.getFgId());
        if(Objects.nonNull(tbZdxlFgdw)){
            fgrw.setFgmc(tbZdxlFgdw.getMc1());
            fgrw.setXfbm(tbZdxlFgdw.getSsbm());
            fgrw.setXfbmdm(tbZdxlFgdw.getSsbmdm());
        }
        if(StringUtils.isEmpty(dto.getSsbmdm())){
            dto.setSsbmdm(user.getDeptCode());
        }
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(dto.getSsbmdm());
        if(Objects.nonNull(dept)){
            fgrw.setSsbm(dept.getDeptname());
            fgrw.setSsbmdm(dept.getDeptcode());
            fgrw.setSsxgajdm(dept.getFxjcode());
            fgrw.setSsxgaj(dept.getFxjname());
            fgrw.setSssgaj(dept.getDszname());
            fgrw.setSssgajdm(dept.getDszcode());
        }
        this.baseMapper.updateById(fgrw);
        this.tbZdyFgbxdMapper.delete(
                new LambdaQueryWrapper<TbZdyFgbxd>()
                        .eq(TbZdyFgbxd::getFgrwid,fgrw.getId())
        );
        if(!CollectionUtils.isEmpty(dto.getDtoList())){
            dto.getDtoList().forEach(tbZdyFgbxdDto -> {
                TbZdyFgbxd bxd = new TbZdyFgbxd();
                BeanUtils.copyProperties(tbZdyFgbxdDto,bxd);
                bxd.setId(UUIDGenerator.getUUID());
                bxd.setFgrwid(fgrw.getId());
                this.tbZdyFgbxdMapper.insert(bxd);
            });
        }
        return true;
    }

    @Override
    public Boolean delTbZdyrw(TbZdyFgrwDto dto) {
        return this.baseMapper.deleteById(dto.getId()) > 0;
    }

    @Override
    public IPage<TbZdyFgrwVO> selectList(TbZdyFgrwQuery query) {
        UserInfo userInfo = UserInfoManager.get();
        query.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(query.getSsbmdm(), null));
        IPage<TbZdyFgrw> page = this.baseMapper.selectPage(
                new Page<>(query.getPageCurrent(),query.getPageSize()),
                new LambdaQueryWrapper<TbZdyFgrw>()
                        .like(StringUtils.isNotEmpty(query.getFgRwmc()),TbZdyFgrw::getFgRwmc,query.getFgRwmc())
                        .likeRight(StringUtils.isNotEmpty(query.getSsbmdm()),TbZdyFgrw::getSsbmdm,query.getSsbmdm())
                        .eq(StringUtils.isNotEmpty(query.getXfbmdm()),TbZdyFgrw::getXfbmdm,query.getXfbmdm())
                        .eq(StringUtils.isNotEmpty(query.getFgrwzt()),TbZdyFgrw::getFgrwzt,query.getFgrwzt())
                        .orderByDesc(TbZdyFgrw::getXfrq)
        );
        List<TbZdyFgrwVO> voList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(page.getRecords())){
            page.getRecords().forEach(tbZdyFgrw -> {
                TbZdyFgrwlq rwlq = this.tbZdyFgrwlqMapper.selectOne(
                        new LambdaQueryWrapper<TbZdyFgrwlq>()
                                .eq(TbZdyFgrwlq::getFgrwid,tbZdyFgrw.getId())
                                .eq(TbZdyFgrwlq::getFgrwlqrid,userInfo.getUserId())
                                .last(" limit 1 ")
                );
                TbZdyFgrwVO vo = new TbZdyFgrwVO();
                BeanUtils.copyProperties(tbZdyFgrw,vo);
                vo.setFgrwzt(tbZdyFgrw.getFgrwzt());
                if(Objects.nonNull(rwlq)){
                    vo.setFgrwlqr(rwlq.getFgrwlqr());
                    vo.setFgrwlqrid(rwlq.getFgrwlqrid());
                    vo.setFgrwlqrsfzh(rwlq.getFgrwlqrsfzh());
                    vo.setFgrwzt(rwlq.getFgrwzt());
                }
                voList.add(vo);
            });
        }
        IPage<TbZdyFgrwVO> pageVo = new Page<>(page.getCurrent(),page.getSize());
        pageVo.setTotal(page.getTotal());
        pageVo.setRecords(voList);
        return pageVo;
    }

    @Override
    public IPage<TbZdyFgrwVO> selectListApp(TbZdyFgrwQuery query) {
        UserInfo userInfo = UserInfoManager.get();
        query.setFgrwlqrid(userInfo.getUserId().toString());
        query.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(query.getSsbmdm(), null));
        //今日已领取任务
//        List<TbZdyFgrwlq> mylqs = this.tbZdyFgrwlqMapper.selectList(
//                new LambdaQueryWrapper<TbZdyFgrwlq>()
//                        .eq(TbZdyFgrwlq::getFgrwlqrid,userInfo.getUserId().toString())
//                        .eq(TbZdyFgrwlq::getRwlqrq,DateUtils.getNowDate())
//        );
//        List<String> ids = mylqs.stream().map(TbZdyFgrwlq::getFgrwid).collect(Collectors.toList());
        //今日待领取任务
        IPage<TbZdyFgrw> page = this.baseMapper.selectPage(
                new Page<>(query.getPageCurrent(),query.getPageSize()),
                new LambdaQueryWrapper<TbZdyFgrw>()
                        .like(StringUtils.isNotEmpty(query.getFgRwmc()),TbZdyFgrw::getFgRwmc,query.getFgRwmc())
                        .likeRight(StringUtils.isNotEmpty(query.getSsbmdm()),TbZdyFgrw::getSsbmdm,query.getSsbmdm())
                        .eq(StringUtils.isNotEmpty(query.getXfbmdm()),TbZdyFgrw::getXfbmdm,query.getXfbmdm())
                        .eq(TbZdyFgrw::getXfrq,DateUtils.getNowDate())
                        .eq(TbZdyFgrw::getFgrwzt,"01")
//                        .notIn(!CollectionUtils.isEmpty(ids),TbZdyFgrw::getId,ids)
                        .orderByDesc(TbZdyFgrw::getXfrq)
        );
        //历史任务（自己已领取任务）
        if("02".equals(query.getAppRwlx())){
            IPage<TbZdyFgrw> pageDto = PageUtils.buildPage(query.getPageSize(),query.getPageCurrent());
            page = this.baseMapper.getLqfgrw(pageDto,query);
        }
        List<TbZdyFgrwVO> voList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(page.getRecords())){
            page.getRecords().forEach(tbZdyFgrw -> {
                TbZdyFgrwlq rwlq = this.tbZdyFgrwlqMapper.selectOne(
                        new LambdaQueryWrapper<TbZdyFgrwlq>()
                                .eq(TbZdyFgrwlq::getFgrwid,tbZdyFgrw.getId())
                                .eq(TbZdyFgrwlq::getFgrwlqrid,userInfo.getUserId())
                                .last(" limit 1 ")
                );
                TbZdyFgrwVO vo = new TbZdyFgrwVO();
                BeanUtils.copyProperties(tbZdyFgrw,vo);
                vo.setFgrwzt("01");
                if(Objects.nonNull(rwlq)){
                    vo.setFgrwlqr(rwlq.getFgrwlqr());
                    vo.setFgrwlqrid(rwlq.getFgrwlqrid());
                    vo.setFgrwlqrsfzh(rwlq.getFgrwlqrsfzh());
                    vo.setFgrwzt(rwlq.getFgrwzt());
                }
                voList.add(vo);
            });
        }
        IPage<TbZdyFgrwVO> pageVo = new Page<>(page.getCurrent(),page.getSize());
        pageVo.setTotal(page.getTotal());
        pageVo.setRecords(voList);
        return pageVo;
    }

    @Override
    public TbZdyFgrwVO getFgrwXq(TbZdyFgrwQuery query) {
        TbZdyFgrwVO vo = new TbZdyFgrwVO();
        UserInfo userInfo = UserInfoManager.get();
        TbZdyFgrw tbZdyFgrw = this.baseMapper.selectById(query.getFgrwid());
        if(Objects.isNull(tbZdyFgrw)) throw new BusinessException("方格任务不存在！");
        BeanUtils.copyProperties(tbZdyFgrw,vo);
        TbZdyFgrwlq rwlq = this.tbZdyFgrwlqMapper.selectOne(
                new LambdaQueryWrapper<TbZdyFgrwlq>()
                        .eq(TbZdyFgrwlq::getFgrwid,tbZdyFgrw.getId())
                        .eq(TbZdyFgrwlq::getFgrwlqrid,userInfo.getUserId())
                        .last(" limit 1 ")
        );
        if(Objects.nonNull(rwlq)){
            vo.setFgrwlqr(rwlq.getFgrwlqr());
            vo.setFgrwlqrid(rwlq.getFgrwlqrid());
            vo.setFgrwlqrsfzh(rwlq.getFgrwlqrsfzh());
            vo.setFgrwzt(rwlq.getFgrwzt());
        }
        List<TbZdyFgbxd> bxds = this.tbZdyFgbxdMapper.selectList(
                new LambdaQueryWrapper<TbZdyFgbxd>()
                        .eq(TbZdyFgbxd::getFgrwid,query.getFgrwid())
        );
        if(!CollectionUtils.isEmpty(bxds)){
            List<Map<String,Object>> bxddks = new ArrayList<>();
            bxds.forEach( bxd ->{
                Map<String, Object> map = new HashMap<>();
                map.put("bxdMc",bxd.getBxdMc());
                TbZdyFgrwlqdk dk = this.tbZdyFgrwlqdkMapper.selectOne(
                        new LambdaQueryWrapper<TbZdyFgrwlqdk>()
                                .eq(TbZdyFgrwlqdk::getFgbxdid,bxd.getId())
                                .eq(TbZdyFgrwlqdk::getFgrwid,tbZdyFgrw.getId())
                                .eq(TbZdyFgrwlqdk::getDkrid,userInfo.getUserId().toString())
                                .orderByDesc(TbZdyFgrwlqdk::getDksj)
                                .last(" limit 1 ")
                );
                if(Objects.nonNull(dk)){
                    map.put("fgrwid",bxd.getFgrwid());
                    map.put("bxdid",bxd.getId());
                    map.put("bxdMc",bxd.getBxdMc());
                    map.put("jd",bxd.getJd());
                    map.put("wd",bxd.getWd());
                    map.put("dkzt","已打卡");
                    map.put("dksj",dk.getDksj());
                    map.put("dktp",dk.getDktp());
                }else {
                    map.put("fgrwid",bxd.getFgrwid());
                    map.put("bxdid",bxd.getId());
                    map.put("bxdMc",bxd.getBxdMc());
                    map.put("jd",bxd.getJd());
                    map.put("wd",bxd.getWd());
                    map.put("dkzt","未打卡");
                    map.put("dksj","");
                    map.put("dktp","");
                }
                bxddks.add(map);
            });
            vo.setBxds(bxddks);
        }
        TbZdxlFgdw tbZdxlFgdw = this.tbZdxlFgdwMapper.selectById(tbZdyFgrw.getFgId());
        TbZdxlFgdwVO fgdwVO = buildAllInfoByEntity(tbZdxlFgdw);
        vo.setFgxx(fgdwVO);
        return vo;
    }

    private TbZdxlFgdwVO buildAllInfoByEntity(TbZdxlFgdw entity){
        if(ObjectUtils.isEmpty(entity)){
            return null;
        }
        TbZdxlFgdwVO resultVO = BeanUtil.copyProperties(entity, TbZdxlFgdwVO.class);

        //组装方格其他数据
        resultVO.setMc(resultVO.getMc1());
        resultVO.setX1(resultVO.getX11());
        resultVO.setY1(resultVO.getY11());
        resultVO.setX2(resultVO.getX21());
        resultVO.setY2(resultVO.getY21());

        return resultVO;
    }

    @Override
    public Boolean getLqrw(TbZdyFgrwlqQuery query) {
        UserInfo userInfo = UserInfoManager.get();
        TbQwXfbb tbQwXfbb = this.baseMapper.selectXfbbByFzrSfzh(userInfo.getIdEntityCard(),DateUtils.getNowDate());
        if(Objects.isNull(tbQwXfbb)) throw new BusinessException("请先报备，再领取！");
        TbZdyFgrw fgrw = this.baseMapper.selectById(query.getFgrwid());
        if(Objects.isNull(fgrw)) throw new BusinessException("方格任务不存在！");
        fgrw.setFgrwzt("02");
        this.baseMapper.updateById(fgrw);
        int num = this.tbZdyFgrwlqMapper.selectCount(
                new LambdaQueryWrapper<TbZdyFgrwlq>()
                        .eq(TbZdyFgrwlq::getFgrwlqrid,userInfo.getUserId().toString())
                        .eq(TbZdyFgrwlq::getFgrwid,query.getFgrwid())
        );
        if(num>1) throw new BusinessException("方格任务已领取，请勿重复领取！");
        TbZdyFgrwlq rwlq = new TbZdyFgrwlq();
        rwlq.setId(UUIDGenerator.getUUID());
        rwlq.setFgrwzt("02");
        rwlq.setFgrwid(query.getFgrwid());
        rwlq.setFgrwlqrid(userInfo.getUserId().toString());
        rwlq.setFgrwlqrsfzh(userInfo.getIdEntityCard());
        rwlq.setFgrwlqr(userInfo.getUserName());
        rwlq.setRwlqrq(DateUtils.getNowDate());
        this.tbZdyFgrwlqMapper.insert(rwlq);
        return true;
    }

    @Override
    public Map<String, Object> getFgrwDkXq(TbZdyFgrwQuery query) {
        Map<String, Object> res = new HashMap<>();
        UserInfo user = UserInfoManager.get();
        TbZdyFgrw fgrw = this.baseMapper.selectById(query.getFgrwid());
        List<TbZdyFgbxd> bxds = this.tbZdyFgbxdMapper.selectList(
                new LambdaQueryWrapper<TbZdyFgbxd>()
                        .eq(TbZdyFgbxd::getFgrwid,query.getFgrwid())
        );
        TbZdxlFgdw tbZdxlFgdw = this.tbZdxlFgdwMapper.selectById(fgrw.getFgId());
        TbZdxlFgdwVO fgdwVO = buildAllInfoByEntity(tbZdxlFgdw);
        res.put("fgdwVO",fgdwVO);
        res.put("fgrw",fgrw);
        List<Map<String,Object>> maps = new ArrayList<>();
        if(!CollectionUtils.isEmpty(bxds)){
            bxds.forEach( bxd ->{
                Map<String, Object> map = new HashMap<>();
                map.put("bxdMc",bxd.getBxdMc());
                TbZdyFgrwlqdk dk = this.tbZdyFgrwlqdkMapper.selectOne(
                        new LambdaQueryWrapper<TbZdyFgrwlqdk>()
                                .eq(TbZdyFgrwlqdk::getFgbxdid,bxd.getId())
                                .eq(TbZdyFgrwlqdk::getFgrwid,fgrw.getId())
                                .eq(TbZdyFgrwlqdk::getDkrid,user.getUserId().toString())
                                .orderByDesc(TbZdyFgrwlqdk::getDksj)
                                .last(" limit 1 ")
                );
                if(Objects.nonNull(dk)){
                    map.put("fgrwid",bxd.getFgrwid());
                    map.put("bxdid",bxd.getId());
                    map.put("jd",bxd.getJd());
                    map.put("wd",bxd.getWd());
                    map.put("dkzt","已打卡");
                    map.put("dksj",dk.getDksj());
                    map.put("dktp",dk.getDktp());
                }else {
                    map.put("fgrwid",bxd.getFgrwid());
                    map.put("bxdid",bxd.getId());
                    map.put("jd",bxd.getJd());
                    map.put("wd",bxd.getWd());
                    map.put("dkzt","未打卡");
                    map.put("dksj","");
                    map.put("dktp","");
                }
                maps.add(map);
            });
        }
        res.put("bxds",maps);
        //最新打卡时间
        TbZdyFgrwlqdk zxdk = this.tbZdyFgrwlqdkMapper.selectOne(
                new LambdaQueryWrapper<TbZdyFgrwlqdk>()
                        .eq(TbZdyFgrwlqdk::getFgrwid,fgrw.getId())
                        .eq(TbZdyFgrwlqdk::getDkrid,user.getUserId().toString())
                        .orderByDesc(TbZdyFgrwlqdk::getDksj)
                        .last(" limit 1 ")
        );
        if(Objects.nonNull(zxdk)){
            res.put("zxdksj",zxdk.getDksj());
        }else{
            res.put("zxdksj","");
        }
        return res;
    }

    @Override
    public Boolean zdyRwdk(TbZdyFgrwDkDto dto) {
        UserInfo user = UserInfoManager.get();
        int num = this.tbZdyFgrwlqMapper.selectCount(
                new LambdaQueryWrapper<TbZdyFgrwlq>()
                        .eq(TbZdyFgrwlq::getFgrwid,dto.getFgrwid())
                        .eq(TbZdyFgrwlq::getFgrwlqrid,user.getUserId().toString())
        );
        if(num ==0 ) throw new  BusinessException("您还没有领取该任务！");
        TbZdyFgbxd tbZdyFgbxd = this.tbZdyFgbxdMapper.selectById(dto.getBxdid());
        long jl = PositionUtil.getDistance(dto.getJd().doubleValue(), dto.getWd().doubleValue(),tbZdyFgbxd.getJd().doubleValue(),tbZdyFgbxd.getWd().doubleValue());
        if(jl > 100L) throw new  BusinessException("您的位置在卡点100米以外，无法打卡");
        TbZdyFgrwlqdk tbZdyFgrwlqdk = new TbZdyFgrwlqdk();
        BeanUtils.copyProperties(dto,tbZdyFgrwlqdk);
        tbZdyFgrwlqdk.setId(UUIDGenerator.getUUID());
        tbZdyFgrwlqdk.setDksj(new Date());
        tbZdyFgrwlqdk.setDkrid(user.getUserId().toString());
        tbZdyFgrwlqdk.setDkr(user.getUserName());
        tbZdyFgrwlqdk.setDarsfzh(user.getIdEntityCard());
        tbZdyFgrwlqdk.setFgbxdid(dto.getBxdid());
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(user.getDeptCode());
        if(Objects.nonNull(dept)){
            tbZdyFgrwlqdk.setSsbm(dept.getDeptname());
            tbZdyFgrwlqdk.setSsbmdm(dept.getDeptcode());
            tbZdyFgrwlqdk.setSsxgajdm(dept.getFxjcode());
            tbZdyFgrwlqdk.setSsxgaj(dept.getFxjname());
            tbZdyFgrwlqdk.setSssgaj(dept.getDszname());
            tbZdyFgrwlqdk.setSssgajdm(dept.getDszcode());
        }
        this.tbZdyFgrwlqdkMapper.insert(tbZdyFgrwlqdk);
        return true;
    }
}
