package com.zjty.tynotes.attendance.service.impl;

import com.zjty.tynotes.attendance.dao.ApprovalInformationDao;
import com.zjty.tynotes.attendance.dao.AttendanceDetailsDao;
import com.zjty.tynotes.attendance.dao.UserOverWorkDao;
import com.zjty.tynotes.attendance.entity.ApprovalInformation;
import com.zjty.tynotes.attendance.entity.AttendanceDetails;
import com.zjty.tynotes.attendance.entity.UserOverWork;
import com.zjty.tynotes.attendance.service.ApprovalInformationService;
import com.zjty.tynotes.pas.dao.ConfigDao;
import com.zjty.tynotes.pas.dao.DayDao;
import com.zjty.tynotes.pas.dao.DepartmentDao;
import com.zjty.tynotes.pas.entity.Config;
import com.zjty.tynotes.pas.entity.Day;
import com.zjty.tynotes.pas.entity.Department;
import com.zjty.tynotes.pas.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotEmpty;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author gwj
 * @create 2020/3/24 15:23
 */
@Service
public class ApprovalInformationServiceImpl implements ApprovalInformationService {
    private static final Logger logger = LoggerFactory.getLogger(ApprovalInformationServiceImpl.class);

    @Autowired
    private ApprovalInformationDao approvalInformationDao;
    @Autowired
    private AttendanceDetailsDao attendanceDetailsDao;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private UserOverWorkDao userOverWorkDao;
    @Autowired
    private DayDao dayDao;
    @Autowired
    private ConfigDao configDao;

    @Override
    public ApprovalInformation addApproval(ApprovalInformation approvalInformation) {

        if(approvalInformation.getApprovalType().equals("调休")){
            String userId = approvalInformation.getUserId();
            UserOverWork userOverWork = userOverWorkDao.findByUserId(userId);
            Long workOverHours = userOverWork.getOverWorkHour();
            Date leaveEndTime = approvalInformation.getLeaveEndTime();
            Date leaveStartTime = approvalInformation.getLeaveStartTime();
            Long aLong = 0L;
            try {
                aLong = computeTime(leaveEndTime, leaveStartTime);
            } catch (Exception e) {
                logger.error("addApproval()方法中计算调休时长出错");
            }
            long daytime = 8;
            long day;
            if(aLong%daytime==0){
                day = aLong/daytime;
            }else{
                day = aLong/daytime + 1;
            }
            if(workOverHours<=(aLong)){
                return null;
            }
            if(day>2){
                approvalInformation.setApprovalLevel("1");
            }else{
                approvalInformation.setApprovalLevel("2");
            }

        }
        approvalInformation.setStatus("0");
        return approvalInformationDao.save(approvalInformation);
    }

    @Override
    public boolean deleteApproval(String id) {
        Optional<ApprovalInformation> optional = approvalInformationDao.findById(id);
        if(optional.isPresent()){
            ApprovalInformation approvalInformation = optional.get();
            String status = approvalInformation.getStatus();
            if(("0").equals(status)){
                approvalInformationDao.deleteById(id);
                return true;
            }
        }
        return false;
    }

    @Override
    @Transactional
    public ApprovalInformation auditApproval(String userId,String approvalStatus,ApprovalInformation approvalInformation) {
        String departmentId = approvalInformation.getDepartmentId();
        String departmentLevel = iUserService.getDepartmentLevel(departmentId);
        System.out.println(departmentLevel);
        if(("1").equals(departmentLevel)||("2").equals(departmentLevel)){
            approvalInformation.setApprovalUserIdOne(userId);
            if(approvalInformation.getApprovalStatus()!=null && approvalInformation.getApprovalStatus().equals("0")){
                if(StringUtils.isNotBlank(approvalInformation.getApprovalType())&&approvalInformation.getApprovalType().equals("调休")){
                    UserOverWork userOverWork = userOverWorkDao.findByUserId(approvalInformation.getUserId());
                    try {
                        Long aLong = computeTime(approvalInformation.getLeaveEndTime(), approvalInformation.getLeaveStartTime());
                        Long overWorkHour = userOverWork.getOverWorkHour();
                        Long timeLeft = overWorkHour - aLong;
                        userOverWork.setOverWorkHour(timeLeft);
                        userOverWorkDao.save(userOverWork);
                    } catch (Exception e) {
                        logger.error("计算调休时长出错");
                    }
                }else if(StringUtils.isNotBlank(approvalInformation.getApprovalType())&&approvalInformation.getApprovalType().equals("加班")){
                    UserOverWork userOverWork = userOverWorkDao.findByUserId(approvalInformation.getUserId());
                    try {
                        Long aLong = computeTime(approvalInformation.getLeaveEndTime(), approvalInformation.getLeaveStartTime());
                        Long overWorkHour = userOverWork.getOverWorkHour();
                        Long timeLeft = overWorkHour + aLong;
                        userOverWork.setOverWorkHour(timeLeft);
                        userOverWorkDao.save(userOverWork);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                approvalInformation.setStatus("1");
                approvalInformation.setApprovalOne("0");
            }else if(approvalInformation.getApprovalStatus()!=null && approvalInformation.getApprovalStatus().equals("1")){
                approvalInformation.setStatus("2");
                approvalInformation.setApprovalOne("1");
            }
        }else {
            if(approvalInformation.getApprovalTwo()==null){
                approvalInformation.setApprovalUserIdTwo(userId);
                if(approvalInformation.getApprovalStatus()!=null && approvalInformation.getApprovalStatus().equals("0")){
                    approvalInformation.setApprovalTwo("0");
                }else if(approvalInformation.getApprovalStatus()!=null && approvalInformation.getApprovalStatus().equals("1")){
                    approvalInformation.setStatus("2");
                    approvalInformation.setApprovalTwo("1");
                }
            }else if(approvalInformation.getApprovalTwo()!=null && approvalInformation.getApprovalOne()==null){
                String parentDepartmentLevel = iUserService.getParentDepartmentLevel(departmentId);
                if(("1").equals(parentDepartmentLevel)||("2").equals(parentDepartmentLevel)){
                    approvalInformation.setApprovalUserIdOne(userId);
                    if(approvalInformation.getApprovalStatus()!=null && approvalInformation.getApprovalStatus().equals("0")){
                        if(StringUtils.isNotBlank(approvalInformation.getApprovalType())&&approvalInformation.getApprovalType().equals("调休")){
                            UserOverWork userOverWork = userOverWorkDao.findByUserId(approvalInformation.getUserId());
                            try {
                                Long aLong = computeTime(approvalInformation.getLeaveEndTime(), approvalInformation.getLeaveStartTime());
                                Long overWorkHour = userOverWork.getOverWorkHour();
                                Long timeLeft = overWorkHour - aLong;
                                userOverWork.setOverWorkHour(timeLeft);
                                userOverWorkDao.save(userOverWork);
                            } catch (Exception e) {
                                logger.error("计算调休时长出错");
                            }
                        }else if(StringUtils.isNotBlank(approvalInformation.getApprovalType())&&approvalInformation.getApprovalType().equals("加班")){
                            UserOverWork userOverWork = userOverWorkDao.findByUserId(approvalInformation.getUserId());
                            try {
                                Long aLong = computeTime(approvalInformation.getLeaveEndTime(), approvalInformation.getLeaveStartTime());
                                Long overWorkHour = userOverWork.getOverWorkHour();
                                Long timeLeft = overWorkHour + aLong;
                                userOverWork.setOverWorkHour(timeLeft);
                                userOverWorkDao.save(userOverWork);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        approvalInformation.setStatus("1");
                        approvalInformation.setApprovalOne("0");
                    }else if(approvalInformation.getApprovalStatus()!=null && approvalInformation.getApprovalStatus().equals("1")){
                        approvalInformation.setStatus("2");
                        approvalInformation.setApprovalOne("1");
                    }
                }
            }
        }
        return approvalInformation;
    }


    @Override
    public List<ApprovalInformation> findAllApproval(String userId) {
        return approvalInformationDao.findAllByUserId(userId);
    }

    @Override
    public List<ApprovalInformation> findAllAuditApproval(String userId) {
        List<String> statusList = new ArrayList<>();
        List<String> strings = new ArrayList<>();
        statusList.add("1");
        statusList.add("2");
        List<ApprovalInformation> approvalInformations = approvalInformationDao.findAllByStatusIn(statusList);
        List<ApprovalInformation> approvalInformationList = new ArrayList<>();
        approvalInformations.forEach(approvalInformation -> {
            if(userId.equals(approvalInformation.getApprovalUserIdOne())){
                approvalInformationList.add(approvalInformation);
            }else if(userId.equals(approvalInformation.getApprovalUserIdTwo())){
                approvalInformationList.add(approvalInformation);
            }
        });
        strings.add("0");
        List<ApprovalInformation> approvalInformationList1 = approvalInformationDao.findAllByStatusIn(strings);
        approvalInformationList1.forEach(approvalInformation -> {
            String departmentId = approvalInformation.getDepartmentId();
            String departmentLevel = iUserService.getDepartmentLevel(departmentId);
            if(("1").equals(departmentLevel)||("2").equals(departmentLevel)){
                boolean flag = iUserService.findUsersByDepartmentAndAuthority(userId,departmentId);
                if(flag){
                    approvalInformationList.add(approvalInformation);
                }
            }else{
                if(approvalInformation.getApprovalTwo()==null&&approvalInformation.getApprovalOne()==null){
                    boolean flag = iUserService.findUsersByDepartmentAndAuthority(userId,departmentId);
                    if(flag){
                        approvalInformationList.add(approvalInformation);
                    }
                }else if (approvalInformation.getApprovalTwo()!=null && approvalInformation.getApprovalOne()==null){
                    Optional<Department> optional = departmentDao.findById(departmentId);
                    if(optional.isPresent()){
                        Department department = optional.get();
                        String parentId = department.getParentId();
                        boolean flag = iUserService.findUsersByDepartmentAndAuthority(userId,parentId);
                        if(flag){
                            approvalInformationList.add(approvalInformation);
                        }
                    }
                }
            }

        });
        return approvalInformationList;
    }


    public static void main(String[] args) throws Exception{
        Config config = new Config("1","09:00:00","17:00:00","2","3","15","17","1","1","1","1","1","1","1","1","1","1","1");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = "2020-03-29 00:00:00";
        String date2 = "2020-03-30 00:00:00";
        String date3 = "2020-03-31 00:00:00";
        Date parse = sdf.parse(date);
        Date parse1 = sdf.parse(date2);
        Date parse2 = sdf.parse(date3);
        Day day = new Day("1",parse,"1");
        Day day1 = new Day("2",parse1,"0");
        Day day2 = new Day("3",parse2,"0");
        List<Day> days = new ArrayList<>();
        days.add(day);
        days.add(day1);
        days.add(day2);

        String start = "2020-03-29 18:00:00";
        String end = "2020-03-31 19:00:00";
        Date startTime = sdf2.parse(start);
        Date endTime = sdf2.parse(end);
        ApprovalInformationServiceImpl approvalInformationService = new ApprovalInformationServiceImpl();
        Long aLong = approvalInformationService.computeTime2(startTime, endTime, config, days);
        System.out.println(aLong);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 17:00:00");
//        Date date = new Date();
//        String format = sdf.format(date);
//        Date parse = sdf.parse(format);
//        System.out.println(parse);
    }

    /**
     * 计算调休时长，请假时长
     */
    private Long computeTime(Date startTime,Date endTime) throws Exception{
        Config config = configDao.findAll().get(0);
        String workTime = config.getWorkTime();//上班时间
        String afterWorkTime = config.getAfterWorkTime();//下班时间
        SimpleDateFormat sdf5 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd "+workTime);
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd " + afterWorkTime);
        SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar calendar = Calendar.getInstance();
        Calendar calendar1 = Calendar.getInstance();
        String format = sdf.format(startTime);
        Date parse = sdf5.parse(format);

        String format1 = sdf2.format(startTime);
        Date parse1 = sdf5.parse(format1);
        calendar1.setTime(parse1);
        calendar.setTime(parse);//设置上班时间

        String format2 = sdf3.format(startTime);
        String format3 = sdf3.format(endTime);
        long hours = 0;
        long hour = 60 * 1000 * 60;
        if(startTime.before(calendar.getTime())){
            if(format2.equals(format3)){
                String format4 = sdf4.format(calendar.getTime());
                Date parse2 = sdf4.parse(format4);
                Day day = dayDao.findByDate(parse2);
                if(day!=null&&day.getStatus().equals("0")){
                    Date leaveWork = calendar1.getTime();
                    if(endTime.before(leaveWork)){
                        long miSecond = endTime.getTime() - calendar.getTime().getTime();
                        if(miSecond%hour==0){
                            hours = miSecond / hour;
                        }else{
                            hours = miSecond / hour + 1;
                        }
                    }else{
                        hours = 8;
                    }
                }
            }else{
                String format4 = sdf4.format(startTime);
                Date parse2 = sdf4.parse(format4);
                Day day = dayDao.findByDate(parse2);
                if(day!=null&&day.getStatus().equals("0")){
                    hours = 8;
                }else{
                    hours = 0;
                }
                while (true){
                    String format5 = sdf4.format(calendar.getTime());
                    Date parse3 = sdf4.parse(format5);
                    Day day1 = dayDao.findByDate(parse3);
                    if(day1!=null&&day1.getStatus().equals("0")){
                        calendar.add(Calendar.DATE,1);
                        calendar1.add(Calendar.DATE,1);
                        Date leaveWork = calendar1.getTime();
                        Date startWorkTime = calendar.getTime();
                        if(endTime.before(startWorkTime)){
                            return hours;
                        }else{
                            if(endTime.before(leaveWork)){
                                long miSecond = endTime.getTime() - calendar.getTime().getTime();
                                if(miSecond%hour==0){
                                    hours = miSecond / hour + hours;
                                }else{
                                    hours = miSecond / hour + 1 + hours;
                                }
                                return hours;
                            }else{
                                hours += 8;
                            }
                        }
                    }
                }
            }
        }else{
            if(format2.equals(format3)){
                String format4 = sdf4.format(calendar.getTime());
                Date parse2 = sdf4.parse(format4);
                Day day = dayDao.findByDate(parse2);
                if(day!=null&&day.getStatus().equals("0")){
                    Date leaveWork = calendar1.getTime();
                    if(endTime.before(leaveWork)){
                        long miSecond = endTime.getTime() - startTime.getTime();
                        if(miSecond%hour==0){
                            hours = miSecond / hour;
                        }else{
                            hours = miSecond / hour + 1;
                        }
                    }else{
                        long miSecond = leaveWork.getTime() - startTime.getTime();
                        if(miSecond%hour==0){
                            hours = miSecond / hour;
                        }else{
                            hours = miSecond / hour + 1;
                        }
                    }
                }

            }else{
                String format4 = sdf4.format(calendar.getTime());
                Date parse2 = sdf4.parse(format4);
                Day day = dayDao.findByDate(parse2);
                if(day!=null&&day.getStatus().equals("0")){
                    long miSecond1 = calendar1.getTime().getTime() - startTime.getTime();
                    if(miSecond1%hour==0){
                        hours = miSecond1 / hour;
                    }else{
                        hours = miSecond1 / hour + 1;
                    }
                }else{
                    hours = 0;
                }
                while (true){
                    String format5 = sdf4.format(calendar.getTime());
                    Date parse3 = sdf4.parse(format5);
                    Day day1 = dayDao.findByDate(parse3);
                    if(day1!=null&&day1.getStatus().equals("0")){
                        calendar.add(Calendar.DATE,1);
                        calendar1.add(Calendar.DATE,1);
                        Date leaveWork = calendar1.getTime();
                        Date startWorkTime = calendar.getTime();
                        if(endTime.before(startWorkTime)){
                            return hours;
                        }else{
                            if(endTime.before(leaveWork)){
                                long miSecond = endTime.getTime() - calendar.getTime().getTime();
                                if(miSecond%hour==0){
                                    hours = miSecond / hour + hours;
                                }else{
                                    hours = miSecond / hour + 1 + hours;
                                }
                                return hours;
                            }else{
                                hours += 8;
                            }
                        }
                    }

                }
            }
        }

        return hours;
    }







    /**
     * 计算调休时长
     */
    private Long computeTime2(Date startTime,Date endTime,Config config,List<Day> days) throws Exception{
        String workTime = config.getWorkTime();//上班时间
        String afterWorkTime = config.getAfterWorkTime();//下班时间
        SimpleDateFormat sdf5 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd "+workTime);
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd " + afterWorkTime);
        SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar calendar = Calendar.getInstance();
        Calendar calendar1 = Calendar.getInstance();
        String format = sdf.format(startTime);
        Date parse = sdf5.parse(format);

        String format1 = sdf2.format(startTime);
        Date parse1 = sdf5.parse(format1);
        calendar1.setTime(parse1);
        calendar.setTime(parse);//设置上班时间

        String format2 = sdf3.format(startTime);
        String format3 = sdf3.format(endTime);
        long hours = 0;
        long hour = 60 * 1000 * 60;
        if(startTime.before(calendar.getTime())){
            if(format2.equals(format3)){
                String format4 = sdf4.format(calendar.getTime());
                Date parse2 = sdf4.parse(format4);
                Day day = null;
                for (Day day1 : days) {
                    if(day1.getDate().equals(parse2)){
                        day = day1;
                    }
                }
                if(day!=null&&day.getStatus().equals("0")){
                    Date leaveWork = calendar1.getTime();
                    if(endTime.before(leaveWork)){
                        long miSecond = endTime.getTime() - calendar.getTime().getTime();
                        if(miSecond%hour==0){
                            hours = miSecond / hour;
                        }else{
                            hours = miSecond / hour + 1;
                        }
                    }else{
                        hours = 8;
                    }
                }
            }else{
                String format4 = sdf4.format(startTime);
                Date parse2 = sdf4.parse(format4);
                Day day = null;
                for (Day day1 : days) {
                    if(day1.getDate().equals(parse2)){
                        day = day1;
                    }
                }
                if(day!=null&&day.getStatus().equals("0")){
                    hours = 8;
                }else{
                    hours = 0;
                }
                while (true){
                    calendar.add(Calendar.DATE,1);
                    calendar1.add(Calendar.DATE,1);
                    String format5 = sdf4.format(calendar.getTime());
                    Date parse3 = sdf4.parse(format5);
                    Day day1 = null;
                    for (Day day2 : days) {
                        if(day2.getDate().equals(parse3)){
                            day1 = day2;
                        }
                    }

                    if(day1!=null&&day1.getStatus().equals("0")){
                        Date leaveWork = calendar1.getTime();
                        Date startWorkTime = calendar.getTime();
                        if(endTime.before(startWorkTime)){
                            return hours;
                        }else{
                            if(endTime.before(leaveWork)){
                                long miSecond = endTime.getTime() - calendar.getTime().getTime();
                                if(miSecond%hour==0){
                                    hours = miSecond / hour + hours;
                                }else{
                                    hours = miSecond / hour + 1 + hours;
                                }
                                return hours;
                            }else{
                                hours += 8;
                            }
                        }
                    }
                }
            }
        }else{
            if(format2.equals(format3)){
                String format4 = sdf4.format(calendar.getTime());
                Date parse2 = sdf4.parse(format4);
                Day day = null;
                for (Day day1 : days) {
                    if(day1.getDate().equals(parse2)){
                        day = day1;
                    }
                }
                if(day!=null&&day.getStatus().equals("0")){
                    Date leaveWork = calendar1.getTime();
                    if(endTime.before(leaveWork)){
                        long miSecond = endTime.getTime() - startTime.getTime();
                        if(miSecond%hour==0){
                            hours = miSecond / hour;
                        }else{
                            hours = miSecond / hour + 1;
                        }
                    }else{
                        long miSecond = leaveWork.getTime() - startTime.getTime();
                        if(miSecond%hour==0){
                            hours = miSecond / hour;
                        }else{
                            hours = miSecond / hour + 1;
                        }
                    }
                }

            }else{
                String format4 = sdf4.format(calendar.getTime());
                Date parse2 = sdf4.parse(format4);
                Day day = null;
                for (Day day1 : days) {
                    if(day1.getDate().equals(parse2)){
                        day = day1;
                    }
                }
                if(day!=null&&day.getStatus().equals("0")){
                    long miSecond1 = calendar1.getTime().getTime() - startTime.getTime();
                    if(miSecond1%hour==0){
                        hours = miSecond1 / hour;
                    }else{
                        hours = miSecond1 / hour + 1;
                    }
                }else{
                    hours = 0;
                }
                while (true){
                    calendar.add(Calendar.DATE,1);
                    calendar1.add(Calendar.DATE,1);
                    String format5 = sdf4.format(calendar.getTime());
                    Date parse3 = sdf4.parse(format5);
                    Day day1 = null;
                    for (Day day2 : days) {
                        if(day2.getDate().equals(parse3)){
                            day1 = day2;
                        }
                    }
                    if(day1!=null&&day1.getStatus().equals("0")){
                        Date leaveWork = calendar1.getTime();
                        Date startWorkTime = calendar.getTime();
                        if(endTime.before(startWorkTime)){
                            return hours;
                        }else{
                            if(endTime.before(leaveWork)){
                                long miSecond = endTime.getTime() - calendar.getTime().getTime();
                                if(miSecond%hour==0){
                                    hours = miSecond / hour + hours;
                                }else{
                                    hours = miSecond / hour + 1 + hours;
                                }
                                return hours;
                            }else{
                                hours += 8;
                            }
                        }
                    }

                }
            }
        }

        return hours;
    }










}
