package com.cpop.clockin.business.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson2.JSON;
import com.cpop.clockin.business.entity.Classes;
import com.cpop.clockin.business.entity.ClockInStaff;
import com.cpop.clockin.business.entity.StaffClasses;
import com.cpop.clockin.business.service.ClassesService;
import com.cpop.clockin.business.service.ClockInRecordService;
import com.cpop.clockin.business.service.ClockInStaffService;
import com.cpop.clockin.business.service.StaffClassesService;
import com.cpop.clockin.framework.constant.ClockInConstant;
import com.cpop.core.service.RedisService;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 打卡记录服务实现类
 * @Author: Yxz
 * @Date: 2024/1/23 21:55
 * @Version: 1.0
 */
@Service
public class ClockInRecordServiceImpl implements ClockInRecordService {
    @Autowired
    private RedisService redisService;
    @Autowired
    private ClockInStaffService clockInStaffService;
    @Autowired
    private StaffClassesService staffClassesService;
    @Autowired
    private ClassesService classesService;

    /**
     * 上传钉钉Excel表
     *
     * @author: Yxz
     * @date: 2024/1/24 14:54
     * @param: [file]
     * @return: java.lang.String
     **/
    @Override
    public String uploadRecord(MultipartFile file) throws IOException, ParseException {
        List<Map<Integer, String>> dataList = new ArrayList<>();
        EasyExcel.read(file.getInputStream())
                .sheet()
                .registerReadListener(new AnalysisEventListener<Map<Integer, String>>() {
                    @Override
                    public void invoke(Map<Integer, String> data, AnalysisContext context) {

                        // 遍历每一列
                        for (Map.Entry<Integer, String> entry : data.entrySet()) {
                            Integer columnIndex = entry.getKey();
                            String columnValue = entry.getValue();

                            // 如果列的值为null，将其替换为空字符串
                            if (columnValue == null) {
                                data.put(columnIndex, ""); // 使用空字符串代替null
                            }
                        }

                        dataList.add(data);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext context) {
                    }
                })
                .doRead();


        Map<Integer, String> sortedJsonObject = dataList.get(1);
        List<Map> mergedJsonList = new ArrayList<>();

        // 合并键值对
        for (int i = 2; i < dataList.size(); i++) {
            Map<String, String> mergedJson = new LinkedHashMap<>();
            Map<Integer, String> element = dataList.get(i);
            String name = element.get(0);
            ClockInStaff clockInStaff = clockInStaffService.getOne(QueryWrapper.create().eq("name", name));
            List<StaffClasses> staffClasses = new ArrayList<>();
            if (ObjectUtil.isNotNull(clockInStaff)) staffClasses = staffClassesService.list(QueryWrapper.create().eq("staff_id", clockInStaff.getId()));



            for (Integer key : sortedJsonObject.keySet()) {
                String newKey = sortedJsonObject.get(key);


                // 获取当前元素
                String value = element.get(key);
                // 时间列
                if (newKey.matches("-?\\d+(\\.\\d+)?") || newKey.equals("六") || newKey.equals("日")){
                    // 工时
                    double manHour = 0.0;
                    // 加班时间
                    double  overtime = 0.0;

                    // 匹配员工
                    // 查找班次
                    if (ObjectUtil.isNotNull( clockInStaff)) {
                        for (StaffClasses staffClass : staffClasses) {
                            Classes classes = classesService.getById(staffClass.getClassId());
                            if (ObjectUtil.isNotNull(classes) && ObjectUtil.isNotEmpty(value)){
                                // 计算工时
                                String firstTime = value.substring(0, 5);

//                                String lastTime = value.substring( value.length() - 5,value.length());
                                String lastTime = value.substring(value.length() - 5).trim();

                                String pattern = "HH:mm";
                                SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);

                                Date firstTimeDate = dateFormat.parse(firstTime);
                                Date lastTimeDate = dateFormat.parse(lastTime);
                                Date overTimeDate = dateFormat.parse("21:00");

                                if (firstTimeDate.before(classes.getStartTime())){
                                    // 正常上班卡
                                    if (lastTimeDate.before(classes.getEndTime())){
                                        // 早退
                                        long timeDifferenceInMillis = lastTimeDate.getTime() - classes.getStartTime().getTime();
                                        manHour = manHour + (double) timeDifferenceInMillis / (1000 * 60 * 60);
                                    }else {
                                        // 正常下班
                                        long timeDifferenceInMillis = classes.getEndTime().getTime() - classes.getStartTime().getTime();
                                        manHour = manHour + (double) timeDifferenceInMillis / (1000 * 60 * 60);
                                    }
                                }else {
                                    // 迟到
                                    if (lastTimeDate.before(classes.getEndTime())){
                                        // 早退
                                        long timeDifferenceInMillis = lastTimeDate.getTime() - firstTimeDate.getTime();
                                        manHour = manHour + (double) timeDifferenceInMillis / (1000 * 60 * 60);
                                    }else {
                                        // 正常下班
                                        long timeDifferenceInMillis = classes.getEndTime().getTime() - firstTimeDate.getTime();
                                        manHour = manHour + (double) timeDifferenceInMillis / (1000 * 60 * 60);
                                    }
                                }


                                if (lastTimeDate.after(overTimeDate)){
                                    // 加班
                                    long timeDifferenceInMillis = lastTimeDate.getTime() - overTimeDate.getTime();
                                    overtime = (double) timeDifferenceInMillis / (1000 * 60 * 60);
                                }

                            }
                        }
                    }

                    // 保留两位小数
                    DecimalFormat decimalFormat = new DecimalFormat("#.##");

                    // 使用format方法进行格式化
                    String formatManHour = decimalFormat.format(manHour + overtime);
                    String formatOverTime = decimalFormat.format(overtime);

                    value = "工时：" + formatManHour;
                    if (overtime != 0.0){
                        //加班
                        value = value + " " + "加班工时：" +formatOverTime;
                    }

                }
                mergedJson.put(newKey,value);

            }
            mergedJsonList.add(mergedJson);

        }
        String jsonString = JSON.toJSONString(mergedJsonList);
        redisService.setCacheObject(ClockInConstant.MAN_TIME_JSON,jsonString,5,TimeUnit.MINUTES);

        return  jsonString;
    }




    /*@Override
    public String uploadRecord(MultipartFile file) throws IOException, ParseException {
        *//*EasyExcel.read(file.getInputStream())
                .sheet()
                .registerReadListener(new AnalysisEventListener<EmployeeAttendanceBo>() {
                    @Override
                    public void invoke(EmployeeAttendanceBo bo, AnalysisContext context) {
                        dataList.add(bo);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext context) {
                        // 处理数据完成后的操作

                    }
                })
                .doRead();*//*
        ExcelListener excelListener = new ExcelListener();
        EasyExcel.read(file.getInputStream(), EmployeeAttendanceBo.class, excelListener)
                .headRowNumber(3) // 从第三行开始读取数据
                .sheet().doReadSync();
        List<EmployeeAttendanceBo> dataList = excelListener.getDataList();

        for (EmployeeAttendanceBo employeeAttendanceBo : dataList) {
            Class<?> clazz = employeeAttendanceBo.getClass();
            Field[] fields = clazz.getDeclaredFields();
            ClockInStaff clockInStaff = clockInStaffService.getOne(QueryWrapper.create().eq("name", employeeAttendanceBo.getName()));
            if (ObjectUtil.isNotNull(clockInStaff)){
                List<StaffClasses> staffClasses = staffClassesService.list(QueryWrapper.create().eq("staff_id", clockInStaff.getId()));
                for (Field field : fields) {
                    if (field.getName().startsWith("day")) {
                        try {
                            field.setAccessible(true);
                            String dayValue = (String) field.get(employeeAttendanceBo);

                            // 进行后续操作，例如输出或其他处理
                            // 工时
                            double manHour = 0.0;
                            // 加班时间
                            double  overtime = 0.0;


                            // 匹配员工
                            // 查找班次
                            if (ObjectUtil.isNotNull( clockInStaff)) {
                                for (StaffClasses staffClass : staffClasses) {
                                    Classes classes = classesService.getById(staffClass.getClassId());
                                    if (ObjectUtil.isNotNull(classes) && ObjectUtil.isNotEmpty(dayValue)){
                                        // 计算工时
                                        String firstTime = dayValue.substring(0, 5);

//                                String lastTime = value.substring( value.length() - 5,value.length());
                                        String lastTime = dayValue.substring(dayValue.length() - 5).trim();

                                        String pattern = "HH:mm";
                                        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);

                                        Date firstTimeDate = dateFormat.parse(firstTime);
                                        Date lastTimeDate = dateFormat.parse(lastTime);
                                        Date overTimeDate = dateFormat.parse("21:00");

                                        if (firstTimeDate.before(classes.getStartTime())){
                                            // 正常上班卡
                                            if (lastTimeDate.before(classes.getEndTime())){
                                                // 早退
                                                long timeDifferenceInMillis = lastTimeDate.getTime() - classes.getStartTime().getTime();
                                                manHour = manHour + (double) timeDifferenceInMillis / (1000 * 60 * 60);
                                            }else {
                                                // 正常下班
                                                long timeDifferenceInMillis = classes.getEndTime().getTime() - classes.getStartTime().getTime();
                                                manHour = manHour + (double) timeDifferenceInMillis / (1000 * 60 * 60);
                                            }
                                        }else {
                                            // 迟到
                                            if (lastTimeDate.before(classes.getEndTime())){
                                                // 早退
                                                long timeDifferenceInMillis = lastTimeDate.getTime() - firstTimeDate.getTime();
                                                manHour = manHour + (double) timeDifferenceInMillis / (1000 * 60 * 60);
                                            }else {
                                                // 正常下班
                                                long timeDifferenceInMillis = classes.getEndTime().getTime() - firstTimeDate.getTime();
                                                manHour = manHour + (double) timeDifferenceInMillis / (1000 * 60 * 60);
                                            }
                                        }


                                        if (lastTimeDate.after(overTimeDate)){
                                            // 加班
                                            long timeDifferenceInMillis = lastTimeDate.getTime() - overTimeDate.getTime();
                                            overtime = (double) timeDifferenceInMillis / (1000 * 60 * 60);
                                        }

                                    }
                                }
                            }

                            // 保留两位小数
                            DecimalFormat decimalFormat = new DecimalFormat("#.##");

                            // 使用format方法进行格式化
                            String formatManHour = decimalFormat.format(manHour + overtime);
                            String formatOverTime = decimalFormat.format(overtime);

                            dayValue = "工时：" + formatManHour;
                            if (overtime != 0.0){
                                //加班
                                dayValue = dayValue + " " + "加班工时：" +formatOverTime;
                            }

                            field.set(employeeAttendanceBo, dayValue);





                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }

        }

        String jsonString = JSON.toJSONString(dataList);
        redisService.setCacheObject(ClockInConstant.MAN_TIME_JSON,jsonString,5,TimeUnit.MINUTES);

        return  jsonString;
    }*/
}
