package com.ruoyi.pay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.pay.domain.bo.PayAttendanceBo;
import com.ruoyi.pay.domain.vo.PayAttendanceVo;
import com.ruoyi.pay.domain.PayAttendance;
import com.ruoyi.pay.mapper.PayAttendanceMapper;
import com.ruoyi.pay.service.IPayAttendanceService;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 考勤Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-12
 */
@RequiredArgsConstructor
@Service
public class PayAttendanceServiceImpl implements IPayAttendanceService {

    private final PayAttendanceMapper baseMapper;

    /**
     * 查询考勤
     */
    @Override
    public PayAttendanceVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询考勤列表
     */
    @Override
    public TableDataInfo<PayAttendanceVo> queryPageList(PayAttendanceBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PayAttendance> lqw = buildQueryWrapper(bo);
        Page<PayAttendanceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询考勤列表
     */
    @Override
    public List<PayAttendanceVo> queryList(PayAttendanceBo bo) {
        LambdaQueryWrapper<PayAttendance> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PayAttendance> buildQueryWrapper(PayAttendanceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PayAttendance> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTenantId() != null, PayAttendance::getTenantId, bo.getTenantId());
        lqw.eq(bo.getEmployeeId() != null, PayAttendance::getEmployeeId, bo.getEmployeeId());
        lqw.like(StringUtils.isNotBlank(bo.getEmpName()), PayAttendance::getEmpName, bo.getEmpName());
        lqw.like(StringUtils.isNotBlank(bo.getDeptName()), PayAttendance::getDeptName, bo.getDeptName());
        lqw.eq(bo.getDeptId() != null, PayAttendance::getDeptId, bo.getDeptId());
        lqw.eq(bo.getAmStartTime() != null, PayAttendance::getAmStartTime, bo.getAmStartTime());
        lqw.eq(bo.getAmEndTime() != null, PayAttendance::getAmEndTime, bo.getAmEndTime());
        lqw.eq(bo.getPmStartTime() != null, PayAttendance::getPmStartTime, bo.getPmStartTime());
        lqw.eq(bo.getPmEndTime() != null, PayAttendance::getPmEndTime, bo.getPmEndTime());
        lqw.eq(bo.getKaoqinDate() != null, PayAttendance::getKaoqinDate, bo.getKaoqinDate());
        lqw.eq(StringUtils.isNotBlank(bo.getKaoqinYearMonth()), PayAttendance::getKaoqinYearMonth, bo.getKaoqinYearMonth());
        lqw.eq(StringUtils.isNotBlank(bo.getKaoqinjiNum()), PayAttendance::getKaoqinjiNum, bo.getKaoqinjiNum());
        return lqw;
    }

    /**
     * 新增考勤
     */
    @Override
    public Boolean insertByBo(PayAttendanceBo bo) {
        PayAttendance add = BeanUtil.toBean(bo, PayAttendance.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改考勤
     */
    @Override
    public Boolean updateByBo(PayAttendanceBo bo) {
        PayAttendance update = BeanUtil.toBean(bo, PayAttendance.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PayAttendance entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除考勤
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public PayAttendance selectEmpInfoByName(String empName) {
        return baseMapper.selectEmpInfoByName(empName);
    }

    @Override
    public String importAttendance(List<PayAttendanceBo> attendanceList, boolean updateSupport, String date) {
        if (null==attendanceList || attendanceList.size() == 0)
        {
            throw new ServiceException("导入考勤数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (PayAttendanceBo attendance : attendanceList)
        {
            try
            {
                // 验证本人当日的考勤是否存在（注意：在controller中更新数据时  以根据年月和考勤机删除原来记录数据）
                PayAttendanceBo query = new PayAttendanceBo();
                query.setKaoqinDate(attendance.getKaoqinDate());
                query.setEmpName(attendance.getEmpName());
                List<PayAttendanceVo> attendances=this.queryList(query);
                if (null==attendances||attendances.size()==0)
                {
                    this.insertByBo(attendance);
                    successNum++;
                    if(!updateSupport) {
                        successMsg.append("<br/>" + successNum  +": "+attendance.getEmpName()+new SimpleDateFormat("yyyy-MM-dd").format(attendance.getKaoqinDate())+ "考勤导入成功");
                    }else{
                        successMsg.append("<br/>" + successNum  +": "+attendance.getEmpName()+new SimpleDateFormat("yyyy-MM-dd").format(attendance.getKaoqinDate())+"考勤更新成功");
                    }
                } else {  //员工在多个考勤机录入考勤  时进入  （注意：要求员工上午或下午打卡必须在同一个考勤机）
                    if(updateSupport){
                        if(attendance.getAmStartTime()==null&&attendance.getAmEndTime()==null){
                            attendance.setAmStartTime(attendances.get(0).getAmStartTime());
                            attendance.setAmEndTime(attendances.get(0).getAmEndTime());
                        }
                        if(attendance.getPmStartTime()==null&&attendance.getPmEndTime()==null){
                            attendance.setPmStartTime(attendances.get(0).getPmStartTime());
                            attendance.setPmEndTime(attendances.get(0).getPmEndTime());
                        }
                        this.updateByBo(attendance);
                        successNum++;
                        successMsg.append("<br/>" + successNum  +": "+attendance.getEmpName()+new SimpleDateFormat("yyyy-MM-dd").format(attendance.getKaoqinDate())+ "考勤更新成功");
                    }else{
                        String kaoqinji="";
                        switch (attendances.get(0).getKaoqinjiNum()){
                            case "0":
                                kaoqinji ="综合办";
                                break;
                            case "1":
                                kaoqinji ="网机";
                                break;
                            case "2":
                                kaoqinji ="围栏";
                                break;
                            case "3":
                                kaoqinji ="手动添加";
                                break;
                        }
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum  +": "+attendance.getEmpName()+new SimpleDateFormat("yyyy-MM-dd").format(attendance.getKaoqinDate())+" "+kaoqinji+"考勤机已存在");

                    }
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum+ ": "+attendance.getEmpName() +" "+attendance.getEmpName()+new SimpleDateFormat("yyyy-MM-dd").format(attendance.getKaoqinDate()) + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                System.err.println(msg+e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "导入成功"+successNum+"条，导入失败" + failureNum + " 条，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
