package cn.com.ty.lift.business.capital.service;

import cn.com.ty.lift.business.capital.dao.entity.CapitalRepair;
import cn.com.ty.lift.business.capital.dao.entity.SignIn;
import cn.com.ty.lift.business.capital.dao.entity.model.request.CapitalRepairRequest;
import cn.com.ty.lift.business.capital.dao.entity.model.response.SignInResponse;
import cn.com.ty.lift.business.capital.dao.entity.model.response.SignRecord;
import cn.com.ty.lift.business.capital.dao.entity.model.response.SignRecordGroupResult;
import cn.com.ty.lift.business.capital.dao.mapper.SignInMapper;
import cn.com.ty.lift.business.framework.util.MessageUtils;
import cn.com.ty.lift.business.project.dao.entity.model.response.ProjectUserResponse;
import cn.com.ty.lift.business.project.service.ProjectUserService;
import cn.com.ty.lift.common.constants.CommonEnum;
import cn.com.ty.lift.common.verify.VerifyUtils;
import cn.com.xwy.boot.web.dto.RestResponse;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author bieao
 * @date 2020/2/5
 * @description 大修签到业务层
 */
@Service
public class SignInService extends ServiceImpl<SignInMapper, SignIn> {

     @Resource
     private ProjectUserService projectUserService;

     @Resource
     private CapitalRepairService capitalRepairService;

    /**
     * @param mtCompanyId 公司id
     * @param projectId 项目id
     * @param userId 用户id
     * @return 签到记录
     * @description 用户签到记录
     * @date 2020/4/20 9:29 下午
     */
    public SignIn getOne(Long mtCompanyId, Long projectId, Long userId) {
        LambdaQueryWrapper<SignIn> lambdaQueryWrapper = new QueryWrapper<SignIn>().lambda();
        lambdaQueryWrapper.eq(SignIn::getProjectId, projectId);
        lambdaQueryWrapper.eq(SignIn::getMtCompanyId, mtCompanyId);
        lambdaQueryWrapper.eq(SignIn::getUserId, userId);
        lambdaQueryWrapper.eq(SignIn::getSignDate, LocalDate.now());
        return getOne(lambdaQueryWrapper);
    }

    /**
     * @param request 用户签到信息
     * @return 是否成功
     * @description 大修签到
     * @date 2020/4/20 9:29 下午
     */
    public RestResponse signIn(CapitalRepairRequest request) {
//        boolean ret = VerifyUtils.preJudgment(request.getCoordinate());
//        if (!ret)
//            return RestResponse.fail(MessageUtils.get("msg.longitude.error"));
        SignIn oldSignIn = getOne(request.getMtCompanyId(), request.getProjectId(), request.getUserId());
        if (ObjectUtil.isNotEmpty(oldSignIn)) {
            String approachTime = oldSignIn.getApproachTime();
            String leavingTime = oldSignIn.getLeavingTime();
            if (ObjectUtil.notEqual("--", approachTime) && ObjectUtil.notEqual("--", leavingTime)) {
                //今日已签到
                return RestResponse.fail(MessageUtils.get("msg.sign.limit"));
            }
            oldSignIn.setLeavingTime(LocalTime.now().withNano(0).toString());
            saveOrUpdate(oldSignIn);
        } else {
            SignIn signIn = new SignIn();
            signIn.setCoordinate(request.getCoordinate());
            signIn.setMtCompanyId(request.getMtCompanyId());
            signIn.setUserId(request.getUserId());
            signIn.setProjectId(request.getProjectId());
            signIn.setAddress(request.getAddress());
            signIn.setSignDate(LocalDate.now());
            signIn.setApproachTime(LocalTime.now().withNano(0).toString());
            save(signIn);
        }
        return  RestResponse.success(null, MessageUtils.get("msg.sign.success"));
    }


   /**
    * @param request 公司ID，用户ID
    * @return 考勤人员列表
    * @description 考勤人员列表
    * @date 2020/4/15 2:52 下午
    */
    public List<ProjectUserResponse> attendanceList(CapitalRepairRequest request) {
        //查询项目组成员列表
        List<ProjectUserResponse> userList = projectUserService.getUserList(request.getProjectId(), request.getMtCompanyId());

        //查询所有项目组成员考勤记录
        QueryWrapper<SignIn> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<SignIn> lambdaQueryWrapper = queryWrapper.lambda();
        lambdaQueryWrapper.eq(SignIn::getMtCompanyId, request.getMtCompanyId());
        lambdaQueryWrapper.eq(SignIn::getProjectId, request.getProjectId());
        lambdaQueryWrapper.eq(Objects.nonNull(request.getSignDate()), SignIn::getSignDate, request.getSignDate());
        //考勤记录列表
        ArrayList<SignIn> recordList = (ArrayList<SignIn>) list(lambdaQueryWrapper);

        List<ProjectUserResponse> responseList = userList.stream().filter(user -> (
                CommonEnum.DefaultRole.MTWORK.getCode().equals(user.getUserRole())
        )).collect(Collectors.toList());

        Optional<ProjectUserResponse> first = responseList.stream().filter(entry -> entry.getUserId().equals(request.getUserId())).findFirst();
        first.ifPresent(response -> {
            String monitor = response.getIsMonitor();
            //当前用户非维保班长的考勤记录
            if ("0".equals(monitor)) {
                recordList.removeIf(entry -> !entry.getUserId().equals(request.getUserId()));
            }
            //组装所有项目成员的考勤记录
            for (ProjectUserResponse entry : responseList) {
                List<SignIn> list = new ArrayList<>();
                for (SignIn signIn : recordList) {
                    if (entry.getUserId().equals(signIn.getUserId())) {
                        list.add(signIn);
                        entry.setAttendanceRecord(list);
                    }
                }
            }
        });
        return responseList;
    }

   /**
    * @param request 公司id，项目id
    * @return 签到时间列表
    * @description 查询签到时间
    * @date 2020/4/18 7:12 下午
    */
    public List<LocalDate> getSignDate(CapitalRepairRequest request) {
       return baseMapper.getSignDate(request);
    }

    /**
     * @param request 大修签到查询条件
     * @return RestResponse 结果集
     * @description 条件查询大修项目签到列表
     * @date 2020/4/16 7:22 下午
     */
    public RestResponse list(CapitalRepairRequest request) {
        SignInResponse response = new SignInResponse();
        //查询大修项目详情
        CapitalRepair capital = capitalRepairService.getOne(request.getId());
        response.setCapitalRepair(capital);
        List<LocalDate> list = getSignDate(request);
        int size = list.size();
        if (CollUtil.isEmpty(list)) return RestResponse.success(null, MessageUtils.get("msg.capital.not.sign.record"));
        int count = size / (int) request.getPageSize();
        Map<String, Object> paramMap = new HashMap<>();
        int minIndex = (int) ((request.getPageNum() - 1) * request.getPageSize());
        int maxIndex = (int) (request.getPageNum() * request.getPageSize());
        if (maxIndex >= size) {
            maxIndex = size - 1;
        }
        LocalDate minDate = list.get(minIndex);
        LocalDate maxDate = list.get(maxIndex);
        paramMap.put("minDate", minDate);
        paramMap.put("maxDate", maxDate);
        paramMap.put("mtCompanyId", request.getMtCompanyId());
        paramMap.put("projectId", request.getId());
        paramMap.put("userId", request.getUserId());
        //查询签到记录
        List<SignRecord> signRecordList = baseMapper.findByCondition(paramMap);
        List<SignRecordGroupResult> results = new ArrayList<>();
        List<String> userNames = signRecordList.stream().map(SignRecord::getUserName).distinct().collect(Collectors.toList());
        //分组签到记录
        Map<LocalDate, List<SignRecord>> signRecordMap = signRecordList.stream().collect(Collectors.groupingBy(SignRecord::getSignDate));
        for (Map.Entry<LocalDate, List<SignRecord>> entry : signRecordMap.entrySet()) {
            LocalDate signDate = entry.getKey();
            List<SignRecord> signRecords = entry.getValue();
            for (String name : userNames) {
                Optional<SignRecord> first = signRecords.stream().filter(sign -> Objects.equals(name, sign.getUserName())).findFirst();
                if (!first.isPresent()) {
                    SignRecord record = new SignRecord();
                    record.setUserName(name);
                    record.setSignDate(signDate);
                    signRecords.add(record);
                }
            }
            SignRecordGroupResult result = new SignRecordGroupResult();
            result.setSignDate(signDate);
            result.setSignRecords(signRecords);
            results.add(result);
        }
        results.sort(Comparator.comparing(SignRecordGroupResult::getSignDate).reversed());
        //组装分页数据
        Page<SignRecordGroupResult> page = new Page<>();
        page.setCurrent(request.getPageNum());
        page.setSize(request.getPageSize());
        page.setPages(size % request.getPageSize() > 0 ? count + 1 : count);
        page.setTotal(size);
        page.setRecords(results);
        response.setResultPage(page);
        return RestResponse.success(response, MessageUtils.get("msg.query.success"));
    }
}
