package com.ruoyi.system.service.impl;

import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.model.MqttMessage;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.KaoqinConfig;
import com.ruoyi.system.domain.KaoqinRecord;
import com.ruoyi.system.mapper.KaoqinConfigMapper;
import com.ruoyi.system.mapper.KaoqinRecordMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IKaoqinRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import static com.ruoyi.common.constant.Constants.*;


/**
 * 考勤记录Service业务层处理
 *
 * @author boman
 * @date 2023-02-09
 */
@Service
public class KaoqinRecordServiceImpl implements IKaoqinRecordService {
    @Autowired
    private KaoqinRecordMapper kaoqinRecordMapper;

    @Autowired
    private KaoqinConfigMapper kaoqinConfigMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询考勤记录
     *
     * @param recordId 考勤记录主键
     * @return 考勤记录
     */
    @Override
    public KaoqinRecord selectKaoqinRecordByRecordId(Long recordId) {
        return kaoqinRecordMapper.selectKaoqinRecordByRecordId(recordId);
    }

    /**
     * 查询考勤记录列表
     *
     * @param kaoqinRecord 考勤记录
     * @return 考勤记录
     */
    @Override
    public List<KaoqinRecord> selectKaoqinRecordList(KaoqinRecord kaoqinRecord) {
        // 判断角色
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!"admin".equals(user.getUserName())) {
            List<SysRole> roles = user.getRoles();
            Boolean bl = false;
            for (SysRole role : roles) {
                if ("conservator".equals(role.getRoleKey())) {
                    bl = true;
                    break;
                }
            }
            if (bl) {
                kaoqinRecord.setDeptId(user.getDeptId());
            } else {
                kaoqinRecord.setUserId(user.getUserId());
            }
        }

        return kaoqinRecordMapper.selectKaoqinRecordList(kaoqinRecord);
    }

    /**
     * 新增考勤记录
     *
     * @param kaoqinRecord 考勤记录
     * @return 结果
     */
    @Override
    public int insertKaoqinRecord(KaoqinRecord kaoqinRecord) {
        //获取当前人员信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String ancestors = kaoqinRecord.getAncestors();
        Long deptId = kaoqinRecord.getDeptId();
        ancestors = ancestors + "," + deptId;
        kaoqinRecord.setAncestors(ancestors);
        kaoqinRecord.setCreateTime(DateUtils.getNowDate());
        kaoqinRecord.setPhone(user.getPhonenumber());
        return kaoqinRecordMapper.insertKaoqinRecord(kaoqinRecord);
    }

    /**
     * 修改考勤记录
     *
     * @param kaoqinRecord 考勤记录
     * @return 结果
     */
    @Override
    public int updateKaoqinRecord(KaoqinRecord kaoqinRecord) {
        kaoqinRecord.setUpdateTime(DateUtils.getNowDate());
        return kaoqinRecordMapper.updateKaoqinRecord(kaoqinRecord);
    }

    /**
     * 批量删除考勤记录
     *
     * @param recordIds 需要删除的考勤记录主键
     * @return 结果
     */
    @Override
    public int deleteKaoqinRecordByRecordIds(Long[] recordIds) {
        return kaoqinRecordMapper.deleteKaoqinRecordByRecordIds(recordIds);
    }

    /**
     * 删除考勤记录信息
     *
     * @param recordId 考勤记录主键
     * @return 结果
     */
    @Override
    public int deleteKaoqinRecordByRecordId(Long recordId) {
        return kaoqinRecordMapper.deleteKaoqinRecordByRecordId(recordId);
    }

    @Async("threadPoolTaskExecutor")
    @Override
    public void faceDate(MqttMessage message) {
        /**
         * 返回值为
         {
         "filename":"文件名（id_name）",
         "time":"时间 （yyyy-MM-dd HH:mm:ss）"
         }
         */
        String payload = message.getPayload();
        JSONObject jsonObject = JSONObject.parseObject(payload);
        String filename = jsonObject.getString("filename");
        String time = jsonObject.getString("time");
        String userId = filename.split("_")[0];
        String nickName = filename.split("_")[1];
        String date = time.split(" ")[0];
        //查询打卡信息
        KaoqinRecord kaoqinRecord = kaoqinRecordMapper.selectKaoqinRecordByRecordByUser(Long.parseLong(userId), date);
        //查询考勤规则
        KaoqinConfig kaoqinConfig = kaoqinConfigMapper.selectKaoqinConfigBynew();
        if (kaoqinRecord == null) {
            //根据id查询人员信息
            SysUser sysUser = sysUserMapper.selectUserById(Long.parseLong(userId));
            String[] dates = date.split("-");
            KaoqinRecord kaoqinRecords = new KaoqinRecord();
            kaoqinRecords.setUserId(Long.parseLong(userId));
            kaoqinRecords.setUserName(sysUser.getNickName());
            kaoqinRecords.setPhone(sysUser.getPhonenumber());
            kaoqinRecords.setDeptId(sysUser.getDeptId());
            kaoqinRecords.setDeptName(sysUser.getDept().getDeptName());
            kaoqinRecords.setAncestors(sysUser.getDept().getAncestors());
            kaoqinRecords.setKaYear(dates[0]);
            kaoqinRecords.setKaMonth(dates[1]);
            kaoqinRecords.setKaDay(dates[2]);
            kaoqinRecords.setKaWeek(DateUtils.dateToWeek(date));
            kaoqinRecords.setKaTime(date);
            kaoqinRecords.setCreateTime(DateUtils.getNowDate());
            //此次打卡为第一次打卡
            //判断是否在上班卡之前打卡
            if (DateUtils.compareTimes(time.split(" ")[1], DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimeAmIn()), "HH:mm:ss") <= 0) {
                //在上班之前打卡
                kaoqinRecords.setKaTimeAmIn(DateUtils.parseDate(time.split(" ")[1]));
                kaoqinRecords.setKaTypeAmIn(ONE);
                kaoqinRecords.setKaStatus(ONE);

            } else {
                //在上班之后打卡
                //判断配置要打几次卡
                if (TWO.equals(kaoqinConfig.getKaNum())) {
                    kaoqinRecords.setKaNum(TWO);
                    if (DateUtils.compareTimes(time.split(" ")[1], DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimePmOut()), "HH:mm:ss") >= 0) {
                        //正常下班
                        kaoqinRecords.setKaTypeAmIn(FIVE);
                        kaoqinRecords.setKaTimePmOut(DateUtils.parseDate(time.split(" ")[1]));
                        kaoqinRecords.setKaTypePmOut(ONE);
                    } else {
                        //迟到
                        kaoqinRecords.setKaTimeAmIn(DateUtils.parseDate(time.split(" ")[1]));
                        kaoqinRecords.setKaTypeAmIn(TWO);
                    }

                } else if (FOUR.equals(kaoqinConfig.getKaNum())) {
                    if (DateUtils.isInTimeRange(time.split(" ")[1], DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimeAmIn()), DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimeAmOut()))) {
                        //迟到
                        kaoqinRecords.setKaTimeAmIn(DateUtils.parseDate(time.split(" ")[1]));
                        kaoqinRecords.setKaTypeAmIn(TWO);

                    } else if (DateUtils.isInTimeRange(time.split(" ")[1], DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimeAmOut()), DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimePmIn()))) {
                        //上午正常下班 打卡类别-上午下班 1正常 2:迟到 3:外勤 4:早退
                        kaoqinRecords.setKaTypeAmIn(FIVE);
                        kaoqinRecords.setKaTimeAmOut(DateUtils.parseDate(time.split(" ")[1]));
                        kaoqinRecords.setKaTypeAmOut(ONE);
                        kaoqinRecord.setKaTimePmIn(DateUtils.parseDate(time.split(" ")[1]));
                        kaoqinRecord.setKaTypePmIn(ONE);

                    } else if (DateUtils.isInTimeRange(time.split(" ")[1], DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimePmIn()), DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimePmOut()))) {
                        //下午迟到 打卡类别-上午下班 1正常 2:迟到 3:外勤 4:早退
                        kaoqinRecords.setKaTypeAmIn(FIVE);
                        kaoqinRecords.setKaTypeAmOut(FIVE);
                        kaoqinRecord.setKaTimePmIn(DateUtils.parseDate(time.split(" ")[1]));
                        kaoqinRecord.setKaTypePmIn(TWO);

                    } else if (DateUtils.compareTimes(time.split(" ")[1], DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimePmOut()), "HH:mm:ss") >= 0) {
                        //下午正常下班
                        kaoqinRecords.setKaTypeAmIn(FIVE);
                        kaoqinRecords.setKaTypeAmOut(FIVE);
                        kaoqinRecord.setKaTypePmIn(FIVE);
                        kaoqinRecords.setKaTimePmOut(DateUtils.parseDate(time.split(" ")[1]));
                        kaoqinRecords.setKaTypePmOut(ONE);
                    }
                }
            }
            kaoqinRecordMapper.insertKaoqinRecord(kaoqinRecords);
        } else {
            if (DateUtils.compareTimes(time.split(" ")[1], DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimeAmIn()), "HH:mm:ss") <= 0) {
                //在上班之前打卡
                kaoqinRecord.setKaTimeAmIn(DateUtils.parseDate(time.split(" ")[1]));
                kaoqinRecord.setKaTypeAmIn(ONE);
                kaoqinRecord.setKaStatus(ONE);

            } else {
                if (TWO.equals(kaoqinConfig.getKaNum())) {
                    if (DateUtils.compareTimes(time.split(" ")[1], DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimePmOut()), "HH:mm:ss") >= 0) {
                        //正常下班
                        kaoqinRecord.setKaTimePmOut(DateUtils.parseDate(time.split(" ")[1]));
                        kaoqinRecord.setKaTypePmOut(ONE);
                    } else {
                        //早退
                        kaoqinRecord.setKaTimePmOut(DateUtils.parseDate(time.split(" ")[1]));
                        kaoqinRecord.setKaTypePmOut(FOUR);
                    }

                } else if (FOUR.equals(kaoqinConfig.getKaNum())) {
                    if (DateUtils.isInTimeRange(time.split(" ")[1], DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimeAmIn()), DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimeAmOut()))) {
                        if (StringUtils.isNotBlank(kaoqinRecord.getKaTypeAmIn())) {
                            //早退 打卡类别-上午下班 1正常 2:迟到 3:外勤 4:早退
                            kaoqinRecord.setKaTimeAmOut(DateUtils.parseDate(time.split(" ")[1]));
                            kaoqinRecord.setKaTypeAmOut(FOUR);
                        } else {
                            //迟到
                            kaoqinRecord.setKaTimeAmIn(DateUtils.parseDate(time.split(" ")[1]));
                            kaoqinRecord.setKaTypeAmIn(TWO);
                        }

                    } else if (DateUtils.isInTimeRange(time.split(" ")[1], DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimeAmOut()), DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimePmIn()))) {
                        if (StringUtils.isNotBlank(kaoqinRecord.getKaTypeAmOut())) {
                            //下午正常上班 打卡类别-上午下班 1正常 2:迟到 3:外勤 4:早退
                            kaoqinRecord.setKaTimePmIn(DateUtils.parseDate(time.split(" ")[1]));
                            kaoqinRecord.setKaTypePmIn(ONE);
                        } else {
                            //上午正常下班
                            kaoqinRecord.setKaTimeAmOut(DateUtils.parseDate(time.split(" ")[1]));
                            kaoqinRecord.setKaTypeAmOut(ONE);
                        }
                    } else if (DateUtils.isInTimeRange(time.split(" ")[1], DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimePmIn()), DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimePmOut()))) {
                        if (StringUtils.isNotBlank(kaoqinRecord.getKaTypePmIn())) {
                            //下午早退
                            kaoqinRecord.setKaTimePmOut(DateUtils.parseDate(time.split(" ")[1]));
                            kaoqinRecord.setKaTypePmOut(FOUR);
                        } else {
                            //下午迟到 打卡类别-上午下班 1正常 2:迟到 3:外勤 4:早退
                            kaoqinRecord.setKaTimePmIn(DateUtils.parseDate(time.split(" ")[1]));
                            kaoqinRecord.setKaTypePmIn(TWO);
                        }
                    } else if (DateUtils.compareTimes(time.split(" ")[1], DateUtils.parseDateToStr("HH:mm:ss", kaoqinConfig.getKaTimePmOut()), "HH:mm:ss") >= 0) {
                        //下午正常下班
                        kaoqinRecord.setKaTimePmOut(DateUtils.parseDate(time.split(" ")[1]));
                        kaoqinRecord.setKaTypePmOut(ONE);
                    }
                }
            }
            kaoqinRecordMapper.updateKaoqinRecord(kaoqinRecord);
        }
    }
}
