package jnpf.workflow.service.impl;

import jnpf.attendance.service.AttendanceClockInService;
import jnpf.base.UserInfo;
import jnpf.base.service.SuperServiceImpl;
import jnpf.entity.workflow.ApplyAttendanceViolation;
import jnpf.enums.attendance.ApplyTypeEnum;
import jnpf.model.attendance.dto.ClockInDto;
import jnpf.model.workflow.dto.ApplyAttendanceViolationDto;
import jnpf.util.ConstantUtil;
import jnpf.util.DateDetail;
import jnpf.util.JsonUtil;
import jnpf.util.UserProvider;
import jnpf.workflow.mapper.ApplyAttendanceViolationMapper;
import jnpf.workflow.service.ApplyAttendanceViolationService;
import jnpf.workflow.service.ApplyPicService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 违规打卡审批服务实现
 *
 * @author yanwenfu
 * @create 2025-09-22
 */
@Slf4j
@Service
public class ApplyAttendanceViolationServiceImpl extends SuperServiceImpl<ApplyAttendanceViolationMapper, ApplyAttendanceViolation> implements ApplyAttendanceViolationService {

    @Resource
    private ApplyPicService applyPicService;
    @Resource
    private AttendanceClockInService attendanceClockInService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRecord(ApplyAttendanceViolationDto dto) throws Exception {

        ApplyAttendanceViolation entity = JsonUtil.getJsonToBean(dto, ApplyAttendanceViolation.class);
        entity.setStatus(ConstantUtil.STATUS_PENDING_APPROVAL);
        log.error("发起异常打卡审批: 任务id: {}, 打卡类型: {}", dto.getTaskId(), dto.getClockInKind());
        //保存外勤打卡图片 picUrlList
        List<String> urlList = applyPicService.getPicList(dto.getPicUrlList());
        if (!urlList.isEmpty()) {
            dto.getPicUrlList().clear();
            dto.getPicUrlList().addAll(urlList);
        }
        applyPicService.saveClockPic(dto.getTaskId(), dto.getPicUrlList());
        UserInfo userInfo = UserProvider.getUser();
        entity.setApplyUser(userInfo.getUserId());
        entity.setApplyDate(DateDetail.getStr2DateTime(dto.getApplyDateStr()));
        entity.setTenantId(userInfo.getTenantId());
        entity.setId(dto.getTaskId());
        entity.setRemark(dto.getRemark());
        ClockInDto clockInDto = new ClockInDto(dto.getDeviceType(), dto.getClockInKind(), dto.getTaskId(), ApplyTypeEnum.VIOLATION, dto.getAddress(), dto.getLng(), dto.getLat(), dto.getRemark());
        MutablePair<Integer, String> pair;
        if (StringUtils.isEmpty(dto.getClockInId())) {
            pair = attendanceClockInService.clockIn(clockInDto);
        } else {
            pair = attendanceClockInService.updateClockIn(dto.getClockInId(), clockInDto);
        }
        entity.setClockInResultId(pair.getRight());
        save(entity);
    }
}
