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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.entity.WorkScheduleAttendance;
import com.jpsoft.shinestar.modules.business.service.WorkScheduleAttendanceService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import 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.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Slf4j
@RestController
@RequestMapping("/business/workScheduleAttendance/dayStat")
public class WorkScheduleDayStatController {
    @Autowired
    private WorkScheduleAttendanceService workScheduleAttendanceService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private WorkPersonSchedulingService workPersonSchedulingService;

    @Autowired
    private WorkShiftInfoService workShiftInfoService;

    @Autowired
    private WorkOverPersonService workOverPersonService;

    @ApiOperation(value="考勤统计日报表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="companyId",value = "单位编号",required = true,paramType = "form"),
            @ApiImplicitParam(name = "subordinate",value = "是否查询下级单位", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name="name",value = "用户姓名",required = true,paramType = "form"),
            @ApiImplicitParam(name = "startDate",value = "开始时间", required = true,paramType="form"),
            @ApiImplicitParam(name = "endDate",value = "截止时间", required = true,paramType="form"),
            @ApiImplicitParam(name = "subject",value = "subject", required = false,paramType="form")
    })
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(@RequestParam(value="companyId",defaultValue="") String companyId,
                                          @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
                                          @RequestParam(value="name",defaultValue="") String name,
                                          @RequestParam(value="personId",defaultValue="") String personId,
                                          @DateTimeFormat(pattern = "yyyy-MM-dd") Date date,
                                          @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
                                          @RequestParam(value="pageSize",defaultValue="10") int pageSize,
                                          @RequestAttribute String subject){
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            //todo 查询每日考勤
            Map<String, Object> searchParams = new HashMap<>();
            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("a.id_", "asc"));

            if (StringUtils.isNotEmpty(name)) {
                String[] names = name.split(",");
                List nameList = new ArrayList();
                for (String n : names) {
                    nameList.add("%" + n + "%");
                }
                searchParams.put("nameList", nameList);
            }

            if (StringUtils.isNotEmpty(personId)){
                searchParams.put("id", Integer.valueOf(personId));
            }

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

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

            DateTime current = new DateTime(date).withTimeAtStartOfDay();

            Map<String,Object> dataMap = new HashMap<>();
            List<Map> mapList = new ArrayList<>();

            Map<String, WorkShiftInfo> workShiftMap = new HashMap<>();

            for (PersonInfo personInfo : page.getResult()) {
                Map<String,Object> rowMap = new HashMap<>();

                rowMap.put("personId" ,personInfo.getId());
                rowMap.put("personName", personInfo.getName());
                rowMap.put("jobNumber", personInfo.getJobNumber());
                rowMap.put("companyName", personInfo.getCompanyName());

                WorkPersonScheduling workPersonScheduling = workPersonSchedulingService.findByPersonIdSchedulingDay(personInfo.getId(), current.toDate());

                if (workPersonScheduling != null) {
                    //查询班次
                    String shiftIds = workPersonScheduling.getShiftIds();

                    String[] shiftIdArr = shiftIds.split(",");

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

                    List<WorkShiftInfo> shiftList = new ArrayList<>();

                    for (String shiftId : shiftIdArr) {
                        if (!workShiftMap.containsKey(shiftId)) {
                            WorkShiftInfo workShiftInfo = workShiftInfoService.get(shiftId);
                            workShiftMap.put(shiftId, workShiftInfo);
                        }

                        shiftList.add(workShiftMap.get(shiftId));
                    }

                    //查询考勤结果
                    for (WorkShiftInfo workShiftInfo : shiftList) {
                        Map<String, Object> workAttendanceMap = new HashMap<>();

                        if (workShiftInfo.getNumber().equals("0")) {
                            workAttendanceMap.put("number", workShiftInfo.getNumber());
                            workAttendanceMap.put("name", workShiftInfo.getName());
                        } else {
                            workAttendanceMap.put("number", workShiftInfo.getNumber());
                            workAttendanceMap.put("name", workShiftInfo.getName());

                            workAttendanceMap.put("workDayType", workShiftInfo.getWorkDayType());
                            workAttendanceMap.put("workDayTypeN", workShiftInfo.getWorkDayTypeN());
                            workAttendanceMap.put("workTime", workShiftInfo.getWorkTime());

                            WorkScheduleAttendance workBeginAttendance = workScheduleAttendanceService
                                    .findLastByPersonScheduleIdAndClassify(workPersonScheduling.getId(), workShiftInfo.getId(), "1");

                            workAttendanceMap.put("workBeginAttendance", workBeginAttendance);

                            workAttendanceMap.put("closingDayType", workShiftInfo.getClosingDayType());
                            workAttendanceMap.put("closingDayTypeN", workShiftInfo.getClosingDayTypeN());
                            workAttendanceMap.put("closingTime", workShiftInfo.getClosingTime());

                            if(workBeginAttendance!=null) {
                                WorkOverPerson workOverPerson = workOverPersonService.get(workBeginAttendance.getWorkOverPersonId());
                                workBeginAttendance.setWorkOverPerson(workOverPerson);
                            }

                            WorkScheduleAttendance workEndAttendance = workScheduleAttendanceService
                                    .findLastByPersonScheduleIdAndClassify(workPersonScheduling.getId(), workShiftInfo.getId(), "2");

                            workAttendanceMap.put("workEndAttendance", workEndAttendance);

                            if(workEndAttendance!=null) {
                                WorkOverPerson workOverPerson = workOverPersonService.get(workEndAttendance.getWorkOverPersonId());
                                workEndAttendance.setWorkOverPerson(workOverPerson);
                            }
                        }

                        workAttendanceList.add(workAttendanceMap);
                    }

                    rowMap.put("workAttendanceList", workAttendanceList);
                }

                mapList.add(rowMap);
            }

            dataMap.put("recordsTotal",page.getTotal());
            dataMap.put("totalPage",page.getPages());
            dataMap.put("pageNumber",page.getPageNum());
            dataMap.put("pageSize",page.getPageSize());
            dataMap.put("data", mapList);

            messageResult.setData(dataMap);
        }
        catch (Exception ex){
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }
}
