package cn.iocoder.yudao.module.attendance.service.workdaysetting;

import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import cn.iocoder.yudao.module.attendance.controller.admin.workdaysetting.vo.*;
import cn.iocoder.yudao.module.attendance.dal.dataobject.workdaysetting.AttendanceWorkdaySettingDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.attendance.dal.mysql.workdaysetting.AttendanceWorkdaySettingMapper;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.attendance.enums.ErrorCodeConstants.*;

/**
 * 考勤工作日设置 Service 实现类
 *
 * @author zhaopq
 */
@Service
@Validated
public class AttendanceWorkdaySettingServiceImpl implements AttendanceWorkdaySettingService {

    @Resource
    private AttendanceWorkdaySettingMapper workdaySettingMapper;

    @Override
    public Long createWorkdaySetting(AttendanceWorkdaySettingSaveReqVO createReqVO) {
        // 插入
        AttendanceWorkdaySettingDO workdaySetting = BeanUtils.toBean(createReqVO, AttendanceWorkdaySettingDO.class);
        workdaySettingMapper.insert(workdaySetting);
        // 返回
        return workdaySetting.getId();
    }

    @Override
    public void updateWorkdaySetting(AttendanceWorkdaySettingSaveReqVO updateReqVO) {
        // 校验存在
        validateWorkdaySettingExists(updateReqVO.getId());
        // 更新
        AttendanceWorkdaySettingDO updateObj = BeanUtils.toBean(updateReqVO, AttendanceWorkdaySettingDO.class);
        workdaySettingMapper.updateById(updateObj);
    }

    @Override
    public void deleteWorkdaySetting(Long id) {
        // 校验存在
        validateWorkdaySettingExists(id);
        // 删除
        workdaySettingMapper.deleteById(id);
    }

    private void validateWorkdaySettingExists(Long id) {
        if (workdaySettingMapper.selectById(id) == null) {
            throw exception(ATTENDANCE_WORKDAY_SETTING_NOT_EXISTS);
        }
    }

    @Override
    public AttendanceWorkdaySettingDO getWorkdaySetting(Long id) {
        return workdaySettingMapper.selectById(id);
    }

    @Override
    public PageResult<AttendanceWorkdaySettingDO> getWorkdaySettingPage(AttendanceWorkdaySettingPageReqVO pageReqVO) {
        return workdaySettingMapper.selectPage(pageReqVO);
    }

    @Override
    public Boolean batchInsert(String[] dates) {
        if (dates == null || dates.length == 0) {
            return false; // 如果输入为空，直接返回false
        }

        List<AttendanceWorkdaySettingDO> workingDaysList = new ArrayList<>();
        String workMonth = dates[0].substring(0, 7); // 假设日期格式是YYYY-MM-DD，这里只取前7位作为月份
        // 获取用户信息和租户ID
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Long tenantId = user != null && user.getTenantId() != null ? user.getTenantId() : 0L;

        // 清理操作，先删除该月份的所有工作日设置
        workdaySettingMapper.deleteByMonth(workMonth, tenantId);

        // 遍历日期数组，为每个日期创建设置对象并添加到列表中
        for (String str : dates) {
            AttendanceWorkdaySettingDO settingDO = new AttendanceWorkdaySettingDO();
            settingDO.setWorkMonth(workMonth);
            settingDO.setWorkDate(str);
            settingDO.setTenantId(tenantId);
            workingDaysList.add(settingDO);
        }

        // 批量插入到数据库
        return workdaySettingMapper.insertBatch(workingDaysList);
    }

    @Override
    public List<AttendanceWorkdaySettingDO> getWorkdays(String workMonth) {
        // 获取用户信息和租户ID
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Long tenantId = user != null && user.getTenantId() != null ? user.getTenantId() : 0L;
        List<AttendanceWorkdaySettingDO> workingDaysList = workdaySettingMapper.getWorkdays(workMonth, tenantId);
        if (workingDaysList.size() == 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = sdf.parse(workMonth + "-01");
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            Integer month = cal.get(Calendar.MONTH) + 1;
            while (month == cal.get(Calendar.MONTH) + 1) {
                if(this.isWorkingDay(sdf.format(cal.getTime()))==0){
                    AttendanceWorkdaySettingDO settingDO = new AttendanceWorkdaySettingDO();
                    settingDO.setWorkMonth(workMonth);
                    settingDO.setWorkDate(sdf.format(cal.getTime()));
                    workingDaysList.add(settingDO);

                }
                cal.add(Calendar.DATE, 1);
            }
            workdaySettingMapper.insertBatch(workingDaysList);
        }
        return workingDaysList;
    }

    private int isWorkingDay(String day) {
        try {
            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
            Date bdate = format1.parse(day);
            Calendar cal = Calendar.getInstance();
            cal.setTime(bdate);
            if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                return 1;
            } else {
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


}