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

import com.github.pagehelper.Page;
import com.github.pagehelper.util.StringUtil;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.base.dto.WorkOverStatistics;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.dto.UpdatePersonAttendanceDTO;
import com.jpsoft.shinestar.modules.business.entity.WorkScheduleAttendance;
import com.jpsoft.shinestar.modules.business.service.WorkScheduleAttendanceService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.entity.DataDictionary;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.joda.time.DateTime;
import org.joda.time.Minutes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

//import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
//import java.text.SimpleDateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 加班申请
 * sz
 */
@Slf4j
@RestController
@RequestMapping("/base/workOver")
@Api(description = "workOver")
public class WorkOverController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WorkOverService workOverService;

    @Autowired
    private WorkOverPersonService workOverPersonService;

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private UserService userService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    private WorkShiftInfoService workShiftInfoService;

    @Autowired
    private WorkScheduleAttendanceService workScheduleAttendanceService;

    @Autowired
    private WorkPersonSchedulingService workPersonSchedulingService;

    @Autowired
    private PersonDeviceLogService personDeviceLogService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<WorkOver> create(){
        MessageResult<WorkOver> msgResult = new MessageResult<>();

        WorkOver workOver = new WorkOver();

        msgResult.setData(workOver);
        msgResult.setResult(true);

        return msgResult;
    }
    
    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<WorkOver> add(@RequestBody WorkOver workOver,@RequestAttribute String subject){
        MessageResult<WorkOver> msgResult = new MessageResult<>();

        try {
            workOver.setId(UUID.randomUUID().toString());
            workOver.setDelFlag(false);
            workOver.setCreateBy(subject);
            workOver.setCreateTime(new Date());
            
            int affectCount = workOverService.insert(workOver);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(workOver);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<WorkOver> edit(@PathVariable("id") String id){
        MessageResult<WorkOver> msgResult = new MessageResult<>();

        try {
            WorkOver workOver = workOverService.get(id);

            if (workOver != null) {
                msgResult.setResult(true);
                msgResult.setData(workOver);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<WorkOver> update(@RequestBody WorkOver workOver,@RequestAttribute String subject){
        MessageResult<WorkOver> msgResult = new MessageResult<>();

        try {
            workOver.setUpdateBy(subject);
            workOver.setUpdateTime(new Date());
            
            int affectCount = workOverService.update(workOver);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(workOver);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

	@ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            WorkOver workOver = workOverService.get(id);
            workOver.setDelFlag(true);
            workOver.setUpdateBy(subject);
            workOver.setUpdateTime(new Date());

            int affectCount = workOverService.update(workOver);

            if (affectCount > 0) {
                List<WorkOverPerson> workOverPersonList = workOverPersonService.findByWorkOverId(workOver.getId());

                for (WorkOverPerson workOverPerson : workOverPersonList) {
                    workOverPerson.setDelFlag(true);
                    workOverPerson.setUpdateTime(new Date());
                    workOverPersonService.update(workOverPerson);

                    WorkScheduleAttendance workScheduleAttendance  = workScheduleAttendanceService.findOneByWorkOverPersonId(workOverPerson.getId());

                    if(workScheduleAttendance!=null){
                        workScheduleAttendance.setRemark("取消加班");
                        workScheduleAttendance.setDelFlag(true);
                        workScheduleAttendance.setUpdateTime(new Date());
                        workScheduleAttendance.setUpdateBy(subject);

                        workScheduleAttendanceService.update(workScheduleAttendance);
                    }

                    PersonPopedom personPopedom = personPopedomService.get(workOverPerson.getPersonPopedomId());

                    UpdatePersonAttendanceDTO updatePersonAttendanceDTO = new UpdatePersonAttendanceDTO(
                            personPopedom.getPersonId(), workOver.getStartTime(),workOver.getEndTime());

                    rabbitTemplate.convertAndSend("updatePersonAttendanceQueue", updatePersonAttendanceDTO);
                }

                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                WorkOver workOver = workOverService.get(id);
                workOver.setDelFlag(true);
                workOver.setUpdateBy(subject);
                workOver.setUpdateTime(new Date());

                affectCount += workOverService.update(workOver);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "单位", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "personName", value = "加班申请人", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "审批状态", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "加班开始日期", paramType = "form"),
            @ApiImplicitParam(name = "endTime", value = "加班结束日期", paramType = "form"),
            @ApiImplicitParam(name = "auditStartTime", value = "审核开始日期", paramType = "form"),
            @ApiImplicitParam(name = "auditEndTime", value = "审核结束日期", paramType = "form"),
            @ApiImplicitParam(name = "exportXls", value = "导出报表", paramType = "form"),
            @ApiImplicitParam(name = "hours", value = "加班时长", paramType = "form"),
            @ApiImplicitParam(name = "workOverPersonName", value = "加班人", paramType = "form")
    })
    public MessageResult<Object> pageList(
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="subordinate",defaultValue="false") Boolean subordinate,
            @RequestParam(value="hqCompanyId",defaultValue="") String hqCompanyId,
            @RequestParam(value="hqSubordinate",defaultValue="false") Boolean hqSubordinate,
            @RequestParam(value = "personName", defaultValue = "") String personName,
            @RequestParam(value = "status", defaultValue = "") String status,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date auditStartTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date auditEndTime,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @RequestParam(value = "exportFlag", defaultValue = "false") Boolean exportFlag,
            @RequestParam(value = "hours", defaultValue = "") Integer hours,
            @RequestParam(value = "workOverPersonName", defaultValue = "") String workOverPersonName,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Object> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("a.create_time","desc"));

        //当前用户ID
        User user = userService.get(subject);

        if(!userService.hasRole(user.getId(),"SYSADMIN")) {
            //非系统管理员
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
            searchParams.put("companyCode", companyInfo.getCode() + "%");
        }

        if (StringUtils.isNotEmpty(companyId)){
            CompanyInfo companyInfo = companyInfoService.get(companyId);

            if(subordinate){
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            }
            else {
                searchParams.put("companyCode", companyInfo.getCode());
            }
        }

        if (StringUtils.isNotEmpty(hqCompanyId)){
            if("hq1".equals(hqCompanyId)){
                //后勤1
                searchParams.put("hqStatus", "1");
            }
            else if("hq2".equals(hqCompanyId)){
                //后勤2
                searchParams.put("hqStatus", "2");
            }
            else {
                CompanyInfo companyInfo = companyInfoService.get(hqCompanyId);

                if (hqSubordinate) {
                    searchParams.put("hqCompanyCode", companyInfo.getCode() + "%");
                } else {
                    searchParams.put("hqCompanyCode", companyInfo.getCode());
                }
            }

            searchParams.put("hqPerson",true);
        }


        if (StringUtils.isNotEmpty(personName)) {
            searchParams.put("personName","%" + personName + "%");
        }

        if (StringUtil.isNotEmpty(status)) {
            searchParams.put("status", status);
        }

        if (startTime!=null) {
            searchParams.put("startTime", startTime);
        }

        if (endTime!=null) {
            searchParams.put("endTime", new DateTime(endTime).plusDays(1).plusSeconds(-1).toDate());
        }

        if (auditStartTime!=null) {
            searchParams.put("auditStartTime", auditStartTime);
        }

        if (auditEndTime!=null) {
            searchParams.put("auditEndTime", new DateTime(auditEndTime).plusDays(1).plusSeconds(-1).toDate());
        }

        if (hours!=null) {
            searchParams.put("hours", hours);
        }

        if(StringUtils.isNotEmpty(workOverPersonName)){
            searchParams.put("workOverPersonName", "%" + workOverPersonName + "%");
        }

        Page<WorkOver> page = workOverService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);

        for(WorkOver wo : page.getResult()){
            Map<String,Object> searchParams2 = new HashMap<>();
            searchParams2.put("workOverId", wo.getId());
            Page<WorkOverPerson> page2 = workOverPersonService.pageSearch(searchParams2,0,10000,false,sortList);
            String overPersonNames = page2.getResult().stream()
                    .map((wop)->wop.getPersonName())
                    .collect(Collectors.joining(","));
            wo.setOverPersonNames(overPersonNames);

//            String overPersonIds = page2.getResult().stream()
//                    .map((wop)->wop.getPersonId())
//                    .collect(Collectors.joining(","));
//            wo.setOverPersonIds(overPersonIds);

            List<Map> overPersonList = new ArrayList<>();

            for (int i=0;i<page2.size();i++){
                WorkOverPerson workOverPerson=page2.get(i);

                Map<Object,String> overPersonMap = new HashMap<>();
                overPersonMap.put("id",workOverPerson.getPersonId());
                overPersonMap.put("name",workOverPerson.getPersonName());
                overPersonList.add(overPersonMap);
            }
            wo.setOverPerson(overPersonList);
        }

        List<WorkOver> dataList = page.getResult();

        if(exportFlag) {
            String filePath = exportXls(dataList);
            msgResult.setData(filePath);
        }
        else{
            msgResult.setData(PojoUtils.pageWrapper(page));
        }

        msgResult.setResult(true);
        return msgResult;
    }


    private String exportXls(List<WorkOver> mapList) {
        String downloadUrl = "";

        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        //表头
        Row rowTitle = sheet.createRow(0);

        String[] titles = new String[]{"序号","申请人","单位/部门","开始时间","结束时间","加班时长","加班原因","审批人","状态","审核时间"};

        for (int i=0;i<titles.length;i++) {
            Cell cell = rowTitle.createCell(i);
            cell.setCellValue(titles[i]);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (int i=0;i<mapList.size();i++){
            WorkOver workOver = mapList.get(i);

            Row row = sheet.createRow(i+1);

            int colIndex = 0;

            row.createCell(colIndex++).setCellValue(i+1);
            row.createCell(colIndex++).setCellValue(workOver.getPersonName());
            row.createCell(colIndex++).setCellValue(workOver.getCompanyName());

            if(workOver.getStartTime()!=null) {
                row.createCell(colIndex).setCellValue(sdf.format(workOver.getStartTime()));
            }

            colIndex++;

            if(workOver.getEndTime()!=null) {
                row.createCell(colIndex).setCellValue(sdf.format(workOver.getEndTime()));
            }

            colIndex++;

            row.createCell(colIndex++).setCellValue(workOver.getHours());
            row.createCell(colIndex++).setCellValue(workOver.getReason());
            row.createCell(colIndex++).setCellValue(workOver.getApprovalPersonName());
            row.createCell(colIndex++).setCellValue(workOver.getStatusN());

            if(workOver.getApprovalTime()!=null){
                row.createCell(colIndex++).setCellValue(sdf.format(workOver.getApprovalTime()));
            }
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            downloadUrl = OSSUtil.upload(ossConfig,"requestForLeave","加班记录.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }

    @ApiOperation(value="加班统计")
    @RequestMapping(value = "statisticsList",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personName", value = "加班申请人", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "companyId", value = "单位", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "jobNumber", value = "工号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "加班开始日期", paramType = "form"),
            @ApiImplicitParam(name = "endTime", value = "加班结束日期", paramType = "form"),
            @ApiImplicitParam(name = "exportFlag", value = "是否导出报表(默认不导出0,1导出", paramType = "form"),
    })
    public MessageResult<Object> statisticsList(
            @RequestParam(value = "companyId", defaultValue = "") String companyId,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @RequestParam(value = "personName", defaultValue = "") String personName,
            @RequestParam(value = "jobNumber", defaultValue = "") String jobNumber,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            @RequestParam(value = "exportFlag", defaultValue = "0") String exportFlag,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Object> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();
        Map<String, Object> msgMap = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("a.id_","asc"));


        if (StringUtil.isNotEmpty(companyId)) {
            CompanyInfo companyInfo = companyInfoService.get(companyId);
            if(subordinate){
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            }else{
                searchParams.put("companyCode", companyInfo.getCode());
            }
        }else{
            User user = userService.get(subject);
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
            if (!userService.hasRole(subject,"SYSADMIN")) {
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            }
        }


        if (StringUtils.isNotEmpty(personName)) {
            searchParams.put("name","%" + personName + "%");
        }

        if (StringUtil.isNotEmpty(jobNumber)) {
            searchParams.put("jobNumber", jobNumber);
        }

        if (startTime!=null) {
            searchParams.put("startTime", startTime);
        }

        if (endTime!=null) {
            endTime = new DateTime(endTime).plusDays(1).plusSeconds(-1).toDate();
            searchParams.put("endDate", new DateTime(endTime).plusDays(1).plusSeconds(-1).toDate());
        }


        //查询申请加班的角色
        List<String> workOverPeopdomIds = workOverService.findPeopdomId(startTime,endTime);
        searchParams.put("popedomList", workOverPeopdomIds);
        Page<PersonInfo> page = personInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);

        List<WorkOverStatistics> wosList = new ArrayList<>();
        for(PersonInfo personInfo:page.getResult()){
            WorkOverStatistics wos = new WorkOverStatistics();
            wos.setCompanyId(personInfo.getCompanyId());
            wos.setCompanyName(personInfo.getCompanyName());
            wos.setPersonId(personInfo.getId());
            wos.setPersonName(personInfo.getName());
            wos.setJobNumber(personInfo.getJobNumber());

            List<WorkOverPerson> overLists = workOverPersonService.findByPersonIdAndSEDate(personInfo.getId(),startTime,endTime);
            wos.setCount(overLists.size());
            Integer minute = 0;
            for(WorkOverPerson wop : overLists){
                if(wop.getDuration() == null){
                    minute = minute + (wop.getHours()*60);
                }else{
                    minute = minute + wop.getDuration();
                }
            }
            wos.setDuration(minute);
            wos.setDurationStr(formatTime(minute));

            int approvalCount = workOverService.findCountByPersonId(personInfo.getId(),startTime,endTime);
            wos.setApprovalCount(approvalCount);

            Date approvalTime = workOverService.findTopApprovalTimeByPersonId(personInfo.getId(),startTime,endTime);
            wos.setLastApprovalTime(approvalTime);
            Date createTime = workOverService.findTopCreateTimeByPersonId(personInfo.getId(),startTime,endTime);
            wos.setLastCreateTime(createTime);

            wosList.add(wos);
        }

        if("0".equals(exportFlag)) {
            msgMap.put("wosList",wosList);
            msgMap.put("recordsTotal",page.getTotal());
            msgMap.put("recordsFiltered",page.getTotal());
            msgMap.put("totalPage",page.getPages());
            msgMap.put("pageNumber",page.getPageNum());
            msgMap.put("pageSize",page.getPageSize());
            msgResult.setData(msgMap);
        }
        else{
            String filePath = exportStatisticsList(wosList);
            msgResult.setData(filePath);
        }
        msgResult.setResult(true);
        return msgResult;
    }

    private String exportStatisticsList(List<WorkOverStatistics> wosList) {
        String downloadUrl = "";

        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        //表头
        Row rowTitle = sheet.createRow(0);

        String[] titles = new String[]{"序号","编号","单位/部门","工号","姓名","加班时长","加班申请次数","审批通过次数","最后申请时间","最后审核时间"};

        for (int i=0;i<titles.length;i++) {
            Cell cell = rowTitle.createCell(i);
            cell.setCellValue(titles[i]);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (int i=0;i<wosList.size();i++){
            WorkOverStatistics workOverStatistics = wosList.get(i);

            Row row = sheet.createRow(i+1);

            int colIndex = 0;

            row.createCell(colIndex++).setCellValue(i+1);
            if(workOverStatistics.getPersonId() != null) {
                row.createCell(colIndex++).setCellValue(workOverStatistics.getPersonId());
            }
            if(workOverStatistics.getCompanyName() != null) {
                row.createCell(colIndex++).setCellValue(workOverStatistics.getCompanyName());
            }
            if(workOverStatistics.getJobNumber() != null) {
                row.createCell(colIndex++).setCellValue(workOverStatistics.getJobNumber());
            }
            if(workOverStatistics.getPersonName() != null) {
                row.createCell(colIndex++).setCellValue(workOverStatistics.getPersonName());
            }
            if(workOverStatistics.getDurationStr() != null) {
                row.createCell(colIndex++).setCellValue(workOverStatistics.getDurationStr());
            }
            if(workOverStatistics.getCount() != null) {
                row.createCell(colIndex++).setCellValue(workOverStatistics.getCount());
            }
            if(workOverStatistics.getApprovalCount() != null) {
                row.createCell(colIndex++).setCellValue(workOverStatistics.getApprovalCount());
            }
            if(workOverStatistics.getLastCreateTime() != null) {
                row.createCell(colIndex++).setCellValue(sdf.format(workOverStatistics.getLastCreateTime()));
            }
            if(workOverStatistics.getLastApprovalTime() != null) {
                row.createCell(colIndex++).setCellValue(sdf.format(workOverStatistics.getLastApprovalTime()));
            }
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMDDHHmmss");

            downloadUrl = OSSUtil.upload(ossConfig,"requestForLeave","加班统计" + sdf2.format(new Date()) + ".xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }

    @ApiOperation(value="加班统计详细")
    @RequestMapping(value = "statisticsDetail",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personId", value = "加班申请人", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "加班开始日期", paramType = "form"),
            @ApiImplicitParam(name = "endTime", value = "加班结束日期", paramType = "form"),
    })
    public MessageResult<Object> statisticsDetail(
            @RequestParam(value = "personId", defaultValue = "") String personId,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            @RequestParam(value = "status", defaultValue = "") String status,
            @RequestParam(value = "exportFlag", defaultValue = "0") String exportFlag,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Object> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();
        Map<String, Object> msgMap = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("a.create_time","asc"));


        if (startTime!=null) {
            searchParams.put("startDate", startTime);
        }

        if (endTime!=null) {
            searchParams.put("endDate", new DateTime(endTime).plusDays(1).plusSeconds(-1).toDate());
        }

        if(StringUtils.isNotEmpty(status)) {
            searchParams.put("status", status);
        }

        searchParams.put("personId", personId);
        Page<WorkOverPerson> page = workOverPersonService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
        for(WorkOverPerson wop : page.getResult()){
            WorkOver wo = workOverService.get(wop.getWorkOverId());
            wop.setWorkOver(wo);
            PersonInfo pi = personInfoService.get(Long.valueOf(wop.getPersonId()));
            wop.setPersonInfo(pi);
        }

        if("0".equals(exportFlag)) {
            msgResult.setData(PojoUtils.pageWrapper(page));
        }
        else{
            String filePath = exportStatisticsDetail(page.getResult());
            msgResult.setData(filePath);
        }

        msgResult.setResult(true);
        return msgResult;
    }

    private String exportStatisticsDetail(List<WorkOverPerson> wopList) {
        String downloadUrl = "";

        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        //表头
        Row rowTitle = sheet.createRow(0);

        String[] titles = new String[]{"序号","申请日期","姓名","工号","部门","开始时间","预计结束时间","实际结束时间","加班时长","加班原因","审批人","审批状态"};

        for (int i=0;i<titles.length;i++) {
            Cell cell = rowTitle.createCell(i);
            cell.setCellValue(titles[i]);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (int i=0;i<wopList.size();i++){
            WorkOverPerson workOverPerson = wopList.get(i);

            Row row = sheet.createRow(i+1);

            int colIndex = 0;

            row.createCell(colIndex++).setCellValue(i+1);
            if(workOverPerson.getCreateTime() != null) {
                row.createCell(colIndex++).setCellValue(sdf.format(workOverPerson.getCreateTime()));
            }else{
                colIndex++;
            }
            if(workOverPerson.getPersonInfo().getName() != null) {
                row.createCell(colIndex++).setCellValue(workOverPerson.getPersonInfo().getName());
            }else{
                colIndex++;
            }
            if(workOverPerson.getPersonInfo().getJobNumber() != null) {
                row.createCell(colIndex++).setCellValue(workOverPerson.getPersonInfo().getJobNumber());
            }else{
                colIndex++;
            }
            if(workOverPerson.getPersonInfo().getCompanyName() != null) {
                row.createCell(colIndex++).setCellValue(workOverPerson.getPersonInfo().getCompanyName());
            }else{
                colIndex++;
            }
            if(workOverPerson.getWorkOver() != null && workOverPerson.getWorkOver().getStartTime() != null) {
                row.createCell(colIndex++).setCellValue(sdf.format(workOverPerson.getWorkOver().getStartTime()));
            }else{
                colIndex++;
            }
            if(workOverPerson.getWorkOver() != null && workOverPerson.getWorkOver().getEndTime() != null) {
                row.createCell(colIndex++).setCellValue(sdf.format(workOverPerson.getWorkOver().getEndTime()));
            }else{
                colIndex++;
            }
            if(workOverPerson.getFinishTime() != null) {
                row.createCell(colIndex++).setCellValue(sdf.format(workOverPerson.getFinishTime()));
            }else{
                colIndex++;
            }
            if(workOverPerson.getDurationStr() != null) {
                row.createCell(colIndex++).setCellValue(workOverPerson.getDurationStr());
            }else{
                colIndex++;
            }
            if(workOverPerson.getWorkOver() != null && workOverPerson.getWorkOver().getReason() != null) {
                row.createCell(colIndex++).setCellValue(workOverPerson.getWorkOver().getReason());
            }else{
                colIndex++;
            }
            if(workOverPerson.getApprovalPersonName() != null) {
                row.createCell(colIndex++).setCellValue(workOverPerson.getApprovalPersonName());
            }else{
                colIndex++;
            }
            if(workOverPerson.getWorkOver() != null && workOverPerson.getWorkOver().getStatusN() != null) {
                row.createCell(colIndex++).setCellValue(workOverPerson.getWorkOver().getStatusN());
            }else{
                colIndex++;
            }
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMDDHHmmss");

            downloadUrl = OSSUtil.upload(ossConfig,"requestForLeave","加班统计" + sdf2.format(new Date()) + ".xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }

    //分钟转小时
    private String formatTime(int minuteStr) {
        String resultStr = "";

        if (minuteStr != 0) {
            if (minuteStr != 0) {
                if (minuteStr / 60 == 0) {
                    resultStr = minuteStr % 60 + "分";
                } else {
                    if (minuteStr % 60 == 0) {
                        resultStr = minuteStr / 60 + "小时";
                    } else {
                        resultStr = (minuteStr / 60 + "小时" + minuteStr % 60 + "分");
                    }
                }
            } else {
                resultStr = "0时0分";
            }
        } else {
            resultStr = "0时0分";
        }
        return resultStr;
    }

    @PostMapping("updateFinishTime")
    @ApiOperation(value="更新加班完成时间")
    public MessageResult<Integer> updateFinishTime(String day){
        MessageResult<Integer> messageResult = new MessageResult<>();

        try {
            int affectCount = workOverPersonService.updateFinishTime(day);

            //todo 填写具体代码
            messageResult.setData(affectCount);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);

            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @GetMapping("updateBeginTime")
    @ApiOperation(value="更新加班开始时间")
    public MessageResult<Date> updateBeginTime(String workPersonId){
        MessageResult<Date> messageResult = new MessageResult<>();

        try {
            WorkOverPerson workOverPerson = workOverPersonService.get(workPersonId);
            WorkOver workOver = workOverService.get(workOverPerson.getWorkOverId());
            PersonPopedom personPopedom = personPopedomService.get(workOverPerson.getPersonPopedomId());

            if (workOver.getStartTime().before(workOver.getCreateTime())){
                //直接设置实际加班开始时间=申请加班开始时间
                workOverPerson.setBeginTime(workOver.getStartTime());
            }
            else {
                //如果加班开始时间前半小时单天人员有班次，则也设置实际加班开始时间=申请加班开始时间
                DateTime startDay = new DateTime(workOver.getStartTime()).withTimeAtStartOfDay();
                DateTime earlyTime = new DateTime(workOver.getStartTime()).plusMinutes(-30);

                WorkPersonScheduling workPersonScheduling = workPersonSchedulingService.findByPersonIdSchedulingDay(personPopedom.getPersonId(), startDay.toDate());

                if(workPersonScheduling!=null) {
                    String shiftIds = workPersonScheduling.getShiftIds();

                    if(StringUtils.isNotEmpty(shiftIds)){
                        String[] shiftIdArr = shiftIds.split(",");

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

                        boolean exist = false;

                        for (String shiftId : shiftIdArr) {
                            WorkShiftInfo workShiftInfo = workShiftInfoService.get(shiftId);

                            Date workTime = sdf.parse(startDay.toString("yyyy-MM-dd") + " " + workShiftInfo.getWorkTime());
                            Date closingTime = sdf.parse(startDay.toString("yyyy-MM-dd") + " " + workShiftInfo.getClosingTime());

                            if (workTime.compareTo(earlyTime.toDate()) <= 0 && closingTime.compareTo(earlyTime.toDate()) >= 0) {
                                exist = true;
                                break;
                            }
                        }

                        if(exist){
                            //直接设置实际加班开始时间=申请加班开始时间
                            workOverPerson.setBeginTime(workOver.getStartTime());
                        }
                    }
                }
            }

            if (workOverPerson.getBeginTime() != null && workOverPerson.getFinishTime() != null) {
                int minutes = (int) Minutes.minutesBetween(new DateTime(workOverPerson.getBeginTime()), new DateTime(workOverPerson.getFinishTime())).getMinutes();
                workOverPerson.setDuration(minutes);

                int intHours = minutes / 60;
                int intMinutes = minutes % 60;
                workOverPerson.setDurationStr(intHours + "小时" + intMinutes + "分钟");
            }

            workOverPerson.setUpdateTime(new Date());
            workOverPersonService.update(workOverPerson);

            //todo 填写具体代码
            messageResult.setData(workOverPerson.getBeginTime());   
            messageResult.setResult(true);
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);

            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }
}
