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

import com.github.pagehelper.Page;
import com.github.pagehelper.util.StringUtil;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.config.WxConfig;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonPopedom;
import com.jpsoft.shinestar.modules.base.entity.PersonRoleInfo;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonPopedomService;
import com.jpsoft.shinestar.modules.base.service.PersonRoleInfoService;
import com.jpsoft.shinestar.modules.business.dto.UpdatePersonAttendanceDTO;
import com.jpsoft.shinestar.modules.business.service.WorkScheduleAttendanceService;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.business.entity.RequestForLeaveInfo;
import com.jpsoft.shinestar.modules.business.service.RequestForLeaveInfoService;
import com.jpsoft.shinestar.modules.common.utils.*;
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.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
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.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 java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/business/requestForLeave")
public class RequestForLeaveInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private RequestForLeaveInfoService requestForLeaveInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;
    @Autowired
    private PersonRoleInfoService personRoleInfoService;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private WorkScheduleAttendanceService workScheduleAttendanceService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @ApiOperation(value = "请假记录分页")
    @PostMapping(value = "pageList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "classId", value = "所属班级", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "leaveType", value = "请假类型", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "审批状态", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "requestStartTime", value = "请假开始日期", paramType = "form"),
            @ApiImplicitParam(name = "requestEndTime", value = "请假结束日期", paramType = "form"),
            @ApiImplicitParam(name = "auditStartTime", value = "审核开始日期", paramType = "form"),
            @ApiImplicitParam(name = "auditEndTime", value = "审核结束日期", paramType = "form"),
            @ApiImplicitParam(name = "exportXls", value = "导出报表", paramType = "form")
    })
    public MessageResult<Object> pageList(
            String name,
            String classId,
            String leaveType,
            Integer status,
            @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,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date requestStartTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date requestEndTime,
            @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,
            @RequestAttribute String subject) {
        MessageResult<Object> messageResult = new MessageResult<>();

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

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

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

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

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

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

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

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

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

            if (requestEndTime!=null) {
                searchParams.put("requestEndTime", new DateTime(requestEndTime).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 (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);
            }

            searchParams.put("pageIndex", pageIndex);
            searchParams.put("pageSize", pageSize);

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

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

            List<DataDictionary> ddList = dataDictionaryService.findByCatalogName("请假类型");

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

            for (DataDictionary dd : ddList) {
                leaveTypeMap.put(dd.getValue(),dd.getName());
            }

            for (RequestForLeaveInfo target : page) {
                Map<String,Object> map = new HashMap<>();

                map.put("id", target.getId());

                map.put("faceImageUrl",target.getFaceImageUrl());
                map.put("name", target.getStudentName());

                //String leaveTypeN = dataDictionaryService.findNameByCatalogNameAndValue("请假类型",target.getLeaveType());
                map.put("leaveTypeN", leaveTypeMap.get(target.getLeaveType()));

                map.put("statusN", target.getStatusN());

                //身份证号
                map.put("idCard", IdCardUtils.decrypt(target.getIdCard()));

                //班级
                map.put("className", target.getClassName());

                map.put("approvedName", target.getApprovedName());


                //请假时间
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

                String startTimeQuantum = "上午";

                if("1".equals(target.getStartTimeQuantum())){
                    startTimeQuantum = "下午";
                }

                String endTimeQuantum = "上午";

                if("1".equals(target.getEndTimeQuantum())){
                    endTimeQuantum = "下午";
                }

                map.put("startTime",sdf1.format(target.getStartTime()));
                map.put("days",target.getDays());

                int days = differentDaysByMillisecond(target.getStartTime(),target.getEndTime());

                if(days < 1) {
                    if("0".equals(target.getStartTimeQuantum()) && "1".equals(target.getEndTimeQuantum())){
                        //请假一天
                        map.put("time", String.format("%s年%s", new DateTime(target.getStartTime()).getYear(),
                                sdf2.format(target.getStartTime())
                        ));
                    }
                    else{
                        //请假半天
                        map.put("time", String.format("%s年%s", new DateTime(target.getStartTime()).getYear(),
                                sdf2.format(target.getStartTime()) + startTimeQuantum
                        ));
                    }

                }
                else{
                    map.put("time", String.format("%s年%s至%s", new DateTime(target.getStartTime()).getYear(),
                            sdf2.format(target.getStartTime())+ startTimeQuantum,
                            sdf2.format(target.getEndTime())+ endTimeQuantum
                    ));
                }

                //请假理由
                map.put("reason", target.getReason());

                //上传图片
                map.put("imageUrl", target.getImageUrl());

                //申请时间
                map.put("createTime", sdf1.format(target.getCreateTime()));

                //审批意见
                map.put("remark", target.getRemark());

                //审批时间
                if(target.getUpdateTime()!=null) {
                    map.put("updateTime", sdf1.format(target.getUpdateTime()));
                }

                map.put("approvalExplain", target.getApprovalExplain());

                if(target.getApprovedTime()!=null) {
                    map.put("approvedTime", sdf1.format(target.getApprovedTime()));
                }

                mapList.add(map);
            }

            if(exportFlag) {
                String filePath = exportXls(mapList);
                messageResult.setData(filePath);
            }
            else{
                Map<String, Object> dataMap = PojoUtils.pageWrapper(page);
                dataMap.put("data", mapList);
                messageResult.setData(dataMap);
            }

            messageResult.setResult(true);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
        }

        return messageResult;
    }

    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     * @param date1
     * @param date2
     * @return
     */
    public int differentDaysByMillisecond(Date date1,Date date2)
    {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
        return days;
    }


    private String exportXls(List<Map> 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]);
        }

        for (int i=0;i<mapList.size();i++){
            Map<String,Object> map = mapList.get(i);

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

            int colIndex = 0;
            row.createCell(colIndex++).setCellValue(i+1);
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("createTime"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("name"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("idCard"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("className"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("approvedName"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("leaveTypeN"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("statusN"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("time"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("days"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("reason"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("remark"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("updateTime"),""));
        }

        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;
    }



    private String leaveExportXls(List<Map> 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]);
        }

        for (int i=0;i<mapList.size();i++){
            Map<String,Object> map = mapList.get(i);

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

            int colIndex = 0;
            row.createCell(colIndex++).setCellValue(i+1);
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("name"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("jobNumber"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("className"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("leaveTypeN"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("cancelTime"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("approvalPersonIdStr"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("startTime"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("endTime"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("days"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("reason"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("statusN"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("createTime"),""));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

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

            downloadUrl = OSSUtil.upload(ossConfig,"cancelLeave","销假记录.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }


    @ApiOperation(value = "打印")
    @PostMapping(value = "leaveExportXlsPageList")
    public MessageResult<Object> leaveExportXlsPageList(
            String leaveType,String name,String classId,String requestTimeRange,String searchType,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @RequestParam(value = "exportFlag", defaultValue = "false") Boolean exportFlag,
            @RequestAttribute String subject) {

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

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

        List<Map> mapList = getMap(subject, classId, leaveType, name, requestTimeRange, "", pageIndex, pageSize);
        List<Map> mapList2 = getMap(subject, classId, leaveType, name, requestTimeRange, "0", pageIndex, pageSize);
        List<Map> mapList3 = getMap(subject, classId, leaveType, name, requestTimeRange, "1", pageIndex, pageSize);

        totalMapList.add(mapList);
        totalMapList.add(mapList2);
        totalMapList.add(mapList3);

        String downloadUrl = "";

        Workbook workbook = new HSSFWorkbook();

        for (int j=0;j<totalMapList.size();j++) {

            Sheet sheet;

            String[] titles;

            if(j==0){
                sheet = workbook.createSheet("请假中");
                titles = new String[]{"序号","姓名","工号","部门",
                        "请假类型","销假时间","销假审核人","开始时间","结束时间","请假时长","请假事由","审批状态","审核备注","申请时间"};
            }
            else if(j==1){
                sheet = workbook.createSheet("待销假");
                titles = new String[]{"序号","姓名","工号","部门",
                        "请假类型","销假时间","销假审核人","开始时间","结束时间","请假时长","请假事由","审批状态","审核备注","申请时间"};
            }
            else{
                sheet = workbook.createSheet("已销假");
                titles = new String[]{"序号","部门","工号","姓名","请假类型","开始时间","结束时间","请假时长","请假事由","销假时间",
                        "审核备注","销假审核人","审批状态","审批时间","申请时间"};
            }


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

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

            for (int i=0;i<totalMapList.get(j).size();i++){
                Map<String,Object> map = totalMapList.get(j).get(i);

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

                int colIndex = 0;
                row.createCell(colIndex++).setCellValue(i+1);

                if(j==0||j==1){
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("name"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("jobNumber"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("className"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("leaveTypeN"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("cancelTime"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("approvalPersonIdStr"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("startTime"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("endTime"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("days"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("reason"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("statusN"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("approvalExplain"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("createTime"),""));
                }
                else{
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("className"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("jobNumber"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("name"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("leaveTypeN"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("startTime"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("endTime"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("days"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("reason"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("cancelTime"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("approvalExplain"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("approvalPersonIdStr"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("statusN"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("updateTime"),""));
                    row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("createTime"),""));
                }



            }


        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {

            workbook.write(output);

            byte[] buffer = output.toByteArray();

            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            downloadUrl = OSSUtil.upload(ossConfig,"cancelLeave","销假记录.xls",input);

            messageResult.setData(downloadUrl);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
            messageResult.setResult(false);
        }

        return messageResult;

    }



    @ApiOperation(value = "请假记录分页")
    @PostMapping(value = "leavePageList")
    public MessageResult<Object> leavePageList(
            String leaveType,String name,
            String classId,String requestTimeRange,
            String searchType,
            @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 = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @RequestParam(value = "exportFlag", defaultValue = "false") Boolean exportFlag,
            @RequestAttribute String subject) {
        MessageResult<Object> messageResult = new MessageResult<>();

        try {
            User user = userService.get(subject);

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

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

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

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

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

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

            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(companyId)){
                    //后勤1
                    searchParams.put("hqStatus", "1");
                }
                else if("hq2".equals(companyId)){
                    //后勤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 (StringUtil.isNotEmpty(requestTimeRange)) {
                String[] timeRangeArray = requestTimeRange.split(",");
                String startTime = "";
                String endTime = "";
                if (timeRangeArray.length == 1) {
                    startTime = timeRangeArray[0];
                } else if (timeRangeArray.length == 2) {
                    startTime = timeRangeArray[0];
                    endTime = timeRangeArray[1];
                }

                searchParams.put("requestStartTime", startTime);
                searchParams.put("requestEndTime", endTime);
            }

            //searchParams.put("leaveTypeSt", "1");

            if(StringUtils.isNotEmpty(searchType)){
                if(searchType.equals("0")){
                    //待销假
                    searchParams.put("cancelStatus", "0");
                }
                else if(searchType.equals("1")){
                    //已销假
                    searchParams.put("cancelStatus", "1");

                    List<Sort> sortList1 = new ArrayList<>();
                    sortList1.add(new Sort("update_time", "desc"));
                    sortList = sortList1;
                }
            }
            else{
                searchParams.put("cancelStatus", "5");
            }

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

            List<Map> mapList = getMap(subject, classId, leaveType, name, requestTimeRange, searchType, pageIndex, pageSize);

            if(exportFlag) {
                String filePath = leaveExportXls(mapList);
                messageResult.setData(filePath);
            }
            else{

                Map<String, Object> dataMap = PojoUtils.pageWrapper(page);
                dataMap.put("data", mapList);
                messageResult.setData(dataMap);
            }

            messageResult.setResult(true);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
        }

        return messageResult;
    }


    private List<Map> getMap(
            String subject,String classId,String leaveType,String name,String requestTimeRange,String searchType,int pageIndex,int pageSize){
        //当前用户ID
        User user = userService.get(subject);

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

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

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

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

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

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

        if (StringUtil.isNotEmpty(requestTimeRange)) {
            String[] timeRangeArray = requestTimeRange.split(",");
            String startTime = "";
            String endTime = "";
            if (timeRangeArray.length == 1) {
                startTime = timeRangeArray[0];
            } else if (timeRangeArray.length == 2) {
                startTime = timeRangeArray[0];
                endTime = timeRangeArray[1];
            }

            searchParams.put("requestStartTime", startTime);
            searchParams.put("requestEndTime", endTime);
        }

        //searchParams.put("leaveTypeSt", "1");

        if(StringUtils.isNotEmpty(searchType)){
            if(searchType.equals("0")){
                //待销假
                searchParams.put("cancelStatus", "0");
            }
            else if(searchType.equals("1")){
                //已销假
                searchParams.put("cancelStatus", "1");
                List<Sort> sortList1 = new ArrayList<>();
                sortList1.add(new Sort("update_time", "desc"));
                sortList = sortList1;
            }
        }
        else{
            searchParams.put("cancelStatus", "5");
        }

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

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

        List<DataDictionary> ddList = dataDictionaryService.findByCatalogName("请假类型");

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

        for (DataDictionary dd : ddList) {
            leaveTypeMap.put(dd.getValue(),dd.getName());
        }

        for (RequestForLeaveInfo target : page) {
            Map<String,Object> map = new HashMap<>();

            map.put("id", target.getId());

            map.put("faceImageUrl",target.getFaceImageUrl());
            map.put("name", target.getStudentName());

            //String leaveTypeN = dataDictionaryService.findNameByCatalogNameAndValue("请假类型",target.getLeaveType());
            map.put("leaveTypeN", leaveTypeMap.get(target.getLeaveType()));

            map.put("statusN", target.getStatusN());

            String jobNumber ="";
            //工号
            PersonInfo personInfo = personInfoService.get(target.getPersonId());
            if(personInfo!=null){
                jobNumber=personInfo.getJobNumber();
            }

            map.put("jobNumber", jobNumber);



            //请假时长
            map.put("days", target.getDays());

            map.put("status", target.getStatusN());

            //班级
            map.put("className", target.getClassName());

            map.put("approvedName", target.getApprovedName());

            if(StringUtils.isNotEmpty(target.getApprovalPersonIdStr())){
                User userApp = userService.get(target.getApprovalPersonIdStr());

                if(userApp!=null){
                    map.put("approvalPersonIdStr", userApp.getRealName());
                }
            }
            else{
                map.put("approvalPersonIdStr", "");
            }


            //请假时间
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");


            if(target.getStartTime()!=null) {
                map.put("startTime", sdf1.format(target.getStartTime()));
            }
            else{
                map.put("startTime", "");
            }

            if(target.getEndTime()!=null) {
                map.put("endTime", sdf1.format(target.getEndTime()));
            }
            else{
                map.put("endTime", "");
            }

            String startTimeQuantum = "上午";

            if("1".equals(target.getStartTimeQuantum())){
                startTimeQuantum = "下午";
            }

            String endTimeQuantum = "上午";

            if("1".equals(target.getEndTimeQuantum())){
                endTimeQuantum = "下午";
            }

            int days = differentDaysByMillisecond(target.getStartTime(),target.getEndTime());

            if(days < 1) {
                if("0".equals(target.getStartTimeQuantum()) && "1".equals(target.getEndTimeQuantum())){
                    //请假一天
                    map.put("time", String.format("%s年%s", new DateTime(target.getStartTime()).getYear(),
                            sdf2.format(target.getStartTime())
                    ));
                }
                else{
                    //请假半天
                    map.put("time", String.format("%s年%s", new DateTime(target.getStartTime()).getYear(),
                            sdf2.format(target.getStartTime()) + startTimeQuantum
                    ));
                }

            }
            else{
                map.put("time", String.format("%s年%s至%s", new DateTime(target.getStartTime()).getYear(),
                        sdf2.format(target.getStartTime())+ startTimeQuantum,
                        sdf2.format(target.getEndTime())+ endTimeQuantum
                ));
            }

            //请假理由
            map.put("reason", target.getReason());


            map.put("approvalExplain", target.getApprovalExplain());



            //上传图片

            List<String> imageUrlList = new ArrayList<>();

            if(StringUtils.isNotEmpty(target.getImageUrl())){
                String[] imageUrlArray = target.getImageUrl().split(",");
                for (String imageUrl:imageUrlArray) {
                    imageUrlList.add(imageUrl);
                }
            }

            map.put("imageUrlList", imageUrlList);

            //申请时间
            map.put("createTime", sdf1.format(target.getCreateTime()));

            //审批意见
            map.put("remark", target.getRemark());

            //审批时间
            if(target.getUpdateTime()!=null) {
                map.put("updateTime", sdf1.format(target.getUpdateTime()));
            }

            map.put("approvalExplain", target.getApprovalExplain());

            if(target.getApprovedTime()!=null) {
                map.put("approvedTime", sdf1.format(target.getApprovedTime()));
            }

            //销假凭证
            List<String> cancelImagesList = new ArrayList<>();

            if(StringUtils.isNotEmpty(target.getCancelImages())){
                String[] imageUrlArray = target.getCancelImages().split(",");
                for (String imageUrl:imageUrlArray) {
                    cancelImagesList.add(imageUrl);
                }
            }

            map.put("cancelImagesList", cancelImagesList);

            //销假时间
            map.put("cancelTime", sdf1.format(target.getCreateTime()));

            //销假审核人
            map.put("approvedId", target.getApprovedId());

            mapList.add(map);
        }

        return mapList;
    }



    @ApiOperation(value="审核列表")
    @PostMapping("flowList/{id}")
    public MessageResult<Map> flowList(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Map> msgResult = new MessageResult<>();
        List<RequestForLeaveInfo> list = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");

        try {
            RequestForLeaveInfo requestForLeaveInfo = requestForLeaveInfoService.get(id);

            if(StringUtils.isNotEmpty(requestForLeaveInfo.getApprovalPersonIdStr())) {
                String[] personIdStr = requestForLeaveInfo.getApprovalPersonIdStr().split(",");
                String[] statusStr = requestForLeaveInfo.getApprovalStatusStr().split(",");
                String[] timeStr = requestForLeaveInfo.getApprovalTimeStr().split(",");
                String[] contentStr = requestForLeaveInfo.getApprovalContentStr().split(",");
                for (int i = 0; i < personIdStr.length; i++) {
                    RequestForLeaveInfo newRequestForLeaveInfo = new RequestForLeaveInfo();
                    newRequestForLeaveInfo.setApprovedPersonPopedomId(personIdStr[i]);
                    newRequestForLeaveInfo.setStatus(Integer.parseInt(statusStr[i]));
                    newRequestForLeaveInfo.setApprovedTime(simpleDateFormat.parse(timeStr[i]));
                    newRequestForLeaveInfo.setApprovalContentStr(contentStr[i]);
                    list.add(newRequestForLeaveInfo);
                }
            }

            RequestForLeaveInfo newRequestForLeaveInfoLast = new RequestForLeaveInfo();
            newRequestForLeaveInfoLast.setApprovedPersonPopedomId(requestForLeaveInfo.getApprovedPersonPopedomId());
            newRequestForLeaveInfoLast.setStatus(requestForLeaveInfo.getStatus());
            newRequestForLeaveInfoLast.setApprovedTime(requestForLeaveInfo.getApprovedTime());
            newRequestForLeaveInfoLast.setApprovalContentStr(requestForLeaveInfo.getApprovalContentStr());
            list.add(newRequestForLeaveInfoLast);

            for(RequestForLeaveInfo requestForLeave : list){
                //翻译
//                CompanyInfo ci = companyInfoService.get(bo.getPersonCompanyId());
//                bo.setPersonCompanyName(ci.getName());

                String approvalPopedomId = requestForLeave.getApprovedPersonPopedomId();
                PersonPopedom pp = personPopedomService.get(approvalPopedomId);
                if(pp == null){
                    continue;
                }
                PersonRoleInfo pri = personRoleInfoService.get(pp.getPersonRoleId());
                PersonInfo pi = personInfoService.get(pp.getPersonId());

                if(pi == null){
                    continue;
                }
                requestForLeave.setApprovedId(pi.getId());
                requestForLeave.setApprovedName(pi.getName());
                if(pri == null){
                    continue;
                }
            }

            Map<String,Object> map = new HashMap<>();
            map.put("data", list);

            msgResult.setResult(true);
            msgResult.setData(map);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }


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

        try {
            RequestForLeaveInfo requestForLeaveInfo = requestForLeaveInfoService.get(id);

            if (requestForLeaveInfo != null) {
                msgResult.setResult(true);
                msgResult.setData(requestForLeaveInfo);
            } 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<RequestForLeaveInfo> update(@RequestBody RequestForLeaveInfo requestForLeaveInfo,@RequestAttribute String subject){
        MessageResult<RequestForLeaveInfo> msgResult = new MessageResult<>();

        try {
            Date now = new Date();
            requestForLeaveInfo.setUpdateBy(subject);
            requestForLeaveInfo.setUpdateTime(now);
            requestForLeaveInfo.setCancelTime(now);
            requestForLeaveInfo.setApprovalPersonIdStr(subject);

            if(("3").equals(requestForLeaveInfo.getCancelStatus())){
                requestForLeaveInfo.setEnableCancel(true);
            }

            int affectCount = requestForLeaveInfoService.update(requestForLeaveInfo);

            if (affectCount > 0) {

                PersonInfo personInfo = personInfoService.get(requestForLeaveInfo.getPersonId());
                if(personInfo!=null){
                    String firstMessage;
                    String stutas;
                    String stutasN;
                    if(requestForLeaveInfo.getCancelStatus().equals("1")){
                        //同意
                        firstMessage="同意销假";
                        stutas="1";
                        stutasN="同意";
                    }
                    else{
                        //拒绝
                        firstMessage="拒绝销假";
                        stutas="2";
                        stutasN="拒绝";
                    }

                    new Thread(() -> {
                        boolean flag = WechatMessageUtil.sendExamine(personInfo.getOpenId(),firstMessage,personInfo.getName(),stutas,stutasN,"销假",requestForLeaveInfo.getApprovalExplain(),null, wxConfig.getAppId(), wxConfig.getAppSecret());
                    }).start();
                }

                msgResult.setResult(true);
                msgResult.setData(requestForLeaveInfo);
            } 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 {
            RequestForLeaveInfo requestForLeaveInfo = requestForLeaveInfoService.get(id);
            requestForLeaveInfo.setDelFlag(true);
            requestForLeaveInfo.setUpdateBy(subject);
            requestForLeaveInfo.setUpdateTime(new Date());

            int affectCount = requestForLeaveInfoService.update(requestForLeaveInfo);

            if (affectCount > 0) {
                UpdatePersonAttendanceDTO updatePersonAttendanceDTO = new UpdatePersonAttendanceDTO(
                        requestForLeaveInfo.getPersonId(), requestForLeaveInfo.getStartTime(),requestForLeaveInfo.getEndTime());

                rabbitTemplate.convertAndSend("updatePersonAttendanceQueue", updatePersonAttendanceDTO);

                Long personId = requestForLeaveInfo.getPersonId();

                PersonInfo personInfo = personInfoService.get(personId);

                if(personInfo!=null){
                    personInfo.setWorkStatus("1");
                    personInfo.setUpdateBy(subject);
                    personInfo.setUpdateTime(new Date());
                    personInfoService.update(personInfo);
                }

                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;
    }
}
