/*
 * Author: Zev
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.sign.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.tofly.api.DepartmentClient;
import com.tofly.api.UserClent;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.es.GpsUpload;
import com.tofly.es.PdaDeviceUpload;
import com.tofly.es.dto.EsQueryDto;
import com.tofly.gpsboot.common.system.NewWorkTypeEnum;
import com.tofly.gpsboot.common.system.SignFlagEnum;
import com.tofly.gpsboot.common.system.SignTypeEnum;
import com.tofly.gpsboot.common.system.WorkStateEnum;
import com.tofly.gpsboot.mapper.plan.PlanMapper;
import com.tofly.gpsboot.service.es.IGpsUploadService;
import com.tofly.pojo.plan.dto.PdasignDto;
import com.tofly.pojo.plan.vo.PdaSignMonitorVo;
import com.tofly.pojo.plan.vo.PdasignVo;
import com.tofly.gpsboot.mapper.plan.PdasignMapper;
import com.tofly.gpsboot.service.es.IPdaDeviceService;
import com.tofly.gpsboot.service.paln.GpscalculateService;
import com.tofly.gpsboot.service.paln.GroupuserService;
import com.tofly.gpsboot.service.sign.PdasignhisService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.User;
import com.tofly.pojo.plan.Gpscalculate;
import com.tofly.pojo.plan.Pdasign;
import com.tofly.gpsboot.service.sign.PdasignService;
import com.tofly.pojo.plan.Pdasignhis;
import com.tofly.pojo.plan.vo.PdasignhisVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 上下班签到瞬时信息表：TF_YWPN_PDASIGN_W
 *
 * @author admin
 * @date Thu Mar 18 00:00:00 CST 2021
 */
@Service("pdasignService")
public class PdasignServiceImpl extends ServiceImpl<PdasignMapper, Pdasign> implements PdasignService {

    @Autowired
    private UserClent userClent;

    @Autowired
    private DepartmentClient departmentClient;

    @Autowired
    private PdasignhisService pdasignhisService;

    @Autowired
    private GpscalculateService gpscalculateService;

    @Autowired
    private IPdaDeviceService iPdaDeviceService;

    @Autowired
    private GroupuserService groupuserService;

    @Autowired
    private IGpsUploadService iGpsUploadService;
    @Autowired
    private PlanMapper planMapper;
    @Override
    public List<PdasignVo> viewConversion(List<Pdasign> infoList) {
        List<PdasignVo> infoVoList = new ArrayList<>();
        infoList.forEach(info -> {
            PdasignVo baseInfo = JSONObject.parseObject(JSON.toJSONString(info), PdasignVo.class);
            // 增加签到用户名称 转换签到类型/签到标识
            Long signUser = info.getSignUser();
            if (null != signUser && 0 != signUser) {
                User userAudit = userClent.getById(signUser).getResult();
                if (null != userAudit) {
                    baseInfo.setSignUserName(userAudit.getRealName());
                    baseInfo.setDeptId(userAudit.getDepartmentId());
                    baseInfo.setDeptName(userAudit.getDepartmentName());
                    baseInfo.setSignType(SignTypeEnum.getCodeForValue(info.getSignType()));
                    baseInfo.setFlag(SignFlagEnum.getCodeForValue(info.getFlag()));
                    infoVoList.add(baseInfo);
                }

            }
        });
        return infoVoList;
    }


    @Override
    public String getUserSignState(Long id) {
        List<Pdasign> pdasign = this.list(new QueryWrapper<Pdasign>().lambda().eq(Pdasign::getSignUser, id));
        if (null == pdasign || pdasign.size()==0) {
            return SignTypeEnum.SIGN_TYPE_UNTREATED.getCode();
        }
        return pdasign.get(0).getSignType();
    }

    @Override
    public Boolean userSign(PdasignDto dto) {
        Long signUser = dto.getSignUser();
        // 用户Id作为更新条件
        Pdasign pdasign = JSONObject.parseObject(JSON.toJSONString(dto), Pdasign.class);
        // 判断当前用户在瞬时表中是否存在上下班签到记录
        List<Pdasign> one = this.list(new QueryWrapper<Pdasign>().lambda().eq(Pdasign::getSignUser, signUser));
        if (null != one && one.size() > 0) {
            pdasign.setId(one.get(0).getId());
            this.updateById(pdasign);
        } else {
            this.save(pdasign);
        }
        // 登录历史表中记录数据
        Pdasignhis pdasignhis = JSONObject.parseObject(JSON.toJSONString(dto), Pdasignhis.class);
        pdasignhisService.save(pdasignhis);

        return true;

    }

    @Override
    public PdaSignMonitorVo getUserSignList(String groupId,String time, Long deptId,String userIds) {
        List<Long> userIdList = null;
        if (!StringUtils.isEmpty(userIds)) {
            userIdList= Arrays.stream(userIds.split(",")).map(k -> Long.parseLong(k.trim())).collect(Collectors.toList());

        }else{

            if (!StringUtils.isEmpty(groupId)) {
                Map<Long, String> groupUserIdNameMap = groupuserService.getGroupUserIdNameMap(Long.valueOf(groupId));
                if (null != groupUserIdNameMap) {
                    userIdList = new ArrayList<>(groupUserIdNameMap.keySet());
                }
            } else {
                Long departmentId = deptId == null ? SecurityUtils.getUserDeptId() : deptId;
                List<User> result = departmentClient.getDeptUserList(departmentId).getResult();
                if(null!=result&&result.size()>0){
                    userIdList = result.stream().map(User::getId).collect(Collectors.toList());
                }

            }
        }
        PdaSignMonitorVo vo = new PdaSignMonitorVo();
        // 获取对应部门id
        if (null != userIdList && userIdList.size() > 0) {
            // 时间不传默认当前天开始/结束时间
            Date staDate = DateTimeUtil.convertLDTToDate(DateTimeUtil.getTodayBeginTime());
            Date endDate = DateTimeUtil.convertLDTToDate(DateTimeUtil.getTodayEndTime());
            if (!StringUtils.isEmpty(time)) {
                // 格式化传入时间
                LocalDateTime localDateTime = DateTimeUtil.fromString2LocalDateTime(time, DateTimeUtil.FULL_FORMAT);
                // 获取指定开始/结束时间
                assert localDateTime != null;
                staDate = DateTimeUtil.convertLDTToDate(DateTimeUtil.getAssignTodayBeginTime(localDateTime));
                endDate = DateTimeUtil.convertLDTToDate(DateTimeUtil.getAssignTodayEndTime(localDateTime));

            }
            List<PdasignhisVo> pdasignVoList = pdasignhisService.viewConversion(pdasignhisService.list(new QueryWrapper<Pdasignhis>().lambda()
                    .in(Pdasignhis::getSignUser, userIdList)
                    .ge(Pdasignhis::getSignTime, staDate)
                    .le(Pdasignhis::getSignTime, endDate)));

            // 用户分组
            Map<Long, List<PdasignhisVo>> listMap = pdasignVoList.stream().collect(Collectors.groupingBy(PdasignhisVo::getSignUser));
            Date finalEndDate = endDate;
            // 获取当前用户最新签到数据
            List<PdasignhisVo> filterList = new ArrayList<>();
            listMap.forEach((k, v) -> {
                PdasignhisVo pdasignhisVo = v.stream().max(Comparator.comparing(PdasignhisVo::getSignTime)).get();
                EsQueryDto esEsQueryDto = new EsQueryDto();
                esEsQueryDto.setUserId(k);
                esEsQueryDto.setIsAsc(true);
                Date today = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    esEsQueryDto.setStartDate(sdf.parse(sdf.format(today) + " 00:00:00"));
                    esEsQueryDto.setEndDate(sdf.parse(sdf.format(today) + " 23:59:59"));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                List<GpsUpload> gpsUploadList = iGpsUploadService.getAll(esEsQueryDto);
                if (gpsUploadList != null && gpsUploadList.size() != 0) {
                    GpsUpload gpsUpload = gpsUploadList.get(gpsUploadList.size() - 1);
                    pdasignhisVo.setLat(gpsUpload.getLocationLatitude().doubleValue());
                    pdasignhisVo.setLng(gpsUpload.getLocationLongitude().doubleValue());
                }
                filterList.add(pdasignhisVo);
            });
            userIdList.forEach(userId -> {
                // 若按照当前时间范围未查询到每个用户的签到记录,则默认赋值为离线状态其余不赋值
                boolean b = listMap.containsKey(userId);
                if (!b) {
                    // 禁用不展示
                    User result = userClent.getById(userId).getResult();
                    if(null!=result&& "1".equals(result.getEnableFlag())){
                        Pdasignhis v = new Pdasignhis();
                        v.setSignUser(userId);
                        v.setFlag(SignFlagEnum.SIGN_FLAG_MANUAL.getCode());
                        v.setSignTime(finalEndDate);
                        v.setSignType(SignTypeEnum.SIGN_TYPE_OFFLINE.getCode());
                        List<Pdasignhis> addList = new ArrayList<>();
                        addList.add(v);
                        filterList.addAll(pdasignhisService.viewConversion(addList));
                    }
                }
            });
            Date finalStaDate = staDate;
            filterList.forEach(info -> {
                List<Gpscalculate> gpsCalculateList = gpscalculateService.list(new QueryWrapper<Gpscalculate>().lambda()
                        .ge(Gpscalculate::getGpsDate, finalStaDate)
                        .le(Gpscalculate::getGpsDate, finalEndDate)
                        .eq(Gpscalculate::getUserId, info.getSignUser()));
                if (null != gpsCalculateList && gpsCalculateList.size() > 0) {
                    Gpscalculate gpscalculate = gpsCalculateList.get(0);
                    info.setTroubleNum(gpscalculate.getFindTroubleNum());
                    info.setBuildNum(gpscalculate.getBuildingsitefinded());
                    info.setTotalOrderNum(gpscalculate.getRepairOrderNum());
                    info.setCompleteOrderNum(gpscalculate.getCompleteOrderNum());

                   /* info.setTotalPlanNum(gpscalculate.getPlanNum());
                    info.setCompletePlanNum(gpscalculate.getPlanCompleteNum());*/
                   /*  gpscalculate.getPlanNum();
                    gpscalculate.getPlanCompleteNumber();*/

                }

                Map<String ,Object> map=planMapper.getPlanRecordCount(finalStaDate,info.getSignUser());
                if(map==null){
                    map.put("overTotal",0);
                    map.put("total",0);
                }
                Long totalPlanNum=Long.valueOf(String.valueOf(map.get("total")));
                Long planCompleteNum=Long.valueOf(String.valueOf(map.get("overTotal")));
                info.setTotalPlanNum(totalPlanNum);
                info.setCompletePlanNum(planCompleteNum);

            });

            // 统计当前时间用户下对应的最新定位网络的类型个数
            List<PdaDeviceUpload> nowUserInfoList = iPdaDeviceService.getNowUserInfoList(userIdList, finalStaDate, finalEndDate);
            if (null != nowUserInfoList && nowUserInfoList.size() > 0) {
                // 分组定位网络类型
                Map<String, Long> collect = nowUserInfoList.stream().collect(Collectors.groupingBy(p -> NewWorkTypeEnum.getCodeForValue(p.getNetwork()), Collectors.counting()));
                // 分组工作状态
                Map<String, Long> longMap = nowUserInfoList.stream().collect(Collectors.groupingBy(p -> WorkStateEnum.getCodeForValue(p.getWorkState()), Collectors.counting()));
                collect.putAll(longMap);
                vo.setLongMap(collect);

            }
            vo.setPdasignVoList(filterList);
        }


        return vo;
    }


}
