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.OrderCol;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.busiz.h5.req.AttendSaveReq;
import com.mortals.xhx.busiz.h5.web.ApiWebPerformController;
import com.mortals.xhx.common.code.ErrorStatusEnum;
import com.mortals.xhx.common.code.ProcessStatusEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.attendance.model.*;
import com.mortals.xhx.module.attendance.service.*;
import com.mortals.xhx.module.dept.model.DeptQuery;
import com.mortals.xhx.module.dept.service.DeptService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 org.apache.commons.lang3.ArrayUtils;
import com.mortals.framework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
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/record/error")
public class AttendanceRecordErrorController extends BaseCRUDJsonBodyMappingController<AttendanceRecordErrorService, AttendanceRecordErrorEntity, Long> {

    @Autowired
    private ParamService paramService;

    @Autowired
    private AttendanceGroupService attendanceGroupService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private AttendanceClassService attendanceClassService;

    @Autowired
    private AttendanceClassDetailService classDetailService;

    @Autowired
    private AttendanceRecordService attendanceRecordService;

    @Autowired
    private AttendanceRecordDetailService attendanceRecordDetailService;

    @Autowired
    private AttendanceRecordErrorService errorService;


    public AttendanceRecordErrorController() {
        super.setModuleDesc("考勤打卡记录异常信息");
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model, "errorStatus", ErrorStatusEnum.getEnumMap());
        this.addDict(model, "processStatus", paramService.getParamBySecondOrganize("AttendanceRecordError", "processStatus"));
        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(value = "revokeError")
    public Rest<String> disposeError(@RequestBody AttendanceRecordErrorEntity query) {
        Rest<String> ret = new Rest();
        Context context = this.getContext();
        query.setOpertor(context.getUser().getRealName());
        query.setOperDateTime(new Date());
        query.setProcessStatus(0);
        query.setProcessResult("已撤销处理");
        errorService.update(query);

        DateUtils.convertTime2Str(query.getErrorDateTime().getTime(), DateUtils.P_yyyy_MM_dd);
        AttendanceRecordQuery attendanceRecordQuery = new AttendanceRecordQuery();
        attendanceRecordQuery.setStaffId(query.getStaffId());
        attendanceRecordQuery.setAttendanceDateStart(DateUtils.convertTime2Str(query.getErrorDateTime().getTime(), DateUtils.P_yyyy_MM_dd));
        attendanceRecordQuery.setAttendanceDateEnd(DateUtils.convertTime2Str(query.getErrorDateTime().getTime(), DateUtils.P_yyyy_MM_dd));
        AttendanceRecordEntity attendanceRecordEntity = attendanceRecordService.selectOne(attendanceRecordQuery);
        AttendanceRecordDetailQuery detailQuery = new AttendanceRecordDetailQuery();
        detailQuery.setRecordId(attendanceRecordEntity.getId());
        detailQuery.setShiftsId(query.getShiftsId());
        List<AttendanceRecordDetailEntity> attendanceRecordDetailEntity = attendanceRecordDetailService.find(detailQuery);

        for (AttendanceRecordDetailEntity recordDetailEntity : attendanceRecordDetailEntity) {
            if (query.getGoOrOff().equals("上班")) {
                if (query.getErrorStatus() == 0) {
                    recordDetailEntity.setGoWorkResult(3);
                }
                if (query.getErrorStatus() == 2) {
                    recordDetailEntity.setGoWorkResult(4);
                }
            }
            if (query.getGoOrOff().equals("下班")) {
                if (query.getErrorStatus() == 0) {
                    recordDetailEntity.setOffWorkResult(3);
                }
                if (query.getErrorStatus() == 1) {
                    recordDetailEntity.setOffWorkResult(5);
                }
            }
        }

        return Rest.ok();
    }


    @Override
    protected void saveBefore(AttendanceRecordErrorEntity entity, Map<String, Object> model, Context context) throws AppException {

        for (AttendanceRecordErrorEntity recordErrorEntity : entity.getRecordErrorEntities()) {
            AttendanceRecordErrorEntity updateEntity = new AttendanceRecordErrorEntity();
            updateEntity.setId(recordErrorEntity.getId());
            updateEntity.setProcessStatus(entity.getProcessStatus());
            updateEntity.setGoOffDateTime(null);
            updateEntity.setProcessResult(entity.getProcessResult());
            updateEntity.setOpertor(context.getUser().getRealName());
            updateEntity.setOperDateTime(new Date());
            updateEntity.setRemark(entity.getRemark());
            updateEntity.setUpdateTime(new Date());
            updateEntity.setUpdateUserId(this.getContextUserId(getContext()));
            this.service.update(recordErrorEntity, getContext());
        }
/*
        if(!ObjectUtils.isEmpty(entity.getRecordErrorEntities())){

            this.batchSave(entity.getRecordErrorEntities());
        }
        */

        for (AttendanceRecordErrorEntity item : entity.getRecordErrorEntities()) {
            DateUtils.convertTime2Str(item.getErrorDateTime().getTime(), DateUtils.P_yyyy_MM_dd);
            AttendanceRecordQuery attendanceRecordQuery = new AttendanceRecordQuery();
            attendanceRecordQuery.setStaffId(item.getStaffId());
            attendanceRecordQuery.setAttendanceDateStart(DateUtils.convertTime2Str(item.getErrorDateTime().getTime(), DateUtils.P_yyyy_MM_dd));
            attendanceRecordQuery.setAttendanceDateEnd(DateUtils.convertTime2Str(item.getErrorDateTime().getTime(), DateUtils.P_yyyy_MM_dd));
            AttendanceRecordEntity attendanceRecordEntity = attendanceRecordService.selectOne(attendanceRecordQuery);
            AttendanceRecordDetailQuery detailQuery = new AttendanceRecordDetailQuery();
            detailQuery.setRecordId(attendanceRecordEntity.getId());
            detailQuery.setShiftsId(item.getShiftsId());
            List<AttendanceRecordDetailEntity> attendanceRecordDetailEntity = attendanceRecordDetailService.find(detailQuery);

            for (AttendanceRecordDetailEntity recordDetailEntity : attendanceRecordDetailEntity) {
                Date goWorkDate = recordDetailEntity.getGoWorkDate();
                Date offWorkDate = recordDetailEntity.getOffWorkDate();
                if (item.getProcessResult().contains("正常")) {
                    if (!ObjectUtils.isEmpty(goWorkDate)) {
                        if (goWorkDate.getTime() == item.getGoOffDateTime().getTime()) {
                            recordDetailEntity.setGoWorkResult(1);
                        }
                    } else {
                        if (item.getGoOrOff().equals("上班")) {
                            recordDetailEntity.setGoWorkResult(1);
                        }
                    }
                    if (!ObjectUtils.isEmpty(offWorkDate)) {
                        if (offWorkDate.getTime() == item.getGoOffDateTime().getTime()) {
                            recordDetailEntity.setOffWorkResult(1);
                        }
                    } else {
                        if (item.getGoOrOff().equals("")) {
                            recordDetailEntity.setOffWorkResult(1);
                        }
                    }

                }
                if (item.getProcessResult().contains("早退")) {
                    if (!ObjectUtils.isEmpty(offWorkDate)) {
                        if (offWorkDate.getTime() == item.getGoOffDateTime().getTime()) {
                            recordDetailEntity.setOffWorkResult(5);
                        }
                    } else {
                        if (item.getGoOrOff().equals("下班")) {
                            recordDetailEntity.setOffWorkResult(5);
                        }
                    }

                }
                if (item.getProcessResult().contains("迟到")) {
                    if (!ObjectUtils.isEmpty(goWorkDate)) {
                        if (goWorkDate.getTime() == item.getGoOffDateTime().getTime()) {
                            recordDetailEntity.setGoWorkResult(4);
                        }
                    } else {
                        if (item.getGoOrOff().equals("上班")) {
                            recordDetailEntity.setGoWorkResult(4);
                        }
                    }
                }
                attendanceRecordDetailService.update(recordDetailEntity);
            }
        }
        super.saveBefore(entity, model, context);
    }


    @Override
    protected int saveAfter(AttendanceRecordErrorEntity entity, Map<String, Object> model, Context context) throws AppException {
        if (YesNoEnum.YES.getValue() == entity.getProcessStatus()) {
            //已经处理，根据错误状态提交考勤绩效
            String ruleCode = "";

            if (ErrorStatusEnum.早退.getValue() == entity.getErrorStatus()) {

                //判断时间差定义

                //entity.getErrorStatus()
            }




/*            AttendSaveReq attendSaveReq = new AttendSaveReq();
            attendSaveReq.setAttendanceGroupId(entity.getAttendanceGroupId());
            attendSaveReq.setAttendanceGroupName(entity.getAttendanceGroupName());
            attendSaveReq.setAttendanceDate(entity.getActualAttendanceDateTime());
            attendSaveReq.setErrorTime(entity.getErrorDateTime());
            attendSaveReq.setGoOffTimeStr(entity.getGoOrOff());
            attendSaveReq.setActualAttendTime();
            attendSaveReq.setErrorResult(entity.getRemark());
            attendSaveReq.setExt();
            attendSaveReq.setWorkNum();
            attendSaveReq.setTitle();
            attendSaveReq.setHappenTime(entity.getErrorDateTime());
            attendSaveReq.setRuleCode(ruleCode);
            attendSaveReq.setRuleId();
            attendSaveReq.setPhone();
            attendSaveReq.setPerformType();
            attendSaveReq.setStaffId();*/


            // apiWebPerformController.attendSave(attendSaveReq);

        }


        return super.saveAfter(entity, model, context);
    }

    @Override
    protected int editAfter(Long id, Map<String, Object> model, AttendanceRecordErrorEntity entity, Context context) throws AppException {
        this.addDict(model, "errorStatus", paramService.getParamBySecondOrganize("AttendanceRecordDetail", "goWorkResult"));
        return super.editAfter(id, model, entity, context);
    }


    @Override
    protected void doListBefore(AttendanceRecordErrorEntity query, Map<String, Object> model, Context context) throws AppException {
        if (org.springframework.util.ObjectUtils.isEmpty(query.getOrderColList())) {
            query.setOrderColList(Arrays.asList(new OrderCol("errorDateTime", OrderCol.DESCENDING), new OrderCol("staffName", OrderCol.DESCENDING)));
        } else {
            query.getOrderColList().add(new OrderCol("errorDateTime", OrderCol.DESCENDING));
            // query.getOrderColList().add(new OrderCol("staffName", OrderCol.DESCENDING));
        }

    }

    @Override
    protected void doListAfter(AttendanceRecordErrorEntity query, List<AttendanceRecordErrorEntity> list, Context context) throws AppException {
/*        for (AttendanceRecordErrorEntity errorEntity : list) {
            Long shiftsId = errorEntity.getShiftsId();
            AttendanceClassDetailEntity attendanceClassDetailEntity = classDetailService.selectOne(new AttendanceClassDetailQuery().id(shiftsId));
            if (!ObjectUtils.isEmpty(attendanceClassDetailEntity)) {
                if (errorEntity.getGoOffDateTime().getTime() == attendanceClassDetailEntity.getGoWorkDate().getTime()) {
                    errorEntity.setGoOrOff("上班");
                }
                if (errorEntity.getGoOffDateTime().getTime() == attendanceClassDetailEntity.getOffWorkDate().getTime()) {
                    errorEntity.setGoOrOff("下班");
                }
            }
        }*/
        super.doListAfter(query, list, context);
    }
}
