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.github.pagehelper.Page;
import com.github.pagehelper.util.StringUtil;
import com.jpsoft.shinestar.config.WxConfig;
import com.jpsoft.shinestar.modules.base.dto.ApprovalDTO;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.dto.RequestForLeaveAddDTO;
import com.jpsoft.shinestar.modules.business.dto.RequestForLeaveDetailDto;
import com.jpsoft.shinestar.modules.business.dto.RequestForLeaveInfoDTO;
import com.jpsoft.shinestar.modules.business.entity.AdjustShift;
import com.jpsoft.shinestar.modules.business.entity.AdjustShiftPerson;
import com.jpsoft.shinestar.modules.business.entity.RequestForLeaveInfo;
import com.jpsoft.shinestar.modules.business.service.RequestForLeaveInfoService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.*;
import com.jpsoft.shinestar.modules.sys.entity.DataDictionary;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/mobile/requestForLeave")
@Slf4j
public class RequestForLeaveController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Autowired
    private RequestForLeaveInfoService requestForLeaveInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private ApplicationExamineService applicationExamineService;

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

    @ApiOperation(value = "请假记录分页")
    @PostMapping(value = "pageList")
    public MessageResult<Map> pageList(
            String token,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @RequestAttribute String subject) {
        MessageResult<Map> messageResult = new MessageResult<>();

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

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

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

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

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

            Page<RequestForLeaveInfoDTO> pageDto = new Page<>();

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

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

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

            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
            for (RequestForLeaveInfo requestForLeaveInfo : page) {

                RequestForLeaveInfoDTO requestForLeaveInfoDTO = new RequestForLeaveInfoDTO();

                requestForLeaveInfoDTO.setId(requestForLeaveInfo.getId());

                Date createTime = requestForLeaveInfo.getCreateTime();

                String createTimeStr = "";

                if (createTime != null) {
                    createTimeStr = sdf.format(createTime);
                }

                requestForLeaveInfoDTO.setCreateTime(createTimeStr);

                PersonInfo personInfo = personInfoService.get(requestForLeaveInfo.getPersonId());

                String leaveType = requestForLeaveInfo.getLeaveType();

                String leaveTypeN = "";

                if (StringUtils.isNotBlank(leaveType)) {
                    leaveTypeN = leaveTypeMap.get(leaveType).toString();
                }

                String title = personInfo.getName() + "的" + leaveTypeN + "申请";

                requestForLeaveInfoDTO.setTitle(title);

                requestForLeaveInfoDTO.setStatus(requestForLeaveInfo.getStatus());

                requestForLeaveInfoDTO.setStatusN(TypeNameUtil.getExamineTypeName(requestForLeaveInfo.getStatus().toString()));
                requestForLeaveInfoDTO.setTypeN(TypeNameUtil.getLeaveTypeName(requestForLeaveInfo.getLeaveType()));
                requestForLeaveInfoDTO.setStartTime(DateUtil.format(requestForLeaveInfo.getStartTime(),"yyyy-MM-dd"));
                requestForLeaveInfoDTO.setStartTimeQuantum(requestForLeaveInfo.getStartTimeQuantum());
                requestForLeaveInfoDTO.setEndTime(DateUtil.format(requestForLeaveInfo.getEndTime(),"yyyy-MM-dd"));
                requestForLeaveInfoDTO.setEndTimeQuantum(requestForLeaveInfo.getEndTimeQuantum());
                requestForLeaveInfoDTO.setCancelStatus(requestForLeaveInfo.getCancelStatus());
                requestForLeaveInfoDTO.setCancelStatusN(TypeNameUtil.getExamineTypeName(requestForLeaveInfo.getCancelStatus()));
                requestForLeaveInfoDTO.setCancelTime(DateUtil.format(requestForLeaveInfo.getCancelTime(),"yyyy-MM-dd HH:mm"));
                requestForLeaveInfoDTO.setCancelImages(requestForLeaveInfo.getCancelImages());
                requestForLeaveInfoDTO.setEnableCancel(requestForLeaveInfo.getEnableCancel());
                if (requestForLeaveInfoDTO.getStatus() == 0){
                    requestForLeaveInfoDTO.setMergeStatus("0");
                    requestForLeaveInfoDTO.setMergeStatusN("请假待审核");
                }
                if (requestForLeaveInfoDTO.getStatus() == 3){
                    requestForLeaveInfoDTO.setMergeStatus("3");
                    requestForLeaveInfoDTO.setMergeStatusN("请假已拒绝");
                }
                if (requestForLeaveInfoDTO.getStatus() == 1){
                    if ("5".equals(requestForLeaveInfoDTO.getCancelStatus()) && requestForLeaveInfoDTO.getEnableCancel()){
                        requestForLeaveInfoDTO.setMergeStatus("1");
                        requestForLeaveInfoDTO.setMergeStatusN("销假待提交");
                    }
                    if ("5".equals(requestForLeaveInfoDTO.getCancelStatus()) && !requestForLeaveInfoDTO.getEnableCancel()){
                        requestForLeaveInfoDTO.setMergeStatus("2");
                        requestForLeaveInfoDTO.setMergeStatusN("请假已批准");
                    }
                    if ("0".equals(requestForLeaveInfoDTO.getCancelStatus())){
                        requestForLeaveInfoDTO.setMergeStatus("4");
                        requestForLeaveInfoDTO.setMergeStatusN("销假待审核");
                    }
                    if ("1".equals(requestForLeaveInfoDTO.getCancelStatus())){
                        requestForLeaveInfoDTO.setMergeStatus("5");
                        requestForLeaveInfoDTO.setMergeStatusN("销假已批准");
                    }
                    if ("3".equals(requestForLeaveInfoDTO.getCancelStatus())){
                        requestForLeaveInfoDTO.setMergeStatus("6");
                        requestForLeaveInfoDTO.setMergeStatusN("销假已拒绝");
                    }
                }


                pageDto.add(requestForLeaveInfoDTO);
            }

            pageDto.setPageSize(page.getPageSize());
            pageDto.setTotal(page.getTotal());
            pageDto.setPageNum(page.getPageNum());

            messageResult.setResult(true);
            messageResult.setData(PojoUtils.pageWrapper(pageDto));

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

        return messageResult;
    }

    @ApiOperation(value = "请假类型列表")
    @PostMapping(value = "leaveTypeList")
    public MessageResult<Object> leaveTypeList(String token) {
        MessageResult<Object> messageResult = new MessageResult<>();

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

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

        for (DataDictionary item : ddList) {
            Map<String, String> map = new HashMap<>();
            map.put("value", item.getValue());
            map.put("name", item.getName());

            list.add(map);
        }

        messageResult.setData(list);
        messageResult.setResult(true);

        return messageResult;
    }

    @ApiOperation(value = "审批人列表")
    @PostMapping(value = "approvedList")
    public MessageResult<Object> approvedList(String token, @RequestAttribute String subject) {
        MessageResult<Object> messageResult = new MessageResult<>();

        PersonInfo person = personInfoService.get(Long.parseLong(subject));

        List<Map<String, Object>> list = new ArrayList<>();

        if (person != null) {
            //查询企业管理员
            PersonPopedom personPopedom0 = personPopedomService.get(person.getPopedom());
            PersonRoleInfo personRoleInfo = personRoleInfoService.get(personPopedom0.getPersonRoleId());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(personRoleInfo.getParentId())) {


                List<PersonPopedom> personPopedomList = personPopedomService.findByCompanyIdAndRoleIds(personPopedom0.getCompanyId(), personRoleInfo.getParentId());
                for (PersonPopedom personPopedom : personPopedomList) {
                    PersonInfo personInfo = personInfoService.get(personPopedom.getPersonId());

                    if (personInfo != null && !personInfo.getDelFlag()) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", personInfo.getId());
                        map.put("name", personInfo.getName());
                        list.add(map);
                    }
                }
            }

            // List<PersonPopedom> personPopedomList = personPopedomService.findByCompanyIdAndRoleIds(person.getCompanyId());


        }

        messageResult.setResult(true);
        messageResult.setData(list);

        return messageResult;
    }


    @ApiOperation(value = "提交请假申请")
    @PostMapping(value = "save")
    public MessageResult<Object> save(@RequestBody RequestForLeaveAddDTO requestForLeaveAddDTO, String token, @RequestAttribute String subject) {
        MessageResult<Object> messageResult = new MessageResult<>();

        try {
            PersonInfo person = personInfoService.get(Long.parseLong(subject));

            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());


            PersonPopedom personPopedom1 = personPopedomService.get(requestForLeaveAddDTO.getApprovedPersonPopedomId());

            PersonInfo approvedPerson = personInfoService.get(personPopedom1.getPersonId());
            requestForLeaveAddDTO.setApprovedId(approvedPerson.getId());

            int workOverTime = personPopedom.getWorkOverTime();
            //调休要验证时间
            if ("4".equals(requestForLeaveAddDTO.getLeaveType())) {
                if (workOverTime < Double.valueOf(requestForLeaveAddDTO.getDays()) * 8) {
                    throw new Exception("申请时间大于可调休时间");
                }
            }


            RequestForLeaveInfo target = new RequestForLeaveInfo();
            target.setId(UUID.randomUUID().toString());
            target.setDelFlag(false);
            target.setCreateBy(subject);
            target.setCreateTime(new Date());

            target.setLeaveType(requestForLeaveAddDTO.getLeaveType());
            Date startTime = DateUtil.parse(requestForLeaveAddDTO.getStartTime());
            Date endTime = DateUtil.parse(requestForLeaveAddDTO.getEndTime());

            target.setStartTime(startTime);
            target.setEndTime(endTime);
            target.setStartTimeQuantum(requestForLeaveAddDTO.getStartTimeQuantum());
            target.setEndTimeQuantum(requestForLeaveAddDTO.getEndTimeQuantum());
            target.setReason(requestForLeaveAddDTO.getReason());
            target.setImageUrl(requestForLeaveAddDTO.getImageUrl());
            target.setPersonId(person.getId());
            target.setApprovedId(requestForLeaveAddDTO.getApprovedId());
            target.setApprovedPersonPopedomId(requestForLeaveAddDTO.getApprovedPersonPopedomId());
            target.setStatus(0);
            target.setDays(requestForLeaveAddDTO.getDays());
            target.setPersonPopedomId(personPopedom.getId());

            int affectCount = requestForLeaveInfoService.insert(target);

            if (affectCount > 0) {
                messageResult.setResult(true);
                messageResult.setData(target);

                new Thread(() -> {
                    try {

                        String accessToken = JwtUtil2.createToken(jwtSecret, approvedPerson.getId() + "", DateTime.now().plusHours(30 * 24).toDate());
                        WechatMessageUtil.sendEvenMessage(approvedPerson.getOpenId(), "有一条新的请假信息待审核", person.getName(), target.getId().substring(0, 5), "前往处理", wxConfig.getPortalUrl() + "master/attendance/verifyLeaveInfo?id=" + target.getId() + "&exchange=1&role_id=" + personPopedom1.getId() + "&token=" + accessToken, wxConfig.getAppId(), wxConfig.getAppSecret());

                    } catch (Exception ex) {
                        log.error(ex.getMessage(), ex);
                    }
                }).start();
            } else {
                messageResult.setResult(false);
                messageResult.setMessage("数据库添加失败");
            }

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

        return messageResult;
    }


    @ApiOperation(value = "个人申请请假提交")
    @PostMapping(value = "leaveSubmit")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "leaveType", value = "请假类型（1：事假，2：病假，3：其它，4：调休）", required = true, paramType = "form"),
            @ApiImplicitParam(name = "startTime", value = "请假开始时间", required = true, paramType = "form"),
            @ApiImplicitParam(name = "endTime", value = "请假结束时间", required = true, paramType = "form"),
            @ApiImplicitParam(name = "startTimeQuantum", value = "开始时间段（0：上午，1：下午）", required = true, paramType = "form"),
            @ApiImplicitParam(name = "endTimeQuantum", value = "结束时间段（0：上午，1：下午）", required = true, paramType = "form"),
            @ApiImplicitParam(name = "imageUrl", value = "上传照片", required = true, paramType = "form"),
            @ApiImplicitParam(name = "reason", value = "请假理由", required = true, paramType = "form"),
            @ApiImplicitParam(name = "days", value = "天数", required = true, paramType = "form"),
            @ApiImplicitParam(name = "formId", value = "页面路径", required = true, paramType = "form"),
            @ApiImplicitParam(name = "activityId", value = "步骤id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "draft", value = "状态（0：草稿，1：提交）", required = true, paramType = "form")
    })
    public MessageResult<Map> leaveSubmit(String id,String draft,String leaveType, String startTime, String endTime, String startTimeQuantum,String endTimeQuantum,String imageUrl,String reason,String days,String formId,String activityId,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 ide = requestForLeaveInfoService.leaveSubmit(personPopedom, leaveType,startTime,endTime, startTimeQuantum, endTimeQuantum, imageUrl,reason,days,formId,activityId,draft,id);

            Map<String, Object> map = new HashMap<>();
            map.put("id", ide);
            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 = "cancelLeaveSubmit")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "imageUrl", value = "凭证", required = true, paramType = "form"),
            @ApiImplicitParam(name = "formId", value = "页面路径", required = true, paramType = "form")
    })
    public MessageResult<Map> cancelLeaveSubmit(String id,String imageUrl,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 leaveId = requestForLeaveInfoService.cancelLeaveSubmit(personPopedom, id,imageUrl,formId);

            Map<String, Object> map = new HashMap<>();
            map.put("id", leaveId);
            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 = "requestLeaveDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form")
    })
    public MessageResult<Map> requestLeaveDetail(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());



            //主业务
            RequestForLeaveInfo requestForLeaveInfo = requestForLeaveInfoService.get(id);

            //申请人
         //   PersonPopedom requestForLeavePopedom = personPopedomService.get(requestForLeaveInfo.getPersonPopedomId());
            PersonInfo requestForLeavePerson = personInfoService.get(requestForLeaveInfo.getPersonId());


            Map<String, Object> map = new HashMap<>();
            map.put("name", requestForLeavePerson.getName());
            map.put("faceImageUrl",requestForLeavePerson.getFaceImageUrl());
            map.put("imageUrl", requestForLeaveInfo.getImageUrl());
            map.put("type",requestForLeaveInfo.getLeaveType());
            map.put("typeName",TypeNameUtil.getLeaveTypeName(requestForLeaveInfo.getLeaveType()));
            map.put("status", requestForLeaveInfo.getStatus());
            map.put("statusName", TypeNameUtil.getExamineTypeName(requestForLeaveInfo.getStatus().toString()));
            map.put("startTime", DateUtil.format(requestForLeaveInfo.getStartTime(),"yyyy-MM-dd"));
            map.put("startTimeQuantum",requestForLeaveInfo.getStartTimeQuantum());
            map.put("endTime",DateUtil.format(requestForLeaveInfo.getEndTime(),"yyyy-MM-dd"));
            map.put("endTimeQuantum",requestForLeaveInfo.getEndTimeQuantum());
            map.put("days",requestForLeaveInfo.getDays());
            map.put("reason",requestForLeaveInfo.getReason());
            map.put("createTime",DateUtil.format(requestForLeaveInfo.getCreateTime(),"yyyy-MM-dd HH:mm"));
            map.put("cancelStatus",requestForLeaveInfo.getCancelStatus());
            map.put("cancelStatusN",TypeNameUtil.getExamineTypeName(requestForLeaveInfo.getCancelStatus()));
            String cancelTime = null;
            if (requestForLeaveInfo.getCancelTime() != null){
                cancelTime = DateUtil.format(requestForLeaveInfo.getCancelTime(),"yyyy-MM-dd HH:mm");
            }
            map.put("cancelTime",cancelTime);
            map.put("enableCancel",requestForLeaveInfo.getEnableCancel());
            map.put("cancelImages",requestForLeaveInfo.getCancelImages());


            if (requestForLeaveInfo.getStatus() == 0){
                map.put("mergeStatus","0");
                map.put("mergeStatusN","请假待审核");
            }
            if (requestForLeaveInfo.getStatus() == 3){
                map.put("mergeStatus","3");
                map.put("mergeStatusN","请假已拒绝");
            }
            if (requestForLeaveInfo.getStatus() == 1){
                if ("5".equals(requestForLeaveInfo.getCancelStatus()) && requestForLeaveInfo.getEnableCancel()){
                    map.put("mergeStatus","1");
                    map.put("mergeStatusN","销假待提交");
                }
                if ("5".equals(requestForLeaveInfo.getCancelStatus()) && !requestForLeaveInfo.getEnableCancel()){
                    map.put("mergeStatus","2");
                    map.put("mergeStatusN","请假已批准");
                }
                if ("0".equals(requestForLeaveInfo.getCancelStatus())){
                    map.put("mergeStatus","4");
                    map.put("mergeStatusN","销假待审核");
                }
                if ("1".equals(requestForLeaveInfo.getCancelStatus())){
                    map.put("mergeStatus","5");
                    map.put("mergeStatusN","销假已批准");
                }
                if ("3".equals(requestForLeaveInfo.getCancelStatus())){
                    map.put("mergeStatus","6");
                    map.put("mergeStatusN","销假已拒绝");
                }
            }




            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 = "detail")
    public MessageResult<Object> detail(String id, String token, @RequestAttribute String subject) {
        MessageResult<Object> messageResult = new MessageResult<>();

        try {

            PersonInfo personInfo0 = personInfoService.get(Long.valueOf(subject));
            PersonPopedom personPopedom0 = personPopedomService.get(personInfo0.getPopedom());


            RequestForLeaveInfo requestForLeaveInfo = requestForLeaveInfoService.get(id);

            if (requestForLeaveInfo != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("y年M月d日");

                PersonInfo person = personInfoService.get(requestForLeaveInfo.getPersonId());

                RequestForLeaveDetailDto requestForLeaveDetailDto = new RequestForLeaveDetailDto();

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

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

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

                String leaveType = requestForLeaveInfo.getLeaveType();

                String leaveTypeN = "";

                if (StringUtils.isNotBlank(leaveType)) {
                    leaveTypeN = leaveTypeMap.get(leaveType).toString();
                }

                requestForLeaveDetailDto.setName(person.getName());
                requestForLeaveDetailDto.setPicUrl(person.getFaceImageUrl());
                requestForLeaveDetailDto.setLeaveTypeN(leaveTypeN);
                requestForLeaveDetailDto.setStatus(requestForLeaveInfo.getStatus());
                requestForLeaveDetailDto.setStatusN(requestForLeaveInfo.getStatusN());
                requestForLeaveDetailDto.setIdCard(person.getIdCard());

                String startTime = sdf.format(requestForLeaveInfo.getStartTime());
                String endTime = sdf.format(requestForLeaveInfo.getEndTime());

                requestForLeaveDetailDto.setStartTime(startTime);
                requestForLeaveDetailDto.setEndTime(endTime);
                requestForLeaveDetailDto.setStartTimeQuantum(requestForLeaveInfo.getStartTimeQuantum());
                requestForLeaveDetailDto.setEndTimeQuantum(requestForLeaveInfo.getEndTimeQuantum());
                requestForLeaveDetailDto.setReason(requestForLeaveInfo.getReason());
                requestForLeaveDetailDto.setImageUrl(requestForLeaveInfo.getImageUrl());
                requestForLeaveDetailDto.setCreateTime(requestForLeaveInfo.getCreateTime());


                //审核人
                PersonPopedom personPopedom = personPopedomService.get(requestForLeaveInfo.getApprovedPersonPopedomId());

                PersonInfo approved = null;
                if (personPopedom == null) {
                    approved = personInfoService.get(requestForLeaveInfo.getApprovedId());
                } else {
                    approved = personInfoService.get(personPopedom.getPersonId());
                }
                // PersonInfo approved = personInfoService.get(personPopedom.getPersonId());

                requestForLeaveDetailDto.setApprovedName(approved.getName());
                requestForLeaveDetailDto.setApprovalOpinions(requestForLeaveInfo.getApprovalOpinions());
                requestForLeaveDetailDto.setApprovalExplain(requestForLeaveInfo.getApprovalExplain());

                if (requestForLeaveInfo.getApprovedTime() != null) {
                    String approvedTime = sdf.format(requestForLeaveInfo.getApprovedTime());
                    requestForLeaveDetailDto.setApprovedTime(approvedTime);
                }


                //审批人
                List<String> personPopedomList = null;
                if (org.apache.commons.lang3.StringUtils.isNotBlank(requestForLeaveInfo.getApprovalPersonIdStr())) {
                    personPopedomList = Arrays.asList(requestForLeaveInfo.getApprovalPersonIdStr().split(","));
                }
                //审批时间
                List<String> approvalTimeList = null;
                if (org.apache.commons.lang3.StringUtils.isNotBlank(requestForLeaveInfo.getApprovalTimeStr())) {
                    approvalTimeList = Arrays.asList(requestForLeaveInfo.getApprovalTimeStr().split(","));
                }

                //审批内容
                List<String> approvalContentList = null;
                if (org.apache.commons.lang3.StringUtils.isNotBlank(requestForLeaveInfo.getApprovalContentStr())) {
                    approvalContentList = Arrays.asList(requestForLeaveInfo.getApprovalContentStr().split(","));
                }

                //审批状态
                List<String> statusList = null;
                if (org.apache.commons.lang3.StringUtils.isNotBlank(requestForLeaveInfo.getApprovalStatusStr())) {
                    statusList = Arrays.asList(requestForLeaveInfo.getApprovalStatusStr().split(","));
                }


                List<ApprovalDTO> approvalDTOList = new ArrayList<>();


                if (personPopedomList != null && personPopedomList.size() != 0) {
                    Integer n = personPopedomList.size();

                    for (int i = 0; i < n; i++) {
                        ApprovalDTO approvalDTO = new ApprovalDTO();

                        //审核人
                        PersonPopedom personPopedom1 = personPopedomService.get(personPopedomList.get(i));

                        if (personPopedom1 != null) {


                            PersonInfo personInfo1 = personInfoService.get(personPopedom1.getPersonId());
                            approvalDTO.setName(personInfo1.getName());
                            approvalDTO.setFaceImageUrl(personInfo1.getFaceImageUrl());
                            approvalDTO.setStatus(statusList.get(i));
                            if ("0".equals(statusList.get(i))) {
                                approvalDTO.setStatusN("待审核");
                            }
                            if ("1".equals(statusList.get(i))) {
                                approvalDTO.setStatusN("同意");
                                if (approvalTimeList != null) {
                                    approvalDTO.setApprovalContent(approvalContentList.get(i));
                                    approvalDTO.setTime(approvalTimeList.get(i));
                                }
                            }
                            if ("2".equals(statusList.get(i))) {
                                approvalDTO.setStatusN("拒绝");
                                if (approvalTimeList != null) {
                                    approvalDTO.setApprovalContent(approvalContentList.get(i));
                                    approvalDTO.setTime(approvalTimeList.get(i));
                                }
                            }
                            approvalDTOList.add(approvalDTO);

                        }
                    }
                }

                ApprovalDTO approvalDTO0 = new ApprovalDTO();

                if (approved != null) {
                    approvalDTO0.setName(approved.getName());
                    approvalDTO0.setFaceImageUrl(approved.getFaceImageUrl());
                }

                if (requestForLeaveInfo.getApprovedTime() != null) {
                    approvalDTO0.setTime(DateUtil.format(requestForLeaveInfo.getApprovedTime(), "yyyy-MM-dd HH:mm"));
                }
                approvalDTO0.setStatus(requestForLeaveInfo.getStatus().toString());
                approvalDTO0.setStatusN(requestForLeaveInfo.getStatusN());
                approvalDTO0.setApprovalContent(requestForLeaveInfo.getApprovalExplain());
                approvalDTOList.add(approvalDTO0);


                requestForLeaveDetailDto.setList(approvalDTOList);
                //   requestForLeaveDetailDto.setRemark(businessOut.getRemark());
                //  requestForLeaveDetailDto.setapp(businessOut.getApprovalPersonPopedomId());
                boolean approvalEnable = false;
                if (personPopedom0.getId().equals(requestForLeaveInfo.getApprovedPersonPopedomId())) {
                    approvalEnable = true;
                }

                requestForLeaveDetailDto.setApprovalEnable(approvalEnable);


                messageResult.setResult(true);
                messageResult.setData(requestForLeaveDetailDto);
            } else {
                messageResult.setResult(false);
                messageResult.setMessage("请假记录不存在！");
            }

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

        return messageResult;
    }


    @ApiOperation(value = "请假审批列表")
    @PostMapping(value = "approvedPageList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "是否处理（0：待处理，1：已处理）", dataType = "int", paramType = "query"),
    })
    public MessageResult<Map> approvedPageList(
            @RequestParam(value = "type", defaultValue = "0") int type,
            String token,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @RequestAttribute String subject) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

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

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


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

            Page<RequestForLeaveInfo> page = new Page<>();
            if (type == 0){
                Map<String,Object> searchParams = new HashMap<>();
                searchParams.put("type","0");
                searchParams.put("approvalPersonPopedomId",personPopedom.getId());
                List<Sort> sortList = new ArrayList<>();
                sortList.add(new Sort("a.create_time","desc"));
                page = requestForLeaveInfoService.pageMobileSearch(searchParams,pageIndex,pageSize,true,sortList);


            }else {
                //操作人的公司
                CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());
                List<CompanyInfo> companyInfoList = companyInfoService.findAllCompanyByCode("%"+companyInfo.getId()+"%");
                Map<String,Object> searchParams = new HashMap<>();
                searchParams.put("type","1");
                searchParams.put("inCompanyInfo",companyInfoList);
                List<Sort> sortList = new ArrayList<>();
                sortList.add(new Sort("a.approved_time","desc"));
                page = requestForLeaveInfoService.pageMobileSearch(searchParams,pageIndex,pageSize,true,sortList);
            }

            /*List<PersonRoleInfo> personRoleInfoList = personRoleInfoService.findParentId(personPopedom.getPersonRoleId());

            List<PersonPopedom> totalPersonPopedomList = new ArrayList<>();


            for (PersonRoleInfo personRoleInfo : personRoleInfoList) {
                List<PersonPopedom> personPopedomList = personPopedomService.findByCompanyIdAndRoleIds(personPopedom.getCompanyId(), personRoleInfo.getId());
                totalPersonPopedomList.addAll(personPopedomList);
            }


            List<Long> approvedIdList = new ArrayList<>();

            approvedIdList.add(person.getId());

            List<PersonInfo> personList = new ArrayList<>();

            for (PersonPopedom item : totalPersonPopedomList) {
                PersonInfo temp = personInfoService.get(item.getPersonId());
                if (temp != null) {
                    approvedIdList.add(item.getPersonId());
                    personList.add(temp);
                }
            }*/

            //    searchParams.put("approvedIdList", approvedIdList);


        //    searchParams.put("status", status);


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


            Page<RequestForLeaveInfoDTO> pageDto = new Page<>();

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

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

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

            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
            for (RequestForLeaveInfo requestForLeaveInfo : page) {

                RequestForLeaveInfoDTO requestForLeaveInfoDTO = new RequestForLeaveInfoDTO();

                requestForLeaveInfoDTO.setId(requestForLeaveInfo.getId());

                Date createTime = requestForLeaveInfo.getCreateTime();

                String createTimeStr = "";

                if (createTime != null) {
                    createTimeStr = sdf.format(createTime);
                }

                requestForLeaveInfoDTO.setCreateTime(createTimeStr);

                PersonInfo personInfo = personInfoService.get(requestForLeaveInfo.getPersonId());

                String leaveType = requestForLeaveInfo.getLeaveType();

                String leaveTypeN = "";

                if (StringUtils.isNotBlank(leaveType)) {
                    leaveTypeN = leaveTypeMap.get(leaveType).toString();
                }

                if (personInfo != null) {
                    String title = personInfo.getName() + "的" + leaveTypeN + "申请";
                    requestForLeaveInfoDTO.setPicUrl(personInfo.getFaceImageUrl());
                    requestForLeaveInfoDTO.setTitle(title);
                    requestForLeaveInfoDTO.setName(personInfo.getName());
                }
                requestForLeaveInfoDTO.setTypeN(leaveTypeN);
                requestForLeaveInfoDTO.setStatus(requestForLeaveInfo.getStatus());

                requestForLeaveInfoDTO.setStatusN(requestForLeaveInfo.getStatusN());

                pageDto.add(requestForLeaveInfoDTO);
            }

            pageDto.setPageSize(page.getPageSize());
            pageDto.setTotal(page.getTotal());
            pageDto.setPageNum(page.getPageNum());

            messageResult.setResult(true);
            messageResult.setData(PojoUtils.pageWrapper(pageDto));

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

        return messageResult;
    }


    @ApiOperation(value = "请假审批")
    @PostMapping(value = "approved")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "请假记录ID", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "approvalOpinions", value = "审批意见", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "approvalExplain", value = "意见说明", dataType = "String", paramType = "query"),
    })
    public MessageResult<Object> approved(String id, String approvalOpinions, String approvalExplain, int status, String token, @RequestAttribute String subject) {
        MessageResult<Object> messageResult = new MessageResult<>();

        try {
            //  String[] sz= id.split(",");
            //审核人
            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());


            if (org.apache.commons.lang3.StringUtils.isNotBlank(approvalOpinions)) {
                approvalOpinions = StrUtil.replace(approvalOpinions, ",", "，");
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(approvalExplain)) {
                approvalExplain = StrUtil.replace(approvalExplain, ",", "，");
            }

            requestForLeaveInfoService.approvalRequestForLeave(personInfo, id, approvalOpinions, approvalExplain, status);


            messageResult.setResult(true);

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

        return messageResult;
    }


    @ApiOperation(value = "获取请假实体类")
    @PostMapping(value = "getRequestForLeaveInfo")
    public MessageResult<RequestForLeaveInfo> getRequestForLeaveInfo(String startTime, String token, @RequestAttribute String subject) {
        MessageResult<RequestForLeaveInfo> messageResult = new MessageResult<>();

        try {
            RequestForLeaveInfo requestForLeaveInfo = requestForLeaveInfoService.findByPersonId(Long.parseLong(subject), startTime);

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

        return messageResult;
    }

}
