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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.WorkPersonSchedulingService;
import com.jpsoft.shinestar.modules.base.service.WorkShiftInfoService;
import com.jpsoft.shinestar.modules.base.service.impl.WorkPersonSchedulingServiceImpl;
import com.jpsoft.shinestar.modules.business.dto.UpdatePersonAttendanceDTO;
import com.jpsoft.shinestar.modules.business.service.WorkScheduleAttendanceService;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.service.impl.RedisServiceImpl;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
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.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 描述:人员每日班次管理
 */

@RestController
@RequestMapping("/base/workPersonScheduling")
@Api(description = "workPersonScheduling")
public class WorkPersonSchedulingController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WorkPersonSchedulingService workPersonSchedulingService;
    @Autowired
    private PersonInfoService personInfoService;
    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private WorkShiftInfoService workShiftInfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ValueOperations<String,Object> valueOperations;
    @Autowired
    private WorkScheduleAttendanceService workScheduleAttendanceService;
    @Autowired
    RabbitTemplate rabbitTemplate;

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

        WorkPersonScheduling workPersonScheduling = new WorkPersonScheduling();

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

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

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

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

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

        return msgResult;
    }

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

        try {
            WorkPersonScheduling workPersonScheduling = workPersonSchedulingService.get(id);

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

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

        return msgResult;
    }

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

        try {
            workPersonScheduling.setUpdateBy(subject);
            workPersonScheduling.setUpdateTime(new Date());
            
            int affectCount = workPersonSchedulingService.update(workPersonScheduling);

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

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

        return msgResult;
    }

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

        try {
            WorkPersonScheduling workPersonScheduling = workPersonSchedulingService.get(id);
            workPersonScheduling.setDelFlag(true);
            workPersonScheduling.setUpdateBy(subject);
            workPersonScheduling.setUpdateTime(new Date());

            int affectCount = workPersonSchedulingService.update(workPersonScheduling);

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

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

        return msgResult;
    }


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

        try {
            int affectCount = 0;

            for (String id : idList) {
                WorkPersonScheduling workPersonScheduling = workPersonSchedulingService.get(id);
                workPersonScheduling.setDelFlag(true);
                workPersonScheduling.setUpdateBy(subject);
                workPersonScheduling.setUpdateTime(new Date());

                affectCount += workPersonSchedulingService.update(workPersonScheduling);
            }

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

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

        return msgResult;
    }

    @ApiOperation(value="查询人员排班")
    @RequestMapping(value = "findScheduling",method = RequestMethod.POST)
    public Map<String,Object> findScheduling(
            @RequestParam(value="personName",defaultValue="")  String personName,
            @RequestParam(value="queryMonth",defaultValue="")  String queryMonth,
            @RequestParam(value="companyId",defaultValue="")  String companyId,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @RequestParam(name="pageIndex",defaultValue = "1") int pageIndex,
            @RequestParam(name="pageSize",defaultValue = "10") int pageSize,
            @RequestAttribute String subject) throws Exception{

        //当前用户ID
        System.out.println(subject);
        Map<String,Object> dataMap = new HashMap<>();
        try{
            Map<String,Object> searchParams = new HashMap<>();
            if (StringUtils.isNotEmpty(personName)) {
                searchParams.put("name","%" + personName + "%");
            }

            if (StringUtils.isNotEmpty(queryMonth)) {
                searchParams.put("queryMonth",queryMonth);
            }else{
                throw new Exception("请选择查询日期!");
            }

            if (StringUtils.isNotEmpty(companyId)) {
                CompanyInfo companyInfo = companyInfoService.get(companyId);
                if(subordinate){
                    searchParams.put("companyCode", companyInfo.getCode() + "%");
                }
                else {
                    searchParams.put("companyCode", companyInfo.getCode());
                }
            }else{
                searchParams.put("companyCode", "");
            }
            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("b.sort_no","asc"));
            sortList.add(new Sort("a.id_","asc"));
            //用户左边列
            Page<PersonInfo> personInfoPage = personInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
            //头部是月份
            Date queryDate = new SimpleDateFormat("yyyy-MM-dd").parse(queryMonth + "-01");
            Map<String,Object> returnMap = getDayByMonth(queryDate);
            List<Integer> days = (List<Integer>)returnMap.get("days");
            int year = Integer.parseInt(returnMap.get("year").toString());
            int month = Integer.parseInt(returnMap.get("month").toString());

            List<Map<String,Object>> personList = new ArrayList<>();
            List<Map> dayMapList = new ArrayList<>();
            for(int i=0;i<days.size();i++){
                int day = days.get(i);
                Map map = new HashMap();
                map.put("id",i);
                map.put("day",day);
                dayMapList.add(map);
            }

            for(PersonInfo personInfo : personInfoPage.getResult()){
                List<WorkPersonScheduling> workDayList = workPersonSchedulingService.findByPersonIdYearMonth(personInfo.getId(),year,month);
                Map<String,List> dayMap = new HashMap<>();


                for(int i=0;i<days.size();i++){
                    int day = days.get(i);
                    List<String> numberList = new ArrayList<>();
                    numberList.add("无");
                    dayMap.put(String.valueOf(day),numberList);
                }

                for(WorkPersonScheduling wps : workDayList){
                    //dayMap.put(sdf.format(wps.getSchedulingDay()),wps);
                    String shiftNumbers = "";
                    String[] shiftIds = null ;
                    if(wps.getShiftIds() != null){
                        shiftIds = wps.getShiftIds().split(",");
                        for(int i=0;i<shiftIds.length;i++){
                            String shiftId = shiftIds[i];
                            String shiftNumber = (String)valueOperations.get("shift_number_" + shiftId);

                            if(StringUtils.isEmpty(shiftNumber)){
                                shiftNumber = workShiftInfoService.findNumberById(shiftId);
                                valueOperations.set("shift_number_" + shiftId, shiftNumber);
                            }

                            if(i < shiftIds.length - 1) {
                                shiftNumbers += shiftNumber + ",";
                            }else{
                                shiftNumbers += shiftNumber;
                            }
                        }
                    }

                    List<String> numberList = new ArrayList<>();
                    numberList.add(shiftNumbers);
                    dayMap.replace(wps.getDay().toString(),numberList);
                }


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

                mapPerson.put("id",personInfo.getId());
                mapPerson.put("name",personInfo.getName());
                mapPerson.put("companyId",personInfo.getCompanyId());
                mapPerson.put("companyName",personInfo.getCompanyName());
                mapPerson.put("personNumberMap",dayMap);

                personList.add(mapPerson);
            }


            dataMap.put("recordsTotal", personInfoPage.getTotal());
            dataMap.put("totalPage", personInfoPage.getPages());
            dataMap.put("personList", personList);
            dataMap.put("dayList", dayMapList);
        }catch (Exception ex){
            ex.printStackTrace();
            logger.error(ex.getMessage(),ex);
        }

        return dataMap;
    }

    @ApiOperation(value="查询后勤人员排班")
    @RequestMapping(value = "findHqScheduling",method = RequestMethod.POST)
    public Map<String,Object> findHqScheduling(
            @RequestParam(value="personName",defaultValue="")  String personName,
            @RequestParam(value="queryMonth",defaultValue="")  String queryMonth,
            @RequestParam(value="companyId",defaultValue="")  String companyId,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @RequestParam(name="pageIndex",defaultValue = "1") int pageIndex,
            @RequestParam(name="pageSize",defaultValue = "10") int pageSize,
            @RequestAttribute String subject) throws Exception{

        //当前用户ID
        System.out.println(subject);
        Map<String,Object> dataMap = new HashMap<>();
        try{
            Map<String,Object> searchParams = new HashMap<>();
            if (StringUtils.isNotEmpty(personName)) {
                searchParams.put("name","%" + personName + "%");
            }

            if (StringUtils.isNotEmpty(queryMonth)) {
                searchParams.put("queryMonth",queryMonth);
            }else{
                throw new Exception("请选择查询日期!");
            }

            if (StringUtils.isNotEmpty(companyId)) {
                if ("hq1".equals(companyId)) {
                    //外勤1
                    List<CompanyInfo> list1 = companyInfoService.findByClassify("1");
                    searchParams.put("companyInfos", list1);

                    searchParams.put("hqStatus", "1");
                } else if ("hq2".equals(companyId)) {
                    //外勤2
                    List<CompanyInfo> list2 = companyInfoService.findByClassify("2");
                    searchParams.put("companyInfos", list2);

                    searchParams.put("hqStatus", "2");
                } else {
                    CompanyInfo parentCompanyInfo = companyInfoService.get(companyId);
                    String parentCode = parentCompanyInfo.getCode();
                    if (subordinate) {
                        searchParams.put("attendanceCompanyCode", parentCode + "%");
                    } else {
                        searchParams.put("attendanceCompanyCode", parentCode);
                    }

                    searchParams.put("hqStatus", parentCompanyInfo.getClassify());
                }
            } else {
                searchParams.put("querHq", "yes");
            }

            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("b.sort_no","asc"));
            sortList.add(new Sort("a.id_","asc"));
            //用户左边列
            Page<PersonInfo> personInfoPage = personInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
            //头部是月份
            Date queryDate = new SimpleDateFormat("yyyy-MM-dd").parse(queryMonth + "-01");
            Map<String,Object> returnMap = getDayByMonth(queryDate);
            List<Integer> days = (List<Integer>)returnMap.get("days");
            int year = Integer.parseInt(returnMap.get("year").toString());
            int month = Integer.parseInt(returnMap.get("month").toString());

            List<Map<String,Object>> personList = new ArrayList<>();
            List<Map> dayMapList = new ArrayList<>();
            for(int i=0;i<days.size();i++){
                int day = days.get(i);
                Map map = new HashMap();
                map.put("id",i);
                map.put("day",day);
                dayMapList.add(map);
            }

            for(PersonInfo personInfo : personInfoPage.getResult()){
                List<WorkPersonScheduling> workDayList = workPersonSchedulingService.findByPersonIdYearMonth(personInfo.getId(),year,month);
                Map<String,List> dayMap = new HashMap<>();


                for(int i=0;i<days.size();i++){
                    int day = days.get(i);
                    List<String> numberList = new ArrayList<>();
                    numberList.add("无");
                    dayMap.put(String.valueOf(day),numberList);
                }

                for(WorkPersonScheduling wps : workDayList){
                    //dayMap.put(sdf.format(wps.getSchedulingDay()),wps);
                    String shiftNumbers = "";
                    String[] shiftIds = null ;
                    if(wps.getShiftIds() != null){
                        shiftIds = wps.getShiftIds().split(",");
                        for(int i=0;i<shiftIds.length;i++){
                            String shiftId = shiftIds[i];
                            String shiftNumber = (String)valueOperations.get("shift_number_" + shiftId);

                            if(StringUtils.isEmpty(shiftNumber)){
                                shiftNumber = workShiftInfoService.findNumberById(shiftId);
                                valueOperations.set("shift_number_" + shiftId, shiftNumber);
                            }

                            if(i < shiftIds.length - 1) {
                                shiftNumbers += shiftNumber + ",";
                            }else{
                                shiftNumbers += shiftNumber;
                            }
                        }
                    }

                    List<String> numberList = new ArrayList<>();
                    numberList.add(shiftNumbers);
                    dayMap.replace(wps.getDay().toString(),numberList);
                }


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

                mapPerson.put("id",personInfo.getId());
                mapPerson.put("name",personInfo.getName());
                mapPerson.put("companyId",personInfo.getCompanyId());
                mapPerson.put("companyName",personInfo.getCompanyName());
                mapPerson.put("personNumberMap",dayMap);

                personList.add(mapPerson);
            }


            dataMap.put("recordsTotal", personInfoPage.getTotal());
            dataMap.put("totalPage", personInfoPage.getPages());
            dataMap.put("personList", personList);
            dataMap.put("dayList", dayMapList);
        }catch (Exception ex){
            ex.printStackTrace();
            logger.error(ex.getMessage(),ex);
        }

        return dataMap;
    }

    public static Map<String,Object> getDayByMonth(Date queryMonth){
        Map<String,Object> returnMap = new HashMap<>();
        List list = new ArrayList();
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        aCalendar.setTime(queryMonth);
        //aCalendar.set(yearParam,monthParam,1);
        int year = aCalendar.get(Calendar.YEAR);//年份
        int month = aCalendar.get(Calendar.MONTH) + 1;//月份
        int day = aCalendar.getActualMaximum(Calendar.DATE);
        for (int i = 1; i <= day; i++) {
            int aDate=i;
            list.add(aDate);
        }
        returnMap.put("year",year);
        returnMap.put("month",month);
        returnMap.put("days",list);
        return returnMap;
    }

    @ApiOperation(value="排班班次")
    @RequestMapping(value = "changeScheduling",method = RequestMethod.POST)
    public MessageResult<List> changeScheduling(
            @RequestParam(name="companyId",defaultValue = "") String companyId,
            @RequestParam(name="personId",defaultValue = "") String personId,
            String[] schedulingIds,
            @DateTimeFormat(pattern = "yyyy-MM-dd") String startDate,
            @DateTimeFormat(pattern = "yyyy-MM-dd") String endDate,
            @RequestAttribute String subject,
            HttpServletRequest request) throws Exception{
        MessageResult<List> msgResult = new MessageResult<>();

        if(!valueOperations.setIfAbsent("changeScheduling_" + subject,true,3,TimeUnit.SECONDS)){
            throw new Exception("操作过于频繁，请稍后再试!");
        }

        Map<String,Object> searchParams = new HashMap<>();
        if (StringUtils.isNotEmpty(companyId)) {
            CompanyInfo companyInfo = companyInfoService.get(companyId);
            searchParams.put("companyCode", companyInfo.getCode());

        }else{
            throw new Exception("请选择部门");
        }

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("b.sort_no","asc"));
        sortList.add(new Sort("a.id_","asc"));
        //查询部门下人员
        Page<PersonInfo> personInfoPage = personInfoService.pageSearch(searchParams,0,10000,false,sortList);
        List<PersonInfo> personInfoList = personInfoPage.getResult();
        if(StringUtils.isNotEmpty(personId)){
            personInfoList = new ArrayList<>();
            String [] pIds = personId.split(",");
            for(String pId : pIds) {
                PersonInfo personInfo = personInfoService.get(Long.valueOf(pId));
                personInfoList.add(personInfo);
            }
        }

        for(PersonInfo pi : personInfoList){
            //查询需要排班的日期
            List<Date> dateList = getDayByYear(startDate,endDate);
            int num=0;
            for(Date scheDate : dateList){
                //如果num = 数组的长度
                String shiftId = schedulingIds[num];
                if(num == schedulingIds.length-1) {
                    num = 0;
                }else{
                    num ++;
                }
                List<WorkShiftInfo> wsiList = null;
                if(StringUtils.isNotEmpty(shiftId)) {
                    String[] shiftIds =  shiftId.split(";");
                    //String sortShiftIds = Arrays.stream(shiftIds).sorted(Comparator.naturalOrder()).collect(Collectors.joining(","));
                    List<String> shiftIdsList = Arrays.asList(shiftIds);

                    List<String> sortShiftIdsList = workShiftInfoService.sortIdsByNumber(shiftIdsList);
                    //返回排序后参数

                    shiftId = StringUtils.join(sortShiftIdsList,",");
                }

                Calendar calendar = Calendar.getInstance(Locale.CHINA);
                calendar.setTime(scheDate);
                int year = calendar.get(Calendar.YEAR);//年份
                int month = calendar.get(Calendar.MONTH) + 1;//月份
                int day = calendar.get(Calendar.DAY_OF_MONTH);

                //先假删除
                workPersonSchedulingService.deleteByPersonIdSchedulingDay(year,month,day,pi.getId());

                WorkPersonScheduling workPersonScheduling = workPersonSchedulingService.findByYearMonthDayPersonId(year,month,day,pi.getId());
                if(workPersonScheduling == null){
                    workPersonScheduling = new WorkPersonScheduling();
                    workPersonScheduling.setId(UUID.randomUUID().toString());
                    workPersonScheduling.setDelFlag(false);
                    workPersonScheduling.setCreateBy(subject);
                    workPersonScheduling.setCreateTime(new Date());

                    workPersonScheduling.setPersonId(pi.getId());
                    workPersonScheduling.setYear(year);
                    workPersonScheduling.setMonth(month);
                    workPersonScheduling.setDay(day);
                    workPersonScheduling.setSchedulingDay(scheDate);
                    workPersonScheduling.setShiftIds(shiftId);
                    //workPersonScheduling.setShiftNumbers(shiftNumber);

                    workPersonSchedulingService.insert(workPersonScheduling);
                }else{
                    workPersonScheduling.setUpdateBy(subject);
                    workPersonScheduling.setUpdateTime(new Date());

                    workPersonScheduling.setPersonId(pi.getId());
                    workPersonScheduling.setYear(year);
                    workPersonScheduling.setMonth(month);
                    workPersonScheduling.setDay(day);
                    workPersonScheduling.setSchedulingDay(scheDate);
                    workPersonScheduling.setShiftIds(shiftId);
                    //workPersonScheduling.setShiftNumbers(shiftNumber);

                    workPersonSchedulingService.update(workPersonScheduling);
                }

            }
        }
        msgResult.setResult(true);
        return msgResult;
    }

    @ApiOperation(value="后勤排班班次")
    @RequestMapping(value = "changeSchedulingHq",method = RequestMethod.POST)
    public MessageResult<List> changeSchedulingHq(
            @RequestParam(name="companyId",defaultValue = "") String companyId,
            @RequestParam(name="personId",defaultValue = "") String personId,
            String[] schedulingIds,
            @DateTimeFormat(pattern = "yyyy-MM-dd") String startDate,
            @DateTimeFormat(pattern = "yyyy-MM-dd") String endDate,
            @RequestAttribute String subject,
            HttpServletRequest request) throws Exception{
        MessageResult<List> msgResult = new MessageResult<>();

        if(!valueOperations.setIfAbsent("changeScheduling_" + subject,true,3,TimeUnit.SECONDS)){
            throw new Exception("操作过于频繁，请稍后再试!");
        }

        Map<String,Object> searchParams = new HashMap<>();
        if (StringUtils.isNotEmpty(companyId)) {
            if ("hq1".equals(companyId)) {
                //外勤1
                List<CompanyInfo> list1 = companyInfoService.findByClassify("1");
                searchParams.put("companyInfos", list1);

                searchParams.put("hqStatus", "1");
            } else if ("hq2".equals(companyId)) {
                //外勤2
                List<CompanyInfo> list2 = companyInfoService.findByClassify("2");
                searchParams.put("companyInfos", list2);

                searchParams.put("hqStatus", "2");
            } else {
                CompanyInfo parentCompanyInfo = companyInfoService.get(companyId);
                String parentCode = parentCompanyInfo.getCode();
                searchParams.put("attendanceCompanyCode", parentCode);
                searchParams.put("hqStatus", parentCompanyInfo.getClassify());
            }
        } else {
            throw new Exception("请选择部门");
        }

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("b.sort_no","asc"));
        sortList.add(new Sort("a.id_","asc"));
        //查询部门下人员
        Page<PersonInfo> personInfoPage = personInfoService.pageSearch(searchParams,0,10000,false,sortList);
        List<PersonInfo> personInfoList = personInfoPage.getResult();
        if(StringUtils.isNotEmpty(personId)){
            personInfoList = new ArrayList<>();
            String [] pIds = personId.split(",");
            for(String pId : pIds) {
                PersonInfo personInfo = personInfoService.get(Long.valueOf(pId));
                personInfoList.add(personInfo);
            }
        }

        for(PersonInfo pi : personInfoList){
            //查询需要排班的日期
            List<Date> dateList = getDayByYear(startDate,endDate);
            int num=0;
            for(Date scheDate : dateList){
                //如果num = 数组的长度
                String shiftId = schedulingIds[num];
                if(num == schedulingIds.length-1) {
                    num = 0;
                }else{
                    num ++;
                }
                List<WorkShiftInfo> wsiList = null;
                if(StringUtils.isNotEmpty(shiftId)) {
                    String[] shiftIds =  shiftId.split(";");
                    //String sortShiftIds = Arrays.stream(shiftIds).sorted(Comparator.naturalOrder()).collect(Collectors.joining(","));
                    List<String> shiftIdsList = Arrays.asList(shiftIds);

                    List<String> sortShiftIdsList = workShiftInfoService.sortIdsByNumber(shiftIdsList);
                    //返回排序后参数

                    shiftId = StringUtils.join(sortShiftIdsList,",");
                }

                Calendar calendar = Calendar.getInstance(Locale.CHINA);
                calendar.setTime(scheDate);
                int year = calendar.get(Calendar.YEAR);//年份
                int month = calendar.get(Calendar.MONTH) + 1;//月份
                int day = calendar.get(Calendar.DAY_OF_MONTH);

                //先假删除
                workPersonSchedulingService.deleteByPersonIdSchedulingDay(year,month,day,pi.getId());

                WorkPersonScheduling workPersonScheduling = workPersonSchedulingService.findByYearMonthDayPersonId(year,month,day,pi.getId());
                if(workPersonScheduling == null){
                    workPersonScheduling = new WorkPersonScheduling();
                    workPersonScheduling.setId(UUID.randomUUID().toString());
                    workPersonScheduling.setDelFlag(false);
                    workPersonScheduling.setCreateBy(subject);
                    workPersonScheduling.setCreateTime(new Date());

                    workPersonScheduling.setPersonId(pi.getId());
                    workPersonScheduling.setYear(year);
                    workPersonScheduling.setMonth(month);
                    workPersonScheduling.setDay(day);
                    workPersonScheduling.setSchedulingDay(scheDate);
                    workPersonScheduling.setShiftIds(shiftId);
                    //workPersonScheduling.setShiftNumbers(shiftNumber);

                    workPersonSchedulingService.insert(workPersonScheduling);
                }else{
                    workPersonScheduling.setUpdateBy(subject);
                    workPersonScheduling.setUpdateTime(new Date());

                    workPersonScheduling.setPersonId(pi.getId());
                    workPersonScheduling.setYear(year);
                    workPersonScheduling.setMonth(month);
                    workPersonScheduling.setDay(day);
                    workPersonScheduling.setSchedulingDay(scheDate);
                    workPersonScheduling.setShiftIds(shiftId);
                    //workPersonScheduling.setShiftNumbers(shiftNumber);

                    workPersonSchedulingService.update(workPersonScheduling);
                }

            }
        }
        msgResult.setResult(true);
        return msgResult;
    }


    @ApiOperation(value="根据年月日人查班次ID")
    @RequestMapping(value = "findWPSByParameter",method = RequestMethod.POST)
    public MessageResult<WorkPersonScheduling> findShiftIdsByParameter(
            @RequestParam(name="personId",defaultValue = "") String personId,
            @RequestParam(value="queryMonth",defaultValue="")  String queryMonth,
            @RequestParam(name="day",defaultValue = "") String day,
            @RequestAttribute String subject,
            HttpServletRequest request)throws Exception{
        MessageResult<WorkPersonScheduling> msgResult = new MessageResult<>();

        try {
            PersonInfo pi = personInfoService.get(Long.valueOf(personId));
            if(pi == null){
                throw new Exception("未找到用户");
            }

            if (StringUtils.isEmpty(queryMonth)) {
                throw new Exception("未选择日期!");
            }


            //头部是月份
            Date queryDate = new SimpleDateFormat("yyyy-MM-dd").parse(queryMonth + "-01");
            Map<String,Object> returnMap = getDayByMonth(queryDate);
            //List<Integer> days = (List<Integer>)returnMap.get("days");
            int year = Integer.parseInt(returnMap.get("year").toString());
            int month = Integer.parseInt(returnMap.get("month").toString());
            int changeDay = Integer.parseInt(day);

            WorkPersonScheduling wps = workPersonSchedulingService.findByYearMonthDayPersonId(year,month,changeDay,pi.getId());

            msgResult.setResult(true);
            msgResult.setData(wps);
        }catch (Exception ex){
            ex.printStackTrace();
            logger.error(ex.getMessage(),ex);
            msgResult.setResult(false);
            msgResult.setMessage("查询失败");
        }

        return msgResult;
    }

    @ApiOperation(value="单人每日调班")
    @RequestMapping(value = "changePersonShift",method = RequestMethod.POST)
    public MessageResult<String> changePersonShift(
            @RequestParam(name="personId",defaultValue = "") String personId,
            @RequestParam(value="queryMonth",defaultValue="")  String queryMonth,
            @RequestParam(name="day",defaultValue = "") String day,
            @RequestParam(name="shiftId",defaultValue = "") String shiftId,
            @RequestAttribute String subject,
            HttpServletRequest request)throws Exception{
        MessageResult<String> msgResult = new MessageResult<>();

        try {
            if(!valueOperations.setIfAbsent("changePersonShift_" + subject,true,3,TimeUnit.SECONDS)){
                throw new Exception("操作过于频繁，请稍后再试!");
            }

            PersonInfo personInfo = personInfoService.get(Long.valueOf(personId));
            if(personInfo == null){
                throw new Exception("未找到用户");
            }

            if (StringUtils.isEmpty(queryMonth)) {
                throw new Exception("未选择日期!");
            }

            //头部是月份
            Date queryDate = new SimpleDateFormat("yyyy-MM-dd").parse(queryMonth + "-01");
            Map<String,Object> returnMap = getDayByMonth(queryDate);
            //List<Integer> days = (List<Integer>)returnMap.get("days");
            int year = Integer.parseInt(returnMap.get("year").toString());
            int month = Integer.parseInt(returnMap.get("month").toString());
            int changeDay = Integer.parseInt(day);

            //先假删除
            workPersonSchedulingService.deleteByPersonIdSchedulingDay(year,month,changeDay,personInfo.getId());

            if(StringUtils.isEmpty(shiftId)){
                //为空删除
                //throw new Exception("未选择班次!");
                msgResult.setResult(true);
                msgResult.setMessage("操作成功");
                return msgResult;
            }else{
                String[] shiftIds =  shiftId.split(",");
                //String sortShiftIds = Arrays.stream(shiftIds).sorted(Comparator.naturalOrder()).collect(Collectors.joining(","));
                List<String> shiftIdsList = Arrays.asList(shiftIds);

                List<String> sortShiftIdsList = workShiftInfoService.sortIdsByNumber(shiftIdsList);
                //返回排序后参数

                shiftId = StringUtils.join(sortShiftIdsList,",");
            }
            WorkPersonScheduling wps = workPersonSchedulingService.findByYearMonthDayPersonId(year,month,changeDay,personInfo.getId());

            if(wps == null){
                wps = new WorkPersonScheduling();
                wps.setId(UUID.randomUUID().toString());
                wps.setDelFlag(false);
                wps.setCreateBy(subject);
                wps.setCreateTime(new Date());

                wps.setPersonId(personInfo.getId());
                wps.setYear(year);
                wps.setMonth(month);
                wps.setDay(changeDay);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String sdate = queryMonth + "-" + day;

                wps.setSchedulingDay(sdf.parse(sdate));
                wps.setShiftIds(shiftId);

                workPersonSchedulingService.insert(wps);
            }else{
                wps.setUpdateBy(subject);
                wps.setUpdateTime(new Date());

                wps.setShiftIds(shiftId);

                workPersonSchedulingService.update(wps);
            }

            Date now = new Date();

            if (wps.getSchedulingDay().before(now)) {
                DateTime startTime = new DateTime(wps.getSchedulingDay());
                DateTime endTime  = startTime.plusDays(1);

                UpdatePersonAttendanceDTO updatePersonAttendanceDTO = new UpdatePersonAttendanceDTO(wps.getPersonId(),startTime.toDate(),endTime.toDate());

                rabbitTemplate.convertAndSend("updatePersonAttendanceQueue", updatePersonAttendanceDTO);
//                workScheduleAttendanceService.batchUpdate(personInfo.getCompanyId(),null,personInfo.getId(),null,
//                        startTime.toDate(), endTime.toDate(),false);
            }

            msgResult.setResult(true);
            msgResult.setMessage("操作成功");
        }catch (Exception ex){
            ex.printStackTrace();
            logger.error(ex.getMessage(),ex);
            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    public static List<Date> getDayByYear(String timeBegin,String timeEnd){
        List<Date> timeStringList = new ArrayList<>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date begin = sdf.parse(timeBegin);
            Date end = sdf.parse(timeEnd);
            List<Date> lDate = new ArrayList();
            lDate.add(begin);
            Calendar calBegin = Calendar.getInstance();
            // 使用给定的 Date 设置此 Calendar 的时间
            calBegin.setTime(begin);
            Calendar calEnd = Calendar.getInstance();
            // 使用给定的 Date 设置此 Calendar 的时间
            calEnd.setTime(end);
            // 测试此日期是否在指定日期之后
            while (end.after(calBegin.getTime())) {
                // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
                calBegin.add(Calendar.DAY_OF_MONTH, 1);
                lDate.add(calBegin.getTime());
            }
            for (Date datePes : lDate) {
                timeStringList.add(datePes);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return timeStringList;
    }


    @ApiOperation(value="删除重复")
    @RequestMapping(value = "deleteRepeatScheduling",method = RequestMethod.POST)
    public MessageResult<Integer> deleteRepeatScheduling(Long personId){
        MessageResult<Integer> msgResult = new MessageResult<>();
        int count = 0;
        try {
            count = workPersonSchedulingService.findRepeatSchedulingDayByPersonId(personId);
            msgResult.setResult(true);
            msgResult.setData(count);
        }catch (Exception e){
            e.printStackTrace();
            msgResult.setResult(false);
        }
        return msgResult;
    }

    public static void main(String[] args) {
        int count = 0;
        //count = deleteRepeatScheduling(Long.valueOf("49495"));
        System.out.println("已删除的用户多余排班数量为:" + count);
    }

    @ApiOperation(value="批量删除")
    @PostMapping("batchDeleteByMonth")
    public MessageResult<Integer> batchDeleteByMonth(
            String personIds,
            @RequestParam(value="queryMonth",defaultValue="")  String queryMonth,
            @RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            if (StringUtils.isEmpty(queryMonth)) {
                throw new Exception("请选择查询日期!");
            }

            Date queryDate = new SimpleDateFormat("yyyy-MM-dd").parse(queryMonth + "-01");
            Map<String,Object> returnMap = getDayByMonth(queryDate);
            List<Integer> days = (List<Integer>)returnMap.get("days");
            int year = Integer.parseInt(returnMap.get("year").toString());
            int month = Integer.parseInt(returnMap.get("month").toString());
            String[] personList = personIds.split(",");
            for(String personId : personList) {
                List<WorkPersonScheduling> workPersonSchedulingList = workPersonSchedulingService.findByPersonIdYearMonth(Long.valueOf(personId),year,month);

                for (WorkPersonScheduling workPersonScheduling : workPersonSchedulingList) {
                    workPersonScheduling.setDelFlag(true);
                    workPersonScheduling.setUpdateBy(subject);
                    workPersonScheduling.setUpdateTime(new Date());

                    affectCount += workPersonSchedulingService.update(workPersonScheduling);
                }
            }

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

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

        return msgResult;
    }
}
