package com.jpsoft.shinestar.modules.base.controller;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.util.StringUtil;
import com.jpsoft.shinestar.modules.base.dto.CompanyRecordReportDTO;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author 墨鱼_mo
 * @date 2020-4-7 8:53
 */

@Slf4j
@RequestMapping("/report")
@RestController
public class ReportController {


    @Autowired
    private UserService userService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonDeviceFilterLogService personDeviceFilterLogService;

    @Autowired
    private PersonDeviceLogService personDeviceLogService;


    @ApiOperation(value = "获取每个单位的人数和打卡人数")
    @PostMapping("getCompanyRecordReport")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId",value = "上级单位ID", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "subordinate",value = "是否查询下级单位", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "timeRanges",value = "时间范围", paramType = "query")
    })
    public MessageResult<Map> getCompanyRecordReport(
            @RequestParam(value="parentId",defaultValue="")  String parentId,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @RequestParam(value="timeRanges",defaultValue = "") String timeRanges,
            @RequestAttribute String subject) {

        MessageResult<Map> msgResult = new MessageResult<>();
        HashMap<String, Object> map = new HashMap<>();
        try {
            User user = userService.get(subject);
            List<CompanyInfo> list = new ArrayList<>();

            //系统管理者和非系统管理者公司列表
            if(StringUtil.isNotEmpty(parentId)){
                CompanyInfo companyInfo = companyInfoService.get(parentId);
                String code = "";

                if (subordinate) {
                    code = companyInfo.getCode() + "%";
                } else {
                    code = companyInfo.getCode();
                }

                list = companyInfoService.findByCompanyCode(code, null);
            }else {
                if (userService.hasRole(subject, "SYSADMIN")) {
                    list = companyInfoService.list();
                } else {
                    CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
                    list = companyInfoService.findByCompanyCode(companyInfo.getCode() + "%", null);
                }
            }

            //查询时间
            Date beginTime = DateUtil.beginOfDay(new Date());
            Date endTime = DateUtil.endOfDay(new Date());
            if(StringUtil.isNotEmpty(timeRanges)){
                String[] timeRangeArray = timeRanges.split(",");
                if(timeRangeArray.length==1){
                    beginTime = DateUtil.parse(timeRangeArray[0]);
                }
                else if(timeRangeArray.length==2){
                    beginTime = DateUtil.parse(timeRangeArray[0]);
                    endTime = DateUtil.parse(timeRangeArray[1]);
                }
            }

            //结果集
            List<CompanyRecordReportDTO> companyRecordReportDTOS = new ArrayList<>();
            //所有公司人员总数初始化
            long totalPersonNum = 0;
            //所有公司已测人数初始化
            long checkTotalPersonNum = 0;

            if (list.size()>0){
                for (CompanyInfo companyInfo : list){
                    //结果集对象初始化
                    CompanyRecordReportDTO companyRecordReportDTO = new CompanyRecordReportDTO();

                    //查询公司的所有未删除员工数
                    long personTotalNum = personInfoService.countByCompanyCode(companyInfo.getCode() + "%",null);

                    //总人数
                    totalPersonNum = totalPersonNum + personTotalNum;

                    //记录表中时间区间内的非重复数据
                    long checkPersonNum = personDeviceLogService.countByAttendance(companyInfo.getCode() + "%",beginTime,endTime);

                    //总已测人数
                    checkTotalPersonNum = checkTotalPersonNum + checkPersonNum;

                    //查询出未测温对象
                    List<Long> unmeasuredList = personDeviceLogService.queryUnAttendanceList(companyInfo.getCode() + "%", beginTime, endTime,null);

                    //未测试人员姓名集合初始化
                    String name = "";
                    if (unmeasuredList.size()>0){
                        for (Long personId: unmeasuredList){
                            PersonInfo personInfo = personInfoService.get(personId);
                            name = name +","+ personInfo.getName();
                        }

                        name = name.substring(1);
                    }

                    companyRecordReportDTO.setCompanyName(companyInfo.getName());
                    companyRecordReportDTO.setPersonTotal(personTotalNum);
                    companyRecordReportDTO.setCheckPersonTotal(checkPersonNum);
                    companyRecordReportDTO.setUnCheckPersonName(name);
                    companyRecordReportDTOS.add(companyRecordReportDTO);
                }
            }
            map.put("list",companyRecordReportDTOS);
            map.put("totalPersonNum",totalPersonNum);
            map.put("checkTotalPersonNum",checkTotalPersonNum);

            msgResult.setData(map);
            msgResult.setResult(true);
            msgResult.setMessage("获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            msgResult.setData(map);
            msgResult.setResult(false);
            msgResult.setMessage(e.getMessage());
        }


        return msgResult;
    }
}
