package com.mortals.xhx.module.attendance.web;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.module.attendance.model.AttendanceClassQuery;
import com.mortals.xhx.module.attendance.model.AttendanceGroupQuery;
import com.mortals.xhx.module.attendance.model.vo.AttendanceSummaryQuery;
import com.mortals.xhx.module.attendance.service.AttendanceClassService;
import com.mortals.xhx.module.attendance.service.AttendanceGroupService;
import com.mortals.xhx.module.dept.model.DeptQuery;
import com.mortals.xhx.module.dept.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.mortals.framework.model.Context;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.module.attendance.model.AttendanceStatEntity;
import com.mortals.xhx.module.attendance.service.AttendanceStatService;
import org.apache.commons.lang3.ArrayUtils;
import com.mortals.framework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import static com.mortals.framework.ap.SysConstains.*;
/**
*
* 考勤汇总信息
*
* @author zxfei
* @date 2023-04-08
*/
@RestController
@RequestMapping("attendance/stat")
public class AttendanceStatController extends BaseCRUDJsonBodyMappingController<AttendanceStatService,AttendanceStatEntity,Long> {

    @Autowired
    private ParamService paramService;

    @Autowired
    private AttendanceGroupService attendanceGroupService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private ICacheService cacheService;

    @Autowired
    private AttendanceClassService attendanceClassService;

    public AttendanceStatController(){
        super.setModuleDesc( "考勤汇总信息");
    }

    private ExecutorService executorService = Executors.newCachedThreadPool();

    private static String SUMMARY_TASK_KEY ="attendanceSummaryTask:run";

    @Override
    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model,"deptId",deptService.find(new DeptQuery()).stream().collect(Collectors.toMap(x->x.getId().toString(), y->y.getDeptName())));
        this.addDict(model,"groupId",attendanceGroupService.find(new AttendanceGroupQuery()).stream().collect(Collectors.toMap(x->x.getId().toString(), y->y.getGroupName())));
        this.addDict(model,"classId",attendanceClassService.find(new AttendanceClassQuery()).stream().collect(Collectors.toMap(x->x.getId().toString(), y->y.getClassName())));
        super.init(model, context);
    }

    @PostMapping({"summary"})
    @UnAuth
    public Rest<Object> summary(@RequestBody AttendanceSummaryQuery query) {
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        Context context = this.getContext();
        String busiDesc = "执行考勤汇总任务";
        int code=1;
        try {
            String verify = cacheService.get(SUMMARY_TASK_KEY);
            if(StringUtils.isNotEmpty(verify)&&verify.equals("true")){
                throw new AppException("汇总任务正在执行，请勿重复操作");
            }
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    cacheService.setnx(SUMMARY_TASK_KEY,"true",3600);
                    if(StringUtils.isNotEmpty(query.getSummaryTimeStart()) && StringUtils.isNotEmpty(query.getSummaryTimeEnd())){
                        List<String> dateList = getDatesBetween(query.getSummaryTimeStart(),query.getSummaryTimeEnd());
                        for(String day:dateList){
                            AttendanceSummaryQuery temp = new AttendanceSummaryQuery(day);
                            service.doAttendanceSummary(temp);
                        }
                    }else {
                        service.doAttendanceSummary(query);
                    }
                }
            });
            cacheService.setnx(SUMMARY_TASK_KEY,"false",60);
            model.put("message_info","开始执行考勤汇总,请稍后查看");
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }
        ret.setCode(code);
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }

    public static List<String> getDatesBetween(String startDateStr, String endDateStr) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDate = LocalDate.parse(startDateStr, formatter);
        LocalDate endDate = LocalDate.parse(endDateStr, formatter);
        List<String> dates = new ArrayList<>();
        //这里是判断开始日期是否在结束日期之后或者=结束日期
        while (startDate .isBefore(endDate) || startDate .isEqual(endDate)) {
            String add = startDate .format(formatter);
            dates.add(add);
            startDate = startDate .plusDays(1);
        }
        return dates;
    }

    public static void main(String[] args){
        List<String> sss = getDatesBetween("2023-07-28","2023-08-04");
        System.out.println(sss);
    }
}
