/*
 * Author: Zev
 * 生成controller
 */
package com.tofly.gpsboot.controller.sign;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;

import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.SignTypeEnum;
import com.tofly.gpsboot.controller.BaseController;
import com.tofly.gpsboot.service.sign.PdasignhisService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.plan.Pdasignhis;
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.exception.BusinessException;
import com.tofly.pojo.plan.Pdasign;

import com.tofly.gpsboot.service.sign.PdasignService;

import com.tofly.pojo.plan.vo.PdasignhisVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 上下班签到瞬时信息
 *
 * @author admin
 * @date Thu Mar 18 00:00:00 CST 2021
 */
@RestController
@RequestMapping("/pdasign")
@Api(tags="上下班签到瞬时信息")
public class PdasignController extends BaseController<Pdasign, PdasignVo> {
    @Autowired
    private PdasignService service;

    @Autowired
    private PdasignhisService pdasignhisService;

    @Autowired
    public PdasignController(PdasignService service) {
        init(service);
    }

    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    @ToFlyAppLog(title = "分页查询上下班签到瞬时信息")
    public ResultRespone<Page<PdasignVo>> getPdasignPage(Page page, @ModelAttribute PdasignDto parDto) {
        return super.getInfoPage(page, JSON.parseObject(JSON.toJSONString(parDto), Pdasign.class));
    }

    @ApiOperation(value = "用户签到")
    @PostMapping("/userSign")
    @ToFlyAppLog(title = "用户签到")
    public ResultRespone<Object> userSign(@Valid @RequestBody PdasignDto parDto, BindingResult result) {
        ResultRespone<Object> rest = new ResultRespone<>();
        try {
            if (!Optional.ofNullable(super.validRest(rest, result)).isPresent()) {
                rest.setResult(service.userSign(parDto));
            }
        }catch (BusinessException e){
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());

        }
        return rest;
    }

    @GetMapping("/getUserSignState/{userId}")
    @ApiOperation(value = "根据用户id 查询当前用户是否签到,签到类型；1：上班 2：下班")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId", required = true, dataType = "Long")
    })
    @ToFlyAppLog(title = "根据用户id 查询当前用户是否签到,签到类型；1：上班 2：下班")
    public ResultRespone<String> getByIdBuild(@PathVariable Long userId) {
        ResultRespone<String> rest = new ResultRespone<>();
        try {
            String userSignState = service.getUserSignState(userId);
            rest.setResult(userSignState);
        }catch (BusinessException e){
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());

        }
        return rest;

    }


    @GetMapping("/getUserSignList")
    @ApiOperation(value = "获取当前用户下部门中所有人员的签到信息")
    @ToFlyAppLog(title = "获取当前用户下部门中所有人员的签到信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "分组id", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "time", value = "查询时间 不传默认今天,格式 YYYY-MM-DD HH:mm:ss", required = false, dataType = "String"),
            @ApiImplicitParam(name = "deptId", value = "部门id,不传默认为当前部门", required = false, dataType = "Long")
    })
    public ResultRespone<PdaSignMonitorVo> getUserSignList(String groupId,String time,Long deptId) {
        return ResultRespone.success(service.getUserSignList(groupId,time,deptId));
    }


    @PutMapping("/updateSignUserDisable")
    @ApiOperation(value = "禁用时,修改用户最新签到信息签到状态为停用")
    public ResultRespone<Boolean> updateSignUserDisable(@RequestParam("userIds") String userIds) {
        if(!StringUtils.isEmpty(userIds)){
            List<Long> userIdList = Arrays.stream(userIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toList());
            // 当前天开始/结束时间
            Date staDate = DateTimeUtil.convertLDTToDate(DateTimeUtil.getTodayBeginTime());
            Date endDate = DateTimeUtil.convertLDTToDate(DateTimeUtil.getTodayEndTime());
            List<PdasignhisVo> pdasignVoList = pdasignhisService.viewConversion(pdasignhisService.list(new QueryWrapper<Pdasignhis>().lambda()
                    .in(Pdasignhis::getSignUser, userIdList)
                    .ge(Pdasignhis::getSignTime, staDate)
                    .le(Pdasignhis::getSignTime, endDate)));
            if(null!=pdasignVoList && pdasignVoList.size()>0){
                // 用户分组
                Map<Long, List<PdasignhisVo>> listMap = pdasignVoList.stream().collect(Collectors.groupingBy(PdasignhisVo::getSignUser));
                // 获取当前用户最新签到数据
                List<Long> filterList = new ArrayList<>();
                listMap.forEach((k, v) -> {
                    PdasignhisVo pdasignhisVo = v.stream().max(Comparator.comparing(PdasignhisVo::getSignTime)).get();
                    filterList.add(pdasignhisVo.getId());
                });
                pdasignhisService.update(new UpdateWrapper<Pdasignhis>().lambda().in(Pdasignhis::getId,filterList).set(Pdasignhis::getSignType, SignTypeEnum.SIGN_TYPE_DISABLE.getCode()));
            }

        }

        return ResultRespone.success();
    }
}
