SignInServiceV1Impl.java 17.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
package com.ruoyi.in.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.ConstDriverProperties;
import com.ruoyi.common.ConstSignInConstSignInProperties;
import com.ruoyi.common.ErrorTypeProperties;
import com.ruoyi.common.cache.TempCache;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.redispre.GlobalRedisPreName;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.domain.DriverScheduling;
import com.ruoyi.domain.DriverSchedulingV1;
import com.ruoyi.driver.domain.Driver;
import com.ruoyi.driver.mapper.DriverMapper;
import com.ruoyi.equipment.domain.Equipment;
import com.ruoyi.equipment.mapper.EquipmentMapper;
import com.ruoyi.in.domain.CalDriverScheduling;
import com.ruoyi.in.domain.SignIn;
import com.ruoyi.in.domain.SignInV1;
import com.ruoyi.in.mapper.SignInMapper;
import com.ruoyi.in.mapper.SignInMapperV1;
import com.ruoyi.in.service.SignInServiceV1;
import com.ruoyi.scheduling.service.SchedulingServiceV1;
import com.ruoyi.service.BigViewServiceV1;
import com.ruoyi.service.SchedulingService;
import com.ruoyi.service.ThreadJobService;
import com.ruoyi.utils.ConstDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import static com.ruoyi.common.ConstSignInConstSignInProperties.*;
import static com.ruoyi.common.ErrorTypeProperties.SIGN_IN_ERROR;
import static com.ruoyi.common.ErrorTypeProperties.SIGN_OUT_ERROR;

@Slf4j
@Service
public class SignInServiceV1Impl extends ServiceImpl<SignInMapperV1, SignInV1> implements SignInServiceV1 {

    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private EquipmentMapper equipmentMapper;
    @Autowired
    private SchedulingServiceV1 schedulingServiceV1;

    @Resource
    private ThreadJobService threadJobService;
    @Resource
    private SchedulingService schedulingService;
    @Resource
    private BigViewServiceV1 bigViewServiceV1;

    @Autowired
    private SignInMapper signInMapper;

    @Autowired
    private RedisCache redisCache;

    private static final FastDateFormat HHMM = FastDateFormat.getInstance("HH:mm");

    @Override
    public AjaxResult addsignInV1(SignIn signIn) throws IOException {

        SignInV1 signInV1 = new SignInV1();

        // 查询员工信息
        Driver driver = driverMapper.getDriverInfoByJobCode(signIn.getJobCode());
        if (Objects.isNull(driver)) {
            log.info("这个工号的员工不存在:[{}]", signIn);
            return AjaxResult.warn("这个工号的员工不存在!");
        }

        Equipment equipment = equipmentMapper.selectEquipmentByDeviceId(signIn.getDeviceId());
        if (Objects.isNull(equipment)) {
            log.info("这个设备号不存在:[{}]", signIn);
            return AjaxResult.warn("这个设备号不存在");
        }

        signInV1.setAddress(equipment.getAddress());
        signInV1.setDeviceId(signIn.getDeviceId());
        signInV1.setSiteName(equipment.getSiteName());
        signInV1.setName(driver.getPersonnelName());
        signInV1.setPosts(driver.getPosts());

        if (Objects.isNull(signIn.getCreateTime())) {
            signIn.setCreateTime(DateUtils.getNowDate());
        }
        long dateTime = signIn.getCreateTime().getTime();
        Date date = DateUtils.shortDate(new Date(dateTime));
        DriverScheduling scheduling = null;
        CalDriverScheduling calDriverScheduling = null;

        uploadImage(signIn);
        List<DriverSchedulingV1> schedulings = schedulingServiceV1.queryByJobCodeAndSchedulingDate(signIn.getJobCode(), date);
        if (CollectionUtils.isEmpty(schedulings)) {
            saveSignOfNoScheduling(signIn, ErrorTypeProperties.WORK_DAY_ERROR);
            switchAndChooseAlcohol(signIn, driver, null);
            return saveData(signIn, null, null, driver, signInV1);
        } else if (Objects.equals(2, signIn.getType())) {
            calDriverScheduling = findSchedulingByDateTime(schedulings, dateTime, ConstDriverProperties.BC_TYPE_IN);
        } else {
            if (checkAlcoholIntake(signIn.getAlcoholIntake())) {
                AjaxResult ajaxResult = bigViewServiceV1.getAjaxResultByDriverSignInfo(signIn);
                if (Objects.nonNull(ajaxResult)) {
                    return ajaxResult;
                }
            }
            calDriverScheduling = findSchedulingByDateTime(schedulings, dateTime, ConstDriverProperties.BC_TYPE_OUT);
        }

        if (Objects.isNull(calDriverScheduling.getDriverScheduling())) {
            log.info("当天没有满足要求的数据:dateTime:[{}],signIn:[{}],scheduling:[{}]", dateTime, signIn, JSON.toJSONString(scheduling));
            saveSignOfNoScheduling(signIn, ErrorTypeProperties.WORK_DAY_ERROR);
            return AjaxResult.success(ErrorTypeProperties.WORK_DAY_ERROR);
        }

        scheduling = calDriverScheduling.getDriverScheduling();

        if (Objects.isNull(scheduling.getSignInId())) {
            switchAndChooseTime(signIn, scheduling, dateTime);
            switchAndChooseAlcohol(signIn, driver, scheduling);

        } else {
            SignInV1 sourceSign = getById(scheduling.getSignInId());
            if (Objects.nonNull(sourceSign)) {
                switchAndChooseTime(signIn, scheduling, dateTime);
                switchAndChooseAlcohol(signIn, driver, scheduling);
            }
        }
        return saveData(signIn, scheduling, calDriverScheduling, driver, signInV1);
    }

    private AjaxResult saveData(SignIn signIn, DriverScheduling scheduling, CalDriverScheduling calDriverScheduling, Driver driver, SignInV1 signInV1) {
        signInMapper.insertSignIn(signIn);
        // 更新考勤
        if (Objects.nonNull(calDriverScheduling)) {
            schedulingService.computedSignInBySignIn(scheduling, calDriverScheduling.getIndex(), signIn);
        }

        if (TempCache.checkJobCodeExist(signIn.getJobCode())) {
            TempCache.updateSignStatus(signIn.getJobCode());
        }

        // 异常保存到异常异常中
        threadJobService.asyncInsertExceptionRecord(signIn, driver, scheduling);

        return handleAjaxResult(signIn, signInV1);
    }


    private AjaxResult handleAjaxResult(SignIn signIn, SignInV1 signInV1) {

        // 酒精测试后续恢复的需要删除异常的酒测缓存
        BeanUtils.copyProperties(signIn, signInV1);
        if (SIGN_IN_SUCCESS.equals(signIn.getStatus())) {
            String prompt = signIn.getRemark().replace("正常", "");
            if (signIn.getType().equals(SIGN_OUT)) {
                return AjaxResult.success(SIGN_OUT_SUCCESS_STRING + "," + prompt, signInV1);
            } else {
                return AjaxResult.success(SIGN_IN_SUCCESS_STRING + "," + prompt, signInV1);
            }
        } else {
            if (signIn.getType().equals(SIGN_OUT)) {
                return AjaxResult.success(SIGN_OUT_ERROR + ":" + signIn.getRemark(), signInV1);
            }
            return AjaxResult.success(SIGN_IN_ERROR + ":" + signIn.getRemark(), signInV1);
        }
    }


    /***
     *  判断是否酒驾;范围 0 =未做酒测;1=酒测;2=酒测正常
     * @author liujun
     * @date 2024/9/23 10:56
     *
     * @param signIn
     * @param driver
     * @param scheduling
     * @return java.lang.Integer
     */
    private Integer switchAndChooseAlcohol(SignIn signIn, Driver driver, DriverScheduling scheduling) {
        // 酒精测试校验 确定 且员工工种是驾驶员
        if (ConstSignInConstSignInProperties.ALCOHOL_FLAG_YES.equals(signIn.getAlcoholFlag()) && ConstDriverProperties.PERSONNEL_POSTS_DRIVER.equals(driver.getPosts())) {
            if (org.apache.commons.lang3.StringUtils.isEmpty(signIn.getIp())) {
                signIn.setIp(IpUtils.getIpAddr());
            }
            Integer extype = Objects.isNull(signIn.getExType()) ? 0 : signIn.getExType();
            if (checkAlcoholIntake(signIn.getAlcoholIntake())) {
                threadJobService.asyncSendEmail(scheduling, signIn, driver);
                signIn.setRemark(join(signIn.getRemark(), ErrorTypeProperties.ALCOHOL_SIGN_IN_ERROR, signIn.getAlcoholIntake().toString(), "mg/100ml。"));
                signIn.setExType(extype + ConstSignInConstSignInProperties.SIGN_ALCOHOL_EX_NUM);

                signIn.setStatus(ConstSignInConstSignInProperties.SIGN_IN_FAIL);
                signIn.setRemark(signIn.getRemark().replaceFirst(",$", "。"));

                return 1;
            } else {
                // 如果驾驶员酒精测试在之前不合格 必须重测
                String key = GlobalRedisPreName.REDIS_SIGN_IN_DRIVER_ALCOHOL_OVERFLOW + ConstDateUtil.formatDate("yyyyMMdd") + ":" + driver.getJobCode();
                Integer count = redisCache.getCacheObject(key);
                if (!Objects.isNull(count)) {
                    redisCache.deleteObject(key);
                }
                if (Objects.isNull(signIn.getStatus()) || Objects.equals(signIn.getStatus(), ConstSignInConstSignInProperties.SIGN_IN_SUCCESS)) {
                    signIn.setStatus(ConstSignInConstSignInProperties.SIGN_IN_SUCCESS);
                }
                extype = extype > 9 ? extype : extype + ConstSignInConstSignInProperties.SIGN_NO_EX_NUM;
                signIn.setExType(extype);
                if (Objects.equals(0, signIn.getExType())) {
                    signIn.setRemark("正常");
                }


                return 2;
            }
        }
        log.info("未做酒测:alcoholFlag[{}];posts:[{}]", signIn.getAlcoholFlag(), driver.getPosts());
        return 0;
    }

    private boolean checkAlcoholIntake(BigDecimal alcoholIntake) {
        return Objects.nonNull(alcoholIntake) ? new BigDecimal("20").compareTo(alcoholIntake) <= 0 : Boolean.FALSE;
    }

    private int switchAndChooseTime(SignIn signIn, DriverScheduling scheduling, long dateTime) {
        if (Objects.equals(2, signIn.getType())) {
            Date zdsj = new Date(scheduling.getZdsjT());

            Date date1 = org.apache.commons.lang3.time.DateUtils.addMinutes(zdsj, 80);
            String fcsjHHMM = HHMM.format(zdsj);
            String dzsjHHMM = HHMM.format(date1);

            String remark = org.apache.commons.lang3.StringUtils.join(ErrorTypeProperties.SIGN_OUT_TIMEOUT, "请在", fcsjHHMM, "到", dzsjHHMM, "之间打卡");
            return switchAndChooseTime(signIn, dateTime, zdsj, 80, remark);
        } else {
            Date fcsj = new Date(scheduling.getFcsjT());

            String fcsjHHMM = HHMM.format(org.apache.commons.lang3.time.DateUtils.addMinutes(fcsj, -60));
            String dzsjHHMM = HHMM.format(fcsj);

            String remark = org.apache.commons.lang3.StringUtils.join(ErrorTypeProperties.SIGN_IN_TIMEOUT, "请在", fcsjHHMM, "到", dzsjHHMM, "之间打卡");
            return switchAndChooseTime(signIn, dateTime, fcsj, -60, remark);
        }
    }

    private String join(String... strs) {
        int length = strs.length;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(strs[i])) {
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(builder.toString())) {
                    builder.append(";");
                }
                builder.append(strs[i]);
            }
        }
        return builder.toString();
    }

    /**
     * 判断时间是否是早签、正常、迟到
     *
     * @param signIn   签到数据
     * @param dateTime 打卡时间
     * @param date     发车或到站时间
     * @param value    允许的最大范围值
     * @param remark   提示信息模板
     * @author liujun
     * @date 2024/9/20 17:14
     */
    private int switchAndChooseTime(SignIn signIn, long dateTime, Date date, Integer value, String remark) {
        long time1 = date.getTime();
        date = org.apache.commons.lang3.time.DateUtils.addMinutes(date, value);
        long time = date.getTime();

        if (value < 0) {
            if (dateTime < time) {
                signIn.setExType(20);
                signIn.setRemark(remark);
                signIn.setStatus(2);

                return 1;
            } else if (dateTime > time1) {
                signIn.setExType(30);
                signIn.setRemark(remark);
                signIn.setStatus(2);

                return 2;
            }
        } else if (value > 0) {
            if (dateTime < time1) {
                signIn.setExType(20);
                signIn.setRemark(remark);
                signIn.setStatus(2);

                return 1;
            } else if (dateTime > time) {
                signIn.setExType(30);
                signIn.setRemark(remark);
                signIn.setStatus(2);

                return 2;
            }
        }

        signIn.setExType(0);
        signIn.setStatus(1);

        return 0;
    }

    /***
     *  在数据中找出最近一条的排班数据
     * @author liujun
     * @date 2024/9/20 17:08
     * @param schedulings 排班数据集合
     * @param dateTime 打开时间
     * @param type  签到类型
     * @return com.ruoyi.domain.DriverScheduling
     */
    private CalDriverScheduling findSchedulingByDateTime(List<DriverSchedulingV1> schedulings, long dateTime, String type) {

        AtomicInteger atomicInteger = new AtomicInteger(-1);
        Optional<DriverSchedulingV1> optional = schedulings.stream().map(s -> {
            atomicInteger.addAndGet(1);
            if (Objects.nonNull(s.getFcsjT()) && org.apache.commons.lang3.StringUtils.equalsAnyIgnoreCase(org.apache.commons.lang3.StringUtils.trim(s.getBcType()), type)) {
                s.setMinTime(Math.abs(s.getFcsjT() - dateTime));
            } else {
                s.setMinTime(Long.MAX_VALUE);
            }
            return s;
        }).min(Comparator.comparing(DriverScheduling::getMinTime));
        return new CalDriverScheduling(atomicInteger.get(), optional.orElse(null));
    }

    /**
     * 没有排班数据
     *
     * @param signIn
     * @param remark
     * @author liujun
     * @date 2024/9/20 16:41
     */
    private void saveSignOfNoScheduling(SignIn signIn, String remark) {
        signIn.setRemark(remark);
        signIn.setExType(2);
        signIn.setStatus(2);
        signIn.setType(1);

    }

    private void uploadImage(SignIn signIn) throws IOException {
        String base64 = signIn.getImage();
        // 图片路径
        String filePath = RuoYiConfig.getUploadPath();
        // 固定jpg文件
        String fileName = "";
        // 看是否带有base64前缀 有就判断文件类型 没有默认jpg
        fileName = checkImageBase64Format(signIn.getImage());
        fileName = extractFilename(fileName);
        // 获取相对路径
        String absPath = getAbsoluteFile(filePath, fileName).getAbsolutePath();

        // 获取文件上传路径
        String pathFileName = getPathFileName(filePath, fileName);
        signIn.setImage(pathFileName);
        signIn.setImage(signIn.getImage());
        log.info("开始异步上传签到图片");
        // 异步上传文件
        threadJobService.asyncStartUploadBase64Image(absPath, base64);
    }

    /**
     * 检查文件类型
     *
     * @param base64ImgData
     * @return
     */
    public static String checkImageBase64Format(String base64ImgData) {
        byte[] b = Base64.getDecoder().decode(base64ImgData);
        String type = "";
        if (0x424D == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = "bmp";
        } else if (0x8950 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = "png";
        } else {
            type = "jpg";
        }
//        else if (0xFFD8 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
//            type = "jpg";
//        }
        return type;
    }

    /**
     * 获取扩展文件名
     *
     * @param extendFileName
     * @return
     */
    private String extractFilename(String extendFileName) {
        return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
                FilenameUtils.getBaseName(UUID.randomUUID().toString().replace("-", "")), Seq.getId(Seq.uploadSeqType), extendFileName);
    }

    /**
     * 获取相对路径名
     *
     * @param uploadDir
     * @param fileName
     * @return
     * @throws IOException
     */
    private File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

    /**
     * @param uploadDir
     * @param fileName
     * @return
     * @throws IOException
     */
    private String getPathFileName(String uploadDir, String fileName) throws IOException {
        int dirLastIndex = RuoYiConfig.getProfile().length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        return Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
    }


}