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.entity.ClockInfo;
import com.yh.saas.plugin.yiliangyiyun.entity.LeaveInfo;
import com.yh.saas.plugin.yiliangyiyun.entity.QualityInspectionManagement;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.LeaveInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.service.IClockInfoService;
import com.yh.saas.plugin.yiliangyiyun.service.ILeaveInfoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.service.INewWorkflowService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 记录请假信息 服务实现类
 * </p>
 *
 * @author Gdc
 * @since 2022-06-22
 */
@Service
public class LeaveInfoServiceImpl extends ServiceImpl<LeaveInfoMapper, LeaveInfo> implements ILeaveInfoService {
    @Autowired
    private IClockInfoService clockInfoService;
    @Autowired
    private INewWorkflowService workflowService;
    @Autowired
    private ILeaveInfoService leaveInfoService;

    /**
     * 添加请假信息
     *
     * @param leaveInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addLeave(LeaveInfo leaveInfo) {
        //当天零点
        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);
        String ClockId = IdGenerator.generateUUID();
        //新增主键id
        leaveInfo.setId(IdGenerator.generateUUID());
        leaveInfo.setClockId(ClockId);

        //获取当前年月日
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String date = f.format(new Date(System.currentTimeMillis()));
        //查询信息数量包括已删除的集合
        List<LeaveInfo> leaveInfoList = this.selectLeaveNoList(leaveInfo);//调用Service中的方法
        //生成请假编号
        if (leaveInfoList.size() > 0) {
            //取第一条数据的编号
            String n = leaveInfoList.get(0).getLeaveNo();
            //截取编号后4位
            int intNumber = Integer.parseInt(n.substring(13));
            intNumber++;
            String Number = String.valueOf(intNumber);
            for (int i = 0; i < 4; i++) {
                Number = Number.length() < 4 ? "0" + Number : Number;
            }
            //编号自增
            Number = "QJ" + date + Number;
            leaveInfo.setLeaveNo(Number);
        } else {
            //如果当天数据为空，生成第一条数据
            String Number = "QJ" + date + "0001";
            leaveInfo.setLeaveNo(Number);
        }
        if (leaveInfo.getLeaveNo().contains("null")) {
            throw new YException(YExceptionEnum.QUALITY_HAVE_ERROR);
        }

        this.insert(leaveInfo);
        boolean isStartWorkflow = StringUtils.isBlank(leaveInfo.getWorkflowId());
        // 不是退回的单子
        if (isStartWorkflow) {
            Workflow workflow = workflowService
                    .findLatestWorkflowByBusinessCodeByApp(leaveInfo.getCompId(), "QINGJIA-APPROVE");
            // 没配置审核流程，直接结束并处理信息
            if (workflow == null) {
                throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
            }
            // 开启审核流
            else {
                // 设置状态 已提交审核
                leaveInfo.setWorkflowId(workflow.getId());
                leaveInfoService.updateById(leaveInfo);
                workflowService.startInstance(workflow.getId(), leaveInfo.getId());
            }
        }
        // 退回的单子 再启用
        else {
            leaveInfoService.updateById(leaveInfo);
            workflowService.activateInstance(leaveInfo.getWorkflowId(), leaveInfo.getId());
        }
        //查询打卡信息
        ClockInfo clockInfo1 = clockInfoService.selectOne(new EntityWrapper<ClockInfo>()
                .eq("comp_id", leaveInfo.getCompId())
                .eq("common_id", leaveInfo.getCommonId())
                .eq("delete_flag", "0")
                .gt("create_date", timeOfDay));
        if (clockInfo1 != null) {
            clockInfo1.setLeaveId(leaveInfo.getId());
            clockInfo1.setLeaveType(leaveInfo.getLeaveType());
            //修改数据
            clockInfoService.updateById(clockInfo1);
        } else {
            //新增打卡信息
            ClockInfo clockInfo = new ClockInfo();
            clockInfo.setId(ClockId);
            clockInfo.setLeaveId(leaveInfo.getId());
            clockInfo.setCommonId(leaveInfo.getCommonId());
            clockInfo.setCompId(leaveInfo.getCompId());
            clockInfo.setDept(leaveInfo.getDept());
            clockInfo.setEmpName(leaveInfo.getEmpName());
            clockInfo.setPhone(leaveInfo.getPhone());
            clockInfo.setLeaveType(leaveInfo.getLeaveType());
            clockInfoService.insert(clockInfo);
        }
        return "OK";

    }

    /**
     * 请假记录查询
     *
     * @param leaveInfo
     * @return
     */
    @Override
    public Page<LeaveInfo> selectLeaveInfo(LeaveInfo leaveInfo) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (leaveInfo.getCurrentPage() - 1)
                * leaveInfo.getPageSize());
        //  公司ID
        pageView.put("compId", leaveInfo.getCompId());
        pageView.put("commonId", leaveInfo.getCommonId());
        pageView.put("pageSize", leaveInfo.getPageSize());
        pageView.put("currentPage", leaveInfo.getCurrentPage());
        // 查询总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<LeaveInfo> dataList = baseMapper.getListByCondition(pageView);
        Page<LeaveInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(leaveInfo.getCurrentPage());
        page.setSize(leaveInfo.getPageSize());
        return page;
    }

    /**
     * 请假记录查询(PC)
     *
     * @param leaveInfo
     * @return
     */
    @Override
    public Page<LeaveInfo> selectLeaveInfoPc(LeaveInfo leaveInfo) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (leaveInfo.getCurrentPage() - 1)
                * leaveInfo.getPageSize());
        //  公司ID
        pageView.put("compId", leaveInfo.getCompId());
        pageView.put("pageSize", leaveInfo.getPageSize());
        pageView.put("currentPage", leaveInfo.getCurrentPage());
        pageView.put("searchKeyWord", leaveInfo.getSearchKeyWord());
        pageView.put("theStartDate", leaveInfo.getTheStartDate());
        pageView.put("theEndDate", leaveInfo.getTheEndDate());
        // 查询总数
        Integer dataCount = baseMapper.getCountByConditionPc(pageView);
        List<LeaveInfo> dataList = baseMapper.getListByConditionPc(pageView);
        Page<LeaveInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(leaveInfo.getCurrentPage());
        page.setSize(leaveInfo.getPageSize());
        return page;
    }

    /**
     * 查看请假信息
     *
     * @param id
     * @return
     */
    @Override
    public LeaveInfo getLeaveInfo(String id) {
        //根据id查询补卡信息
        LeaveInfo leaveInfo = this.selectById(id);
        String taskId = "";
        // 只有待审核状态才有taskId
        if (StringUtils.isNotBlank(leaveInfo.getWorkflowId())) {
            JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(leaveInfo.getWorkflowId()), leaveInfo.getId());
            taskId = jsonObject.getString("taskId");
            leaveInfo.setTaskId(taskId);
        }
        return leaveInfo;
    }

    /**
     * 查询请假编号
     *
     * @param
     * @return
     */
    @Override
    public List<LeaveInfo> selectLeaveNoList(LeaveInfo leaveInfo) {
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String date = f.format(new Date(System.currentTimeMillis()));
        Map<String, Object> pageView = new HashMap<>(7);
        pageView.put("date", date);
        pageView.put("compId", leaveInfo.getCompId());
        List<LeaveInfo> dataList = baseMapper.getListByConditionLeave(pageView);
        return dataList;
    }
}
