package com.yh.saas.plugin.yiliangyiyun.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.winsea.svc.base.workflow.entity.Workflow;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.ClockInfo;
import com.yh.saas.plugin.yiliangyiyun.entity.FuelFillingInfo;
import com.yh.saas.plugin.yiliangyiyun.entity.LeaveInfo;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.ClockInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.service.IClockInfoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.service.INewWorkflowService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 记录打卡信息 服务实现类
 * </p>
 *
 * @author Gdc
 * @since 2022-06-11
 */
@Service
public class ClockInfoServiceImpl extends ServiceImpl<ClockInfoMapper, ClockInfo> implements IClockInfoService {
    @Autowired
    private IClockInfoService clockInfoService;
    @Autowired
    private INewWorkflowService workflowService;

    /**
     * 添加打卡信息
     *
     * @param clockInfo
     * @return
     */
    @Override
    public String addClock(ClockInfo clockInfo) {
        //当天零点
        SimpleDateFormat now = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar a = Calendar.getInstance();
        a.setTime(new Date());
        a.add(Calendar.YEAR, 0);
        Date x = a.getTime();
        String timeOfDay = now.format(x);
        //早八
        SimpleDateFormat eight = new SimpleDateFormat("yyyy-MM-dd 08:00:00");
        Calendar b = Calendar.getInstance();
        b.setTime(new Date());
        b.add(Calendar.YEAR, 0);
        Date y = b.getTime();
        String timeOfEight = eight.format(y);
        //晚五
        SimpleDateFormat five = new SimpleDateFormat("yyyy-MM-dd 17:00:00");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, 0);
        Date z = c.getTime();
        String timeOfFive = five.format(z);
        //获取当前系统时间
        Date date = new Date();
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = s.format(date);
        //查询打卡信息
        ClockInfo clockInfo1 = this.selectOne(new EntityWrapper<ClockInfo>()
                .eq("comp_id", clockInfo.getCompId())
                .eq("common_id", clockInfo.getCommonId())
                .eq("delete_flag", "0")
                .gt("create_date", timeOfDay));
        //信息不为空
        if (clockInfo1 != null) {
            if ("3".equals(clockInfo.getClockType())) {
                if (timeOfFive.compareTo(currentTime) > 0 && clockInfo1.getLeaveId() == null) {
                    //早退
                    clockInfo1.setLeaveEarlyFlag("1");
                }
                clockInfo1.setOffClockDate(date);
            } else {
                clockInfo1.setToClockDate(date);
            }
            //更新主表数据
            this.updateById(clockInfo1);
        }
        //信息为空
        else {
            clockInfo.setId(IdGenerator.generateUUID());
            //下班打卡
            if ("3".equals(clockInfo.getClockType())) {
                if (timeOfFive.compareTo(currentTime) > 0) {
                    //早退
                    clockInfo.setLeaveEarlyFlag("1");
                }
                clockInfo.setOffClockDate(date);
            }
            //上班打卡
            else {
                if (currentTime.compareTo(timeOfEight) > 0) {
                    //迟到
                    clockInfo.setLateFlag("1");
                }
                clockInfo.setToClockDate(date);
            }
            //操作主表数据
            this.insert(clockInfo);
        }
        return "OK";
    }

    /**
     * 打卡记录
     *
     * @param clockInfo
     * @return
     */
    @Override
    public Page<ClockInfo> selectClockInfo(ClockInfo clockInfo) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (clockInfo.getCurrentPage() - 1)
                * clockInfo.getPageSize());
        //  公司ID
        pageView.put("compId", clockInfo.getCompId());
        pageView.put("commonId", clockInfo.getCommonId());
        pageView.put("pageSize", clockInfo.getPageSize());
        pageView.put("yearMonth", clockInfo.getYearMonth());
        pageView.put("currentPage", clockInfo.getCurrentPage());
        // 查询总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<ClockInfo> dataList = baseMapper.getListByCondition(pageView);
        dataList.forEach(clockInfo1 -> {
            String taskId = "";
            // 只有待审核状态才有taskId
            if (StringUtils.isNotBlank(clockInfo1.getWorkflowId())) {
                JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(clockInfo1.getWorkflowId()), clockInfo1.getId());
                taskId = jsonObject.getString("taskId");
                clockInfo1.setTaskId(taskId);
            }

        });
        Page<ClockInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(clockInfo.getCurrentPage());
        page.setSize(clockInfo.getPageSize());
        return page;
    }

    /**
     * 考勤记录(PC)
     *
     * @param clockInfo
     * @return
     */
    @Override
    public Page<ClockInfo> selectClockInfoPc(ClockInfo clockInfo) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (clockInfo.getCurrentPage() - 1)
                * clockInfo.getPageSize());
        //  公司ID
        pageView.put("compId", clockInfo.getCompId());
        pageView.put("pageSize", clockInfo.getPageSize());
        pageView.put("currentPage", clockInfo.getCurrentPage());
        pageView.put("searchKeyWord", clockInfo.getSearchKeyWord());
        pageView.put("startDate", clockInfo.getStartDate());
        pageView.put("endDate", clockInfo.getEndDate());
        // 查询总数
        Integer dataCount = baseMapper.getCountByConditionPc(pageView);
        List<ClockInfo> dataList = baseMapper.getListByConditionPc(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            for (ClockInfo clockInfo1 : dataList) {
                List<ClockInfo> clockInfoList = clockInfoService.selectList(new EntityWrapper<ClockInfo>()
                        .eq("comp_id", clockInfo1.getCompId())
                        .eq("common_id", clockInfo1.getCommonId())
                        .eq("delete_flag", "0"));
                if (CollectionUtils.isNotEmpty(clockInfoList)) {
                    clockInfo1.setClockInfoList(clockInfoList);
                }
            }
        }
        Page<ClockInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(clockInfo.getCurrentPage());
        page.setSize(clockInfo.getPageSize());
        return page;
    }

    /**
     * 添加补卡信息
     *
     * @param clockInfo1
     * @return
     */
    @Override
    public String suppClock(ClockInfo clockInfo1) {
        //查询打卡信息
        ClockInfo clockInfo = this.selectById(clockInfo1.getId());
        if (clockInfo != null) {
            clockInfo.setSupplementClockType(clockInfo1.getSupplementClockType());
            clockInfo.setReasonForApplication(clockInfo1.getReasonForApplication());
            this.updateById(clockInfo);

            boolean isStartWorkflow = StringUtils.isBlank(clockInfo.getWorkflowId());
            // 不是退回的单子
            if (isStartWorkflow) {
                Workflow workflow = workflowService
                        .findLatestWorkflowByBusinessCodeByApp(clockInfo.getCompId(), "BUKA-APPROVE");
                // 没配置审核流程，直接结束并处理信息
                if (workflow == null) {
                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                }
                // 开启审核流
                else {
                    // 设置状态 已提交审核
                    clockInfo.setWorkflowId(workflow.getId());
                    clockInfoService.updateById(clockInfo);
                    workflowService.startInstance(workflow.getId(), clockInfo.getId());
                }
            }
            // 退回的单子 再启用
            else {
                clockInfoService.updateById(clockInfo);
                workflowService.activateInstance(clockInfo.getWorkflowId(), clockInfo.getId());
            }
        }
        return "OK";
    }
    /**
     * 查看补卡信息
     * @param id
     * @return
     */
    @Override
    public ClockInfo getSuppClock(String id) {
        //根据id查询补卡信息
        ClockInfo clockInfo = this.selectById(id);
        String taskId = "";
        // 只有待审核状态才有taskId
        if (StringUtils.isNotBlank(clockInfo.getWorkflowId())) {
            JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(clockInfo.getWorkflowId()), clockInfo.getId());
            taskId = jsonObject.getString("taskId");
            clockInfo.setTaskId(taskId);
        }
        return clockInfo;
    }
}