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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Week;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.domain.Person;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.dto.CompanyAndPersonDTO;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.dto.*;
import com.jpsoft.shinestar.modules.business.entity.*;
import com.jpsoft.shinestar.modules.business.service.*;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.TypeNameUtil;
import com.jpsoft.shinestar.modules.workflow.entity.*;
import com.jpsoft.shinestar.modules.workflow.service.*;
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.omg.CORBA.OBJ_ADAPTER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 墨鱼_mo
 * @date 2021-4-27 15:53
 */
@Slf4j
@RestController
@RequestMapping("/mobile/adjustShiftApi")
@Api(description = "调排班接口")
public class AdjustShiftApiController {

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private PersonCompanyService personCompanyService;

    @Autowired
    private WorkScheduleAttendanceService workScheduleAttendanceService;

    @Autowired
    private TemplateDepartmentService templateDepartmentService;

    @Autowired
    private ProcessTemplateService processTemplateService;

    @Autowired
    private RequestForLeaveInfoService requestForLeaveInfoService;

    @Autowired
    private BusinessOutService businessOutService;

    @Autowired
    private WorkOverPersonService workOverPersonService;

    @Autowired
    private CustomerDiningRecordService customerDiningRecordService;

    @Autowired
    private WorkOverService workOverService;

    @Autowired
    private CarryThingsOutFactoryService carryThingsOutFactoryService;

    @Autowired
    private SupplementWorkService supplementWorkService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private ProcessActivityService processActivityService;

    @Autowired
    private AdjustShiftPersonService adjustShiftPersonService;

    @Autowired
    private ProcessActUserService processActUserService;

    @Autowired
    private PersonRoleInfoService personRoleInfoService;

    @Autowired
    private ProcinstActUserService procinstActUserService;

    @Autowired
    private ProcinstActivityService procinstActivityService;

    @Autowired
    private AdjustShiftService adjustShiftService;

    @Autowired
    private ProcinstService procinstService;

    @Autowired
    private ProcessSetService processSetService;

    @Autowired
    private WorkShiftCompanyService workShiftCompanyService;

    @Autowired
    private WorkPersonSchedulingService workPersonSchedulingService;

    @Autowired
    private WorkShiftInfoService workShiftInfoService;

    @Autowired
    private YearRequestForLeaveInfoService yearRequestForLeaveInfoService;

    @ApiOperation(value = "根据登录人查询自己的排班")
    @PostMapping(value = "ownerShift")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "查询的日期", required = true, paramType = "form"),
    })
    public MessageResult<OwnerShiftDTO> ownerShift(String date, String token, @RequestAttribute String subject) {


        MessageResult<OwnerShiftDTO> messageResult = new MessageResult<>();
        try {

            OwnerShiftDTO ownerShiftDTO = new OwnerShiftDTO();
            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());
            Date dateTime = DateUtil.parse(date, "yyyy-MM-dd HH:mm:ss");
            //年
            int year = DateUtil.year(dateTime);
            //月
            int month = DateUtil.month(dateTime) + 1;
            //日
            int day = DateUtil.dayOfMonth(dateTime);

            WorkPersonScheduling workPersonScheduling = workPersonSchedulingService.findByYearMonthDayPersonId(year, month, day, person.getId());

            if (workPersonScheduling != null) {
                String shifIds = workPersonScheduling.getShiftIds();
                List<String> shiftIdList = Arrays.asList(shifIds.split(","));
                String name = null;
                for (String shiftId : shiftIdList) {
                    WorkShiftInfo workShiftInfo = workShiftInfoService.get(shiftId);
                    String workShiftName = workShiftInfo.getNumber() + "-" + workShiftInfo.getName();
                    if (StringUtils.isBlank(name)) {
                        name = workShiftName;
                    } else {
                        name = name + "," + workShiftName;
                    }

                }

                ownerShiftDTO.setId(workPersonScheduling.getShiftIds());
                ownerShiftDTO.setName(name);
            }

            messageResult.setCode(200);
            messageResult.setResult(true);
            messageResult.setData(ownerShiftDTO);


        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }

        return messageResult;
    }


    @ApiOperation(value = "根据登录人查询自己部门能使用的排班")
    @PostMapping(value = "ownerCompanyShift")
    public MessageResult<Map> ownerCompanyShift(String token, @RequestAttribute String subject, @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());
            CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());

            List<CompanyInfo> companyInfoList = companyInfoService.findAllCompanyByCode(companyInfo.getCode() + "%");
            List<String> companyIdList = Arrays.asList(companyInfo.getCode().split(","));
            if (companyIdList.size() > 0) {
                for (String id : companyIdList) {
                    CompanyInfo companyInfo1 = companyInfoService.get(id);
                    if (!companyInfoList.contains(companyInfo1)) {
                        companyInfoList.add(companyInfo1);
                    }
                }
            }


            Map<String, Object> searchParams = new HashMap<>();
            searchParams.put("inCompanyId", companyInfoList);
            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("b.number_", "asc"));
            Page<WorkShiftCompany> page = workShiftCompanyService.pageSearch(searchParams, pageIndex, 10000, true, sortList);

            List<WorkShiftCompany> workShiftCompanyList = page.getResult();
            List<OwnerShiftDTO> list = new ArrayList<>();
            if (workShiftCompanyList.size() > 0) {
                for (WorkShiftCompany workShiftCompany : workShiftCompanyList) {
                    WorkShiftInfo workShiftInfo = workShiftInfoService.get(workShiftCompany.getShiftId());
                    OwnerShiftDTO ownerShiftDTO = new OwnerShiftDTO();
                    ownerShiftDTO.setId(workShiftInfo.getId());
                    ownerShiftDTO.setName(workShiftInfo.getNumber() + "-" + workShiftInfo.getName() + " " + workShiftInfo.getWorkTime() + "-" + workShiftInfo.getClosingTime());
                    ownerShiftDTO.setWorkTime(workShiftInfo.getWorkTime());
                    ownerShiftDTO.setClosingTime(workShiftInfo.getClosingTime());
                    if (!list.contains(ownerShiftDTO)) {
                        list.add(ownerShiftDTO);
                    }

                }
            }

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

            pageMap.put("recordsTotal", page.getTotal());
            pageMap.put("recordsFiltered", page.getTotal());
            pageMap.put("totalPage", page.getPages());
            pageMap.put("pageNumber", page.getPageNum());
            pageMap.put("pageSize", page.getPageSize());
            pageMap.put("data", list);

            messageResult.setData(pageMap);
            messageResult.setCode(200);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }

        return messageResult;
    }


    @ApiOperation(value = "申请批量补卡选择到时间")
    @PostMapping(value = "allShift")
    public MessageResult<Map> allShift(String token, @RequestAttribute String subject) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());
            CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());

            List<WorkShiftInfo> workShiftInfoList = workShiftInfoService.list();

            List<OwnerShiftDTO> list = new ArrayList<>();
            if (workShiftInfoList.size() > 0) {
                for (WorkShiftInfo workShiftInfo : workShiftInfoList) {
                    OwnerShiftDTO ownerShiftDTO = new OwnerShiftDTO();
                    ownerShiftDTO.setId(workShiftInfo.getId());
                    ownerShiftDTO.setName(workShiftInfo.getNumber() + "-" + workShiftInfo.getName() + " " + workShiftInfo.getWorkTime() + "-" + workShiftInfo.getClosingTime());
                    ownerShiftDTO.setWorkTime(workShiftInfo.getWorkTime());
                    ownerShiftDTO.setClosingTime(workShiftInfo.getClosingTime());
                    if (!list.contains(ownerShiftDTO)) {
                        list.add(ownerShiftDTO);
                    }
                }
            }
            Map<String, Object> pageMap = new HashMap<>();

            pageMap.put("data", list);

            messageResult.setData(pageMap);
            messageResult.setCode(200);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }

        return messageResult;
    }


    @ApiOperation(value = "根据条件获取审核人能使用的模板")
    @PostMapping(value = "processTemplateList")
    public MessageResult<Map> examinePerson(String token, @RequestAttribute String subject, String formId) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());


            if (StringUtils.isBlank(formId)) {
                throw new Exception("缺乏业务关键字");
            }
            List<ProcessTemplate> list = new ArrayList<>();

            List<TemplateDepartment> templateDepartments = templateDepartmentService.findByFormIdDepartmentId(formId, personPopedom.getCompanyId(), personPopedom.getPersonRoleId());
            if (templateDepartments.size() == 0) {
                throw new Exception("您的部门没有相应流程模板");
            }
            for (TemplateDepartment templateDepartment : templateDepartments) {
                ProcessTemplate processTemplate = processTemplateService.get(templateDepartment.getProcessTemplateId());
                if (!list.contains(processTemplate)) {
                    list.add(processTemplate);
                }
            }
            List<ProcessTemplate> list1 =  list.stream()
                    .sorted(Comparator.comparing(ProcessTemplate::getSort))
                    .collect(Collectors.toList());


            Map<String, Object> map = new HashMap<>();
            map.put("list", list1);
            messageResult.setData(map);
            messageResult.setCode(200);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }

        return messageResult;
    }


    @ApiOperation(value = "根据条件获取审核人")
    @PostMapping(value = "examinePerson")
    public MessageResult<Map> examinePerson(String token, @RequestAttribute String subject, String formId,
                                            String processTemplateId, String days, String leaveType) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());

            if (StringUtils.isBlank(formId) && StrUtil.isBlank(processTemplateId)) {
                throw new Exception("缺乏业务关键字");
            }

            if (StrUtil.isBlank(processTemplateId)) {
                List<TemplateDepartment> templateDepartments = templateDepartmentService.findByFormIdDepartmentId(formId, personPopedom.getCompanyId(), personPopedom.getPersonRoleId());
                if (templateDepartments.size() == 0) {
                    throw new Exception("您的部门没有相应流程模板");
                }
                TemplateDepartment templateDepartment = templateDepartments.get(0);
                processTemplateId = templateDepartment.getProcessTemplateId();
            }

            ProcessTemplate processTemplate = processTemplateService.get(processTemplateId);

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

            if(StringUtils.isNotEmpty(days)) {
                conditions.put("day", Double.valueOf(days));
            }

            if(StringUtils.isNotEmpty(leaveType)) {
                conditions.put("leaveType", Double.valueOf(leaveType));
            }

            ExaminePersonDTO examinePersonDTO = processSetService.getExaminePerson(null, processTemplate.getId(), personPopedom, 1, conditions);

            if (StringUtils.isBlank(examinePersonDTO.getPersonNames())) {
                throw new Exception("无对应审核人");
            }

            List<String> nameList = Arrays.asList(examinePersonDTO.getPersonNames().split(","));

            String operation = examinePersonDTO.getOperation();
            if (nameList.size() == 1) {
                operation = null;
            }

            Map<String, Object> map = new HashMap<>();
            map.put("operation", operation);
            map.put("name", examinePersonDTO.getPersonNames());
            map.put("processActivityId", examinePersonDTO.getActivityId());

            messageResult.setData(map);
            messageResult.setCode(200);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }

        return messageResult;
    }


    @ApiOperation(value = "个人申请调班提交")
    @PostMapping(value = "adjustShiftSubmit")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "查询的日期", required = true, paramType = "form"),
            @ApiImplicitParam(name = "shiftIds", value = "班次ids", required = true, paramType = "form"),
            @ApiImplicitParam(name = "remark", value = "备注", required = true, paramType = "form"),
            @ApiImplicitParam(name = "formId", value = "页面路径", required = true, paramType = "form"),
            @ApiImplicitParam(name = "draft", value = "状态（0：草稿，1：提交）", required = true, paramType = "form")
    })
    public MessageResult<Map> adjustShiftSubmit(String ids, String draft, String date, String shiftIds, String remark, String formId, String token, @RequestAttribute String subject) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());


            String id = adjustShiftService.adjustShiftSubmit(personPopedom, date, shiftIds, remark, formId, ids, draft);

            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            messageResult.setData(map);
            messageResult.setCode(200);
            messageResult.setResult(true);


        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }

        return messageResult;
    }

    @ApiOperation(value = "根据id查询审核详情")
    @PostMapping(value = "examineDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form")
    })
    public MessageResult<Map> examineDetail(String id, String token, @RequestAttribute String subject) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());

            //  AdjustShiftPerson adjustShiftPerson = adjustShiftPersonService.get(id);
            //  AdjustShift adjustShift = adjustShiftService.get(adjustShiftPerson.getAdjustShiftId());

            //主流程表
            Procinst procinst = procinstService.findByBusinessKey(id);
            Boolean ownerSubmit = false;

            //调班
            if ("1".equals(procinst.getType())) {
                AdjustShift adjustShift = adjustShiftService.get(procinst.getBusinessKey());
                if (adjustShift.getPersonPopedomId().equals(personPopedom.getId()) && adjustShift.getStatus().equals("0")) {
                    ownerSubmit = true;
                }

            }
            //请假
            if ("2".equals(procinst.getType())) {
                RequestForLeaveInfo requestForLeaveInfo = requestForLeaveInfoService.get(procinst.getBusinessKey());
                if (requestForLeaveInfo.getPersonPopedomId().equals(personPopedom.getId()) && requestForLeaveInfo.getStatus() == 0) {
                    ownerSubmit = true;
                }

            }
            //出差
            if ("3".equals(procinst.getType())) {
                BusinessOut businessOut = businessOutService.get(procinst.getBusinessKey());
                if (businessOut.getPersonPopedomId().equals(personPopedom.getId()) && businessOut.getStatus().equals("0")) {
                    ownerSubmit = true;
                }

            }
            //补卡，批量补卡
            if ("4".equals(procinst.getType()) || "5".equals(procinst.getType())) {
                SupplementWork supplementWork = supplementWorkService.get(procinst.getBusinessKey());
                if (supplementWork.getPersonPopedomId().equals(personPopedom.getId()) && supplementWork.getStatus().equals("0")) {
                    ownerSubmit = true;
                }
            }
            //加班，批量加班
            if ("6".equals(procinst.getType()) || "7".equals(procinst.getType())) {
                WorkOver workOver = workOverService.get(procinst.getBusinessKey());
                if (workOver.getPersonPopedomId().equals(personPopedom.getId()) && workOver.getStatus().equals("0")) {
                    ownerSubmit = true;
                }
            }
            //携物出厂
            if ("8".equals(procinst.getType())) {
                CarryThingsOutFactory carryThingsOutFactory = carryThingsOutFactoryService.get(procinst.getBusinessKey());
                if (carryThingsOutFactory.getPersonPopedomId().equals(personPopedom.getId()) && carryThingsOutFactory.getAuditStatus().equals("0")) {
                    ownerSubmit = true;
                }
            }
            //接待就餐
            if ("9".equals(procinst.getType())) {
                CustomerDiningRecord customerDiningRecord = customerDiningRecordService.get(procinst.getBusinessKey());
                if (customerDiningRecord.getPersonPopedomId().equals(personPopedom.getId()) && customerDiningRecord.getStatus().equals("0")) {
                    ownerSubmit = true;
                }
            }

            //年假
            if ("11".equals(procinst.getType())) {
                YearRequestForLeaveInfo yearRequestForLeaveInfo = yearRequestForLeaveInfoService.get(procinst.getBusinessKey());
                if (yearRequestForLeaveInfo.getPersonPopedomId().equals(personPopedom.getId()) && yearRequestForLeaveInfo.getStatus() == 0) {
                    ownerSubmit = true;
                }
            }


            //查询当前审核步骤
            ProcinstActivity procinstActivity0 = procinstActivityService.findProcinstIdAndStatus(procinst.getId(), "1");
            Boolean allowExamine = false;
            String procinstActUserId = "";
            if (procinstActivity0 != null) {
                List<ProcinstActUser> procinstActUserList = procinstActUserService.findByProcinstActivityIdActionType(procinstActivity0.getId(), "0", "1");
                if (procinstActUserList.size() > 0) {
                    for (ProcinstActUser procinstActUser : procinstActUserList) {
                        if (procinstActUser.getUserId().equals(subject)) {
                            allowExamine = true;
                            procinstActUserId = procinstActUser.getId();
                            break;
                        }
                    }
                }
            }


            List<ProcinstActivity> procinstActivityList = procinstActivityService.findByProcinstId(procinst.getId());

            List<ExamineDetailDTO> examineDetailDTOList = new ArrayList<>();

            for (ProcinstActivity procinstActivity : procinstActivityList) {

                ProcessActivity processActivity = processActivityService.get(procinstActivity.getActivityId());

                ExamineDetailDTO examineDetailDTO = new ExamineDetailDTO();
                examineDetailDTO.setFinishTime(procinstActivity.getFinishTime());
                examineDetailDTO.setAction(procinstActivity.getAction());
                examineDetailDTO.setRemark(procinstActivity.getRemark());
                examineDetailDTO.setOperation(processActivity.getOperation());

                List<ProcessActUser> processActUserList = processActUserService.findItemByActIdAndUserType(processActivity.getId(), "1");
                String source = processActUserList.get(0).getSource();
                String desc = "审核人";
                examineDetailDTO.setSource(source);
                if ("2".equals(source)) {
                    CompanyInfo companyInfo = companyInfoService.get(processActUserList.get(0).getDepartmentId());
                    PersonRoleInfo personRoleInfo = personRoleInfoService.get(processActUserList.get(0).getPersonRoleId());
                    desc = companyInfo.getName() + " " + personRoleInfo.getPersonRoleName();
                }
                if ("3".equals(source)) {
                    desc = "直属领导";
                }

                examineDetailDTO.setDesc(desc);
                examineDetailDTO.setActionName(TypeNameUtil.getActionName("1", procinstActivity.getAction()));


                List<ProcinstActUser> procinstActUserList = procinstActUserService.findByProcinstActivityId(procinstActivity.getId());
                List<ExaminePersonDetailDTO> examinePersonDetailDTOList = new ArrayList<>();
                List<ExaminePersonDetailDTO> ccPersonDetailDTOList = new ArrayList<>();
                if (procinstActUserList.size() > 0) {

                    for (ProcinstActUser procinstActUser : procinstActUserList) {
                        ExaminePersonDetailDTO examinePersonDetailDTO = new ExaminePersonDetailDTO();
                        PersonInfo personInfo = personInfoService.get(Long.parseLong(procinstActUser.getUserId()));
                        examinePersonDetailDTO.setPersonId(personInfo.getId());
                        examinePersonDetailDTO.setFaceImageUrl(personInfo.getFaceImageUrl());
                        examinePersonDetailDTO.setType(procinstActUser.getType());
                        examinePersonDetailDTO.setName(personInfo.getName());
                        examinePersonDetailDTO.setAction(procinstActUser.getAction());
                        examinePersonDetailDTO.setRemark(procinstActUser.getRemark());

                        //审核人
                        if ("1".equals(procinstActUser.getType())) {
                            examinePersonDetailDTOList.add(examinePersonDetailDTO);
                        } else {
                            ccPersonDetailDTOList.add(examinePersonDetailDTO);
                        }

                    }
                }
                examineDetailDTO.setExaminePersonDetailDTOList(examinePersonDetailDTOList);
                examineDetailDTO.setCcPersonDetailDTOList(ccPersonDetailDTOList);

                examineDetailDTOList.add(examineDetailDTO);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("examineList", examineDetailDTOList);
            map.put("allowExamine", allowExamine);
            map.put("ownerSubmit", ownerSubmit);
            map.put("procinstActUserId", procinstActUserId);
            messageResult.setData(map);
            messageResult.setCode(200);
            messageResult.setResult(true);

        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }
        return messageResult;
    }

    @ApiOperation(value = "根据id查询审核详情-后台")
    @PostMapping(value = "examineDetailPortal")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form")
    })
    public MessageResult<Map> examineDetailPortal(String id, @RequestAttribute String subject) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {
            //主流程表
            Procinst procinst = procinstService.findByBusinessKey(id);

            //查询当前审核步骤
            ProcinstActivity procinstActivity0 = procinstActivityService.findProcinstIdAndStatus(procinst.getId(), "1");
            Boolean allowExamine = false;
            String procinstActUserId = "";
            if (procinstActivity0 != null) {
                List<ProcinstActUser> procinstActUserList = procinstActUserService.findByProcinstActivityIdActionType(procinstActivity0.getId(), "0", "1");
                if (procinstActUserList.size() > 0) {
                    for (ProcinstActUser procinstActUser : procinstActUserList) {
                        if (procinstActUser.getUserId().equals(subject)) {
                            allowExamine = true;
                            procinstActUserId = procinstActUser.getId();
                            break;
                        }
                    }
                }
            }


            List<ProcinstActivity> procinstActivityList = procinstActivityService.findByProcinstId(procinst.getId());

            List<ExamineDetailDTO> examineDetailDTOList = new ArrayList<>();

            for (ProcinstActivity procinstActivity : procinstActivityList) {

                ProcessActivity processActivity = processActivityService.get(procinstActivity.getActivityId());

                ExamineDetailDTO examineDetailDTO = new ExamineDetailDTO();
                examineDetailDTO.setFinishTime(procinstActivity.getFinishTime());
                examineDetailDTO.setAction(procinstActivity.getAction());
                examineDetailDTO.setRemark(procinstActivity.getRemark());
                examineDetailDTO.setOperation(processActivity.getOperation());

                List<ProcessActUser> processActUserList = processActUserService.findItemByActIdAndUserType(processActivity.getId(), "1");
                String source = processActUserList.get(0).getSource();
                String desc = "审核人";
                examineDetailDTO.setSource(source);
                if ("2".equals(source)) {
                    CompanyInfo companyInfo = companyInfoService.get(processActUserList.get(0).getDepartmentId());
                    PersonRoleInfo personRoleInfo = personRoleInfoService.get(processActUserList.get(0).getPersonRoleId());
                    desc = companyInfo.getName() + " " + personRoleInfo.getPersonRoleName();
                }
                if ("3".equals(source)) {
                    desc = "直属领导";
                }

                examineDetailDTO.setDesc(desc);
                examineDetailDTO.setActionName(TypeNameUtil.getActionName("1", procinstActivity.getAction()));


                List<ProcinstActUser> procinstActUserList = procinstActUserService.findByProcinstActivityId(procinstActivity.getId());
                List<ExaminePersonDetailDTO> examinePersonDetailDTOList = new ArrayList<>();
                List<ExaminePersonDetailDTO> ccPersonDetailDTOList = new ArrayList<>();
                if (procinstActUserList.size() > 0) {

                    for (ProcinstActUser procinstActUser : procinstActUserList) {
                        ExaminePersonDetailDTO examinePersonDetailDTO = new ExaminePersonDetailDTO();
                        PersonInfo personInfo = personInfoService.get(Long.parseLong(procinstActUser.getUserId()));
                        examinePersonDetailDTO.setPersonId(personInfo.getId());
                        examinePersonDetailDTO.setFaceImageUrl(personInfo.getFaceImageUrl());
                        examinePersonDetailDTO.setType(procinstActUser.getType());
                        examinePersonDetailDTO.setName(personInfo.getName());
                        examinePersonDetailDTO.setAction(procinstActUser.getAction());
                        examinePersonDetailDTO.setRemark(procinstActUser.getRemark());

                        //审核人
                        if ("1".equals(procinstActUser.getType())) {
                            examinePersonDetailDTOList.add(examinePersonDetailDTO);
                        } else {
                            ccPersonDetailDTOList.add(examinePersonDetailDTO);
                        }

                    }
                }
                examineDetailDTO.setExaminePersonDetailDTOList(examinePersonDetailDTOList);
                examineDetailDTO.setCcPersonDetailDTOList(ccPersonDetailDTOList);

                examineDetailDTOList.add(examineDetailDTO);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("examineList", examineDetailDTOList);
            map.put("allowExamine", allowExamine);
            map.put("procinstActUserId", procinstActUserId);
            messageResult.setData(map);
            messageResult.setCode(200);
            messageResult.setResult(true);

        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }
        return messageResult;
    }

    @ApiOperation(value = "根据id查询申请调班详情")
    @PostMapping(value = "adjustShiftDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form")
    })
    public MessageResult<Map> adjustShiftDetail(String id, String token, @RequestAttribute String subject) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());


            //   AdjustShiftPerson adjustShiftPerson = adjustShiftPersonService.get(id);
            //主业务
            AdjustShift adjustShift = adjustShiftService.get(id);
            //子业务表
            List<AdjustShiftPerson> adjustShiftPersonList = adjustShiftPersonService.findByAdjustShiftId(id);
            PersonPopedom adjustPersonPopedom = personPopedomService.get(adjustShift.getPersonPopedomId());
            PersonInfo adjustPerson = personInfoService.get(adjustPersonPopedom.getPersonId());

            //调整前的班次
            // String shifIds = adjustShift.getOldShiftId();
            String shifIds = adjustShiftPersonList.get(0).getOldShiftId();
            List<String> shiftIdList = Arrays.asList(shifIds.split(","));
            String oldShiftName = null;
            for (String shiftId : shiftIdList) {
                WorkShiftInfo workShiftInfo = workShiftInfoService.get(shiftId);
                String workShiftName = workShiftInfo.getNumber() + "-" + workShiftInfo.getName();
                if (StringUtils.isBlank(oldShiftName)) {
                    oldShiftName = workShiftName;
                } else {
                    oldShiftName = oldShiftName + "," + workShiftName;
                }

            }

            //调整后的班次
            //   String newShiftIds = adjustShift.getNewShiftId();

            String newShiftIds = adjustShiftPersonList.get(0).getNewShiftId();
            List<String> newShiftIdList = Arrays.asList(newShiftIds.split(","));
            String newShiftName = null;
            for (String shiftId : newShiftIdList) {
                WorkShiftInfo workShiftInfo = workShiftInfoService.get(shiftId);
                String workShiftName = workShiftInfo.getNumber() + "-" + workShiftInfo.getName();
                if (StringUtils.isBlank(newShiftName)) {
                    newShiftName = workShiftName;
                } else {
                    newShiftName = newShiftName + "," + workShiftName;
                }

            }

            Date adjustTime = DateUtil.parse(adjustShift.getAdjustDate(), "yyyy-MM-dd");


            Map<String, Object> map = new HashMap<>();
            map.put("name", adjustPerson.getName());
            map.put("faceImageUrl", adjustPerson.getFaceImageUrl());
            map.put("status", adjustShift.getStatus());
            map.put("statusName", TypeNameUtil.getExamineTypeName(adjustShift.getStatus()));
            map.put("remark", adjustShift.getRemark());
            Week week = DateUtil.dayOfWeekEnum(adjustTime);
            map.put("adjustDate", DateUtil.format(adjustTime, "yyyy-MM-dd") + " " + week.toChinese());
            map.put("oldShift", oldShiftName);
            map.put("newShift", newShiftName);
            map.put("createTime", DateUtil.format(adjustShift.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            map.put("newShiftIds", newShiftIds);
            messageResult.setData(map);
            messageResult.setCode(200);
            messageResult.setResult(true);

        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }
        return messageResult;
    }

    @ApiOperation(value = "个人调班记录")
    @PostMapping(value = "adjustShiftList")
    public MessageResult<Map> adjustShiftList(String token, @RequestAttribute String subject, @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());

            List<AdjustShiftListDTO> list = new ArrayList<>();
            Map<String, Object> searchParams = new HashMap<>();
            searchParams.put("personPopedomId", personPopedom.getId());
            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("create_time", "desc"));
            Page<AdjustShiftPerson> page = adjustShiftPersonService.pageSearch(searchParams, pageIndex, pageSize, true, sortList);

            List<AdjustShiftPerson> adjustShiftPersonList = page.getResult();
            if (adjustShiftPersonList.size() > 0) {
                for (AdjustShiftPerson adjustShiftPerson : adjustShiftPersonList) {
                    AdjustShift adjustShift = adjustShiftService.get(adjustShiftPerson.getAdjustShiftId());
                    AdjustShiftListDTO adjustShiftListDTO = new AdjustShiftListDTO();
                    adjustShiftListDTO.setId(adjustShiftPerson.getAdjustShiftId());
                    adjustShiftListDTO.setType(adjustShift.getType());
                    adjustShiftListDTO.setTypeName(adjustShiftListDTO.getTypeName(adjustShift.getType()));
                    adjustShiftListDTO.setStatus(adjustShift.getStatus());
                    adjustShiftListDTO.setStatusName(adjustShiftListDTO.getStatusName(adjustShift.getStatus()));
                    adjustShiftListDTO.setAdjustDate(adjustShift.getAdjustDate());
                    adjustShiftListDTO.setSubmitTime(adjustShift.getSubmitTime());
                    list.add(adjustShiftListDTO);
                }
            }


            Map<String, Object> pageMap = new HashMap<>();
            pageMap.put("recordsTotal", page.getTotal());
            pageMap.put("recordsFiltered", page.getTotal());
            pageMap.put("totalPage", page.getPages());
            pageMap.put("pageNumber", page.getPageNum());
            pageMap.put("pageSize", page.getPageSize());
            pageMap.put("data", list);

            messageResult.setData(pageMap);
            messageResult.setCode(200);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }

        return messageResult;
    }


    @ApiOperation(value = "安排调班选择人员时展示的部门")
    @PostMapping(value = "arrangeShiftCompanyList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "对应公司或部门id", required = false, paramType = "form"),
            @ApiImplicitParam(name = "queryDate", value = "时间", required = false, paramType = "form")
    })
    public MessageResult<Map> arrangeShiftCompanyList(String companyId, String batchJob, String token, @RequestAttribute String subject, @DateTimeFormat(pattern = "yyyy-MM-dd") Date queryDate) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());
            CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());

            List<String> companyIds = new ArrayList<>();
            companyIds.add(companyInfo.getId());

            //关联部门的id
            List<String> relationCompanyIds = new ArrayList<>();

            List<String> companyIdList = Arrays.asList(companyInfo.getCode().split(","));
            List<CompanyAndPersonDTO> list = new ArrayList<>();


            if ("1".equals(batchJob)) {
                //用户关联的部门
                List<PersonCompany> personCompanyList = personCompanyService.findByPersonId(person.getId());
                relationCompanyIds = personCompanyList.stream()
                        .map(p -> p.getCompanyId())
                        .collect(Collectors.toList());
                if (relationCompanyIds.contains(companyInfo.getId())) {
                    relationCompanyIds.remove(companyInfo.getId());
                }
                companyIds.addAll(relationCompanyIds);
            }

            if (StringUtils.isBlank(companyId)) {


                for (String id : companyIds) {
                    CompanyInfo companyInfo1 = companyInfoService.get(id);
                    String code = companyInfo1.getCode();
                    List<String> idList = Arrays.asList(code.split(","));
                    CompanyInfo companyInfo2 = companyInfoService.get(idList.get(0));
                    CompanyAndPersonDTO companyAndPersonDTO = new CompanyAndPersonDTO();
                    companyAndPersonDTO.setId(companyInfo2.getId());
                    companyAndPersonDTO.setName(companyInfo2.getName());
                    companyAndPersonDTO.setType("1");
                    if (!list.contains(companyAndPersonDTO)) {
                        list.add(companyAndPersonDTO);
                    }

                }


            } else {
                CompanyInfo companyInfo2 = companyInfoService.get(companyId);

                //查看公司下面是否还有子部门
                List<CompanyInfo> companyInfoList0 = companyInfoService.findByParentId(companyId);
                List<String> companyInfoListId = companyInfoList0.stream()
                        .map(p -> p.getId())
                        .collect(Collectors.toList());




                //如果有子部门那么展示部门
                if (companyInfoList0.size() > 0) {

                    if (!companyIds.contains(companyId)){
                        //选择展开公司的code
                        List<String> companyIdList2 = Arrays.asList(companyInfo2.getCode().split(","));
                        //当前角色所在部门的code集合小于所选公司code集合那么，只展示当前角色所在公司或部门
                        if (companyIdList.size() <= companyIdList2.size()) {
                            List<CompanyInfo> companyInfoList = companyInfoService.findByParentId(companyId);
                            if (companyInfoList.size() > 0) {
                                for (CompanyInfo companyInfo1 : companyInfoList) {
                                    CompanyAndPersonDTO companyAndPersonDTO = new CompanyAndPersonDTO();
                                    companyAndPersonDTO.setId(companyInfo1.getId());
                                    companyAndPersonDTO.setName(companyInfo1.getName());
                                    companyAndPersonDTO.setType("1");
                                    if (!list.contains(companyAndPersonDTO)) {
                                        list.add(companyAndPersonDTO);
                                    }
                                }
                            }

                        } else {
                            int codeSize = companyIdList2.size();
                            String id = companyIdList.get(codeSize);
                            CompanyInfo companyInfo1 = companyInfoService.get(id);
                            CompanyAndPersonDTO companyAndPersonDTO = new CompanyAndPersonDTO();
                            companyAndPersonDTO.setId(companyInfo1.getId());
                            companyAndPersonDTO.setName(companyInfo1.getName());
                            companyAndPersonDTO.setType("1");
                            if (!list.contains(companyAndPersonDTO)) {
                                list.add(companyAndPersonDTO);
                            }
                        }

                        List<String> intersection = companyInfoListId.stream().filter(relationCompanyIds::contains).collect(Collectors.toList());
                        if (intersection.size() > 0) {
                            for (String id : intersection) {
                                CompanyInfo companyInfo1 = companyInfoService.get(id);
                                CompanyAndPersonDTO companyAndPersonDTO = new CompanyAndPersonDTO();
                                companyAndPersonDTO.setId(companyInfo1.getId());
                                companyAndPersonDTO.setName(companyInfo1.getName());
                                companyAndPersonDTO.setType("1");
                                if (!list.contains(companyAndPersonDTO)) {
                                    list.add(companyAndPersonDTO);
                                }

                            }
                        }

                    }else {
                        for (String id : companyInfoListId) {
                            CompanyInfo companyInfo1 = companyInfoService.get(id);
                            CompanyAndPersonDTO companyAndPersonDTO = new CompanyAndPersonDTO();
                            companyAndPersonDTO.setId(companyInfo1.getId());
                            companyAndPersonDTO.setName(companyInfo1.getName());
                            companyAndPersonDTO.setType("1");
                            if (!list.contains(companyAndPersonDTO)) {
                                list.add(companyAndPersonDTO);
                            }

                        }
                    }

                }
                //没有子部门那么展示人员
                else {
                    List<PersonInfo> personInfoList = personInfoService.findByCompanyId(companyId);
                    if (personInfoList.size() > 0) {
                        for (PersonInfo personInfo : personInfoList) {
                            CompanyAndPersonDTO companyAndPersonDTO = new CompanyAndPersonDTO();
                            companyAndPersonDTO.setId(personInfo.getId().toString());
                            companyAndPersonDTO.setName(personInfo.getName());
                            companyAndPersonDTO.setType("2");
                            companyAndPersonDTO.setDesc(personInfo.getJobNumber());

                            if (queryDate != null) {
                                Map<String, Object> searchParams = new HashMap<>();
                                searchParams.put("personId", personInfo.getId());
                                searchParams.put("attendanceDate", DateUtil.format(queryDate, "yyyy-MM-dd"));
                                List<Sort> sortList = new ArrayList<>();
                                sortList.add(new Sort("a.create_time", "desc"));

                                List<WorkScheduleAttendance> workScheduleAttendanceList = workScheduleAttendanceService.listSearch(searchParams, sortList);
                                List<Map<String, Object>> mapList = new ArrayList<>();
                                if (workScheduleAttendanceList.size() > 0) {
                                    for (WorkScheduleAttendance workScheduleAttendance : workScheduleAttendanceList) {
                                        Map<String, Object> data = new HashMap<>();
                                        String time = DateUtil.format(workScheduleAttendance.getRecordTime(), "HH:mm");
                                        String remark = null;
                                        String status = null;
                                        String id = workScheduleAttendance.getId();
                                        String result = null;
                                        String workStatus = workScheduleAttendance.getWorkStatus();

                                        //工作状态：工作
                                        if (!"4".equals(workScheduleAttendance.getWorkStatus())) {
                                            //缺卡
                                            if ("0".equals(workScheduleAttendance.getResult())) {
                                                remark = "缺卡";
                                                status = "0";
                                                result = "0";
                                            }
                                            //有考勤，要区分是机器打卡还是填报打卡
                                            if (!"0".equals(workScheduleAttendance.getResult())) {
                                                //机器打卡
                                                if (StringUtils.isBlank(workScheduleAttendance.getSupplementWorkPersonId())) {
                                                    remark = "正常";
                                                    status = "1";
                                                }
                                                //填报打卡
                                                else {
                                                    remark = "正常";
                                                    status = "3";
                                                }
                                                //考勤正常
                                                if ("1".equals(workScheduleAttendance.getResult())) {
                                                    result = "1";
                                                }
                                                //迟到
                                                if ("2".equals(workScheduleAttendance.getResult())) {
                                                    remark = "迟到";
                                                    result = "2";
                                                }
                                                //早退
                                                if ("3".equals(workScheduleAttendance.getResult())) {
                                                    remark = "早退";
                                                    result = "3";
                                                }


                                            }
                                        }

                                        //工作状态：请假
                                        if ("4".equals(workScheduleAttendance.getWorkStatus())) {
                                            remark = "请假";
                                            status = "2";
                                            result = "5";
                                        }

                                        data.put("time", time);
                                        data.put("remark", remark);
                                        data.put("status", status);
                                        data.put("workStatus", workStatus);
                                        data.put("result", result);
                                        data.put("id", id);

                                        mapList.add(data);
                                    }
                                }
                                companyAndPersonDTO.setList(mapList);
                            }


                            list.add(companyAndPersonDTO);

                        }
                    }
                }
            }


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

            messageResult.setData(map);
            messageResult.setCode(200);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }

        return messageResult;
    }


    @ApiOperation(value = "安排调班选择人员时展示的人员")
    @PostMapping(value = "arrangeShiftPersonList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "对应公司或部门id", required = false, paramType = "form"),
            @ApiImplicitParam(name = "queryDate", value = "时间", required = false, paramType = "form")
    })
    public MessageResult<Map> arrangeShiftPersonList(String companyId, String token, @RequestAttribute String subject, @DateTimeFormat(pattern = "yyyy-MM-dd") Date queryDate) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());
            CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());
            List<String> companyIdList = Arrays.asList(companyInfo.getCode().split(","));
            List<CompanyAndPersonDTO> list = new ArrayList<>();

            CompanyInfo companyInfo2 = companyInfoService.get(companyId);

            //查看公司下面是否还有子部门
            List<CompanyInfo> companyInfoList0 = companyInfoService.findByParentId(companyId);

            if (companyInfoList0.size() > 0) {
                //选择展开公司的code
                List<String> companyIdList2 = Arrays.asList(companyInfo2.getCode().split(","));
                //当前角色所在部门的code集合小于所选公司code集合那么，只展示当前角色所在公司或部门
                if (companyIdList.size() <= companyIdList2.size()) {
                    List<PersonInfo> personInfoList = personInfoService.findByCompanyId(companyId);
                    if (personInfoList.size() > 0) {
                        for (PersonInfo personInfo : personInfoList) {
                            CompanyAndPersonDTO companyAndPersonDTO = new CompanyAndPersonDTO();
                            companyAndPersonDTO.setId(personInfo.getId().toString());
                            companyAndPersonDTO.setName(personInfo.getName());
                            companyAndPersonDTO.setType("2");
                            companyAndPersonDTO.setDesc(personInfo.getJobNumber());

                            if (queryDate != null) {
                                Map<String, Object> searchParams = new HashMap<>();
                                searchParams.put("personId", personInfo.getId());
                                searchParams.put("attendanceDate", DateUtil.format(queryDate, "yyyy-MM-dd"));
                                List<Sort> sortList = new ArrayList<>();
                                sortList.add(new Sort("a.create_time", "desc"));

                                List<WorkScheduleAttendance> workScheduleAttendanceList = workScheduleAttendanceService.listSearch(searchParams, sortList);
                                List<Map<String, Object>> mapList = new ArrayList<>();
                                if (workScheduleAttendanceList.size() > 0) {
                                    for (WorkScheduleAttendance workScheduleAttendance : workScheduleAttendanceList) {
                                        Map<String, Object> data = new HashMap<>();
                                        String time = DateUtil.format(workScheduleAttendance.getRecordTime(), "HH:mm");
                                        String remark = null;
                                        String status = null;
                                        String id = workScheduleAttendance.getId();
                                        String result = null;
                                        String workStatus = workScheduleAttendance.getWorkStatus();

                                        //工作状态：工作
                                        if (!"4".equals(workScheduleAttendance.getWorkStatus())) {
                                            //缺卡
                                            if ("0".equals(workScheduleAttendance.getResult())) {
                                                remark = "缺卡";
                                                status = "0";
                                                result = "0";
                                            }
                                            //有考勤，要区分是机器打卡还是填报打卡
                                            if (!"0".equals(workScheduleAttendance.getResult())) {
                                                //机器打卡
                                                if (StringUtils.isBlank(workScheduleAttendance.getSupplementWorkPersonId())) {
                                                    remark = "正常";
                                                    status = "1";
                                                }
                                                //填报打卡
                                                else {
                                                    remark = "正常";
                                                    status = "3";
                                                }
                                                //考勤正常
                                                if ("1".equals(workScheduleAttendance.getResult())) {
                                                    result = "1";
                                                }
                                                //迟到
                                                if ("2".equals(workScheduleAttendance.getResult())) {
                                                    remark = "迟到";
                                                    result = "2";
                                                }
                                                //早退
                                                if ("3".equals(workScheduleAttendance.getResult())) {
                                                    remark = "早退";
                                                    result = "3";
                                                }


                                            }
                                        }

                                        //工作状态：请假
                                        if ("4".equals(workScheduleAttendance.getWorkStatus())) {
                                            remark = "请假";
                                            status = "2";
                                            result = "5";
                                        }

                                        data.put("time", time);
                                        data.put("remark", remark);
                                        data.put("status", status);
                                        data.put("workStatus", workStatus);
                                        data.put("result", result);
                                        data.put("id", id);

                                        mapList.add(data);
                                    }
                                }
                                companyAndPersonDTO.setList(mapList);
                            }


                            list.add(companyAndPersonDTO);
                        }
                    }

                }
            }


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

            messageResult.setData(map);
            messageResult.setCode(200);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }

        return messageResult;
    }


    @ApiOperation(value = "安排调班提交")
    @PostMapping(value = "arrangeShiftSubmit")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "查询的日期", required = true, paramType = "form"),
            @ApiImplicitParam(name = "personIds", value = "人员", required = true, paramType = "form"),
            @ApiImplicitParam(name = "shiftIds", value = "班次ids", required = true, paramType = "form"),
            @ApiImplicitParam(name = "remark", value = "备注", required = true, paramType = "form")

    })
    public MessageResult<Map> arrangeShiftSubmit(String date, String personIds, String shiftIds, String remark, String token, @RequestAttribute String subject) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());

            String id = adjustShiftService.arrangeShiftSubmit(personPopedom, personIds, date, shiftIds, remark);

            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            messageResult.setData(map);
            messageResult.setCode(200);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }

        return messageResult;
    }

    @ApiOperation(value = "根据id查询安排调班详情")
    @PostMapping(value = "arrangeShiftDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form")
    })
    public MessageResult<Map> arrangeShiftDetail(String id, String token, @RequestAttribute String subject) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());

            String arrangeName = "";

            //   AdjustShiftPerson adjustShiftPerson = adjustShiftPersonService.get(id);
            //主业务
            AdjustShift adjustShift = adjustShiftService.get(id);
            //子业务表
            List<AdjustShiftPerson> adjustShiftPersonList = adjustShiftPersonService.findByAdjustShiftId(id);

            //操作人
            PersonPopedom adjustPersonPopedom = personPopedomService.get(adjustShift.getPersonPopedomId());
            PersonInfo adjustPerson = personInfoService.get(adjustPersonPopedom.getPersonId());

            //新班次
            String newShiftIds = adjustShiftPersonList.get(0).getNewShiftId();
            List<String> newShiftIdList = Arrays.asList(newShiftIds.split(","));
            String newShiftName = null;
            for (String shiftId : newShiftIdList) {
                WorkShiftInfo workShiftInfo = workShiftInfoService.get(shiftId);
                String workShiftName = workShiftInfo.getNumber() + "-" + workShiftInfo.getName();
                if (StringUtils.isBlank(newShiftName)) {
                    newShiftName = workShiftName;
                } else {
                    newShiftName = newShiftName + "," + workShiftName;
                }

            }

            if (adjustShiftPersonList.size() > 0) {
                for (AdjustShiftPerson adjustShiftPerson : adjustShiftPersonList) {
                    PersonPopedom personPopedom1 = personPopedomService.get(adjustShiftPerson.getPersonPopedomId());
                    PersonInfo personInfo = personInfoService.get(personPopedom1.getPersonId());
                    if (StringUtils.isBlank(arrangeName)) {
                        arrangeName = personInfo.getName();
                    } else {
                        arrangeName = arrangeName + "," + personInfo.getName();
                    }
                }
            }


            Date adjustTime = DateUtil.parse(adjustShift.getAdjustDate(), "yyyy-MM-dd");


            Map<String, Object> map = new HashMap<>();
            map.put("name", adjustPerson.getName());
            map.put("arrangeName", arrangeName);
            map.put("type", adjustShift.getType());
            map.put("typeName", TypeNameUtil.getTypeName(adjustShift.getType()));
            map.put("status", adjustShift.getStatus());
            map.put("statusName", TypeNameUtil.getExamineTypeName(adjustShift.getStatus()));
            map.put("remark", adjustShift.getRemark());
            Week week = DateUtil.dayOfWeekEnum(adjustTime);
            map.put("adjustDate", DateUtil.format(adjustTime, "yyyy-MM-dd") + " " + week.toChinese());
            map.put("newShift", newShiftName);
            map.put("createTime", DateUtil.format(adjustShift.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            messageResult.setData(map);
            messageResult.setCode(200);
            messageResult.setResult(true);

        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }
        return messageResult;
    }


    @ApiOperation(value = "安排调班记录")
    @PostMapping(value = "arrangeShiftList")
    public MessageResult<Map> arrangeShiftList(String token, @RequestAttribute String subject, @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());

            List<ArrangeShiftListDTO> list = new ArrayList<>();
            Map<String, Object> searchParams = new HashMap<>();
            searchParams.put("personPopedomId", personPopedom.getId());
            searchParams.put("type", "2");
            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("create_time", "desc"));
            Page<AdjustShift> page = adjustShiftService.pageSearch(searchParams, pageIndex, pageSize, true, sortList);

            List<AdjustShift> adjustShiftList = page.getResult();
            if (adjustShiftList.size() > 0) {
                for (AdjustShift adjustShift : adjustShiftList) {
                    List<AdjustShiftPerson> adjustShiftPersonList = adjustShiftPersonService.findByAdjustShiftId(adjustShift.getId());
                    AdjustShiftPerson adjustShiftPerson = adjustShiftPersonList.get(0);
                    PersonPopedom personPopedom1 = personPopedomService.get(adjustShiftPerson.getPersonPopedomId());
                    PersonInfo personInfo = personInfoService.get(personPopedom1.getPersonId());
                    ArrangeShiftListDTO arrangeShiftListDTO = new ArrangeShiftListDTO();
                    arrangeShiftListDTO.setId(adjustShift.getId());
                    arrangeShiftListDTO.setName(personInfo.getName() + "等" + adjustShiftPersonList.size() + "人");
                    arrangeShiftListDTO.setAdjustDate(adjustShift.getAdjustDate());
                    arrangeShiftListDTO.setSubmitDate(DateUtil.format(adjustShift.getSubmitTime(), "yyyy-MM-dd HH:mm:ss"));
                    arrangeShiftListDTO.setStatus(adjustShift.getStatus());
                    arrangeShiftListDTO.setStatusName(TypeNameUtil.getExamineTypeName(adjustShift.getStatus()));
                    list.add(arrangeShiftListDTO);

                }
            }

            Map<String, Object> pageMap = new HashMap<>();
            pageMap.put("recordsTotal", page.getTotal());
            pageMap.put("recordsFiltered", page.getTotal());
            pageMap.put("totalPage", page.getPages());
            pageMap.put("pageNumber", page.getPageNum());
            pageMap.put("pageSize", page.getPageSize());
            pageMap.put("data", list);

            messageResult.setData(pageMap);
            messageResult.setCode(200);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }

        return messageResult;
    }


    @ApiOperation(value = "撤销申请（未审核完成）")
    @PostMapping(value = "revoke")
    public MessageResult<Map> revoke(String token, @RequestAttribute String subject, String id) {


        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());

            procinstService.revoke(personPopedom, id);

            messageResult.setCode(200);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }

        return messageResult;
    }

}
