package jnpf.workflow.service.impl;

import cn.hutool.core.collection.CollUtil;
import jnpf.attendance.antifreeze.UserAntifreeze;
import jnpf.attendance.service.handle.notice.AttendanceNoticeHandler;
import jnpf.base.service.SuperServiceImpl;
import jnpf.constants.AttendanceConstant;
import jnpf.engine.vo.ApproverByTaskIdAndNodeIdVo;
import jnpf.entity.workflow.AttendanceWorkOvertimeApprove;
import jnpf.enums.attendance.ApprovalSettingTypeEnum;
import jnpf.enums.attendance.AttendanceNoticeEnum;
import jnpf.model.attendance.vo.attendance.ApproveBaseImVo;
import jnpf.model.attendance.vo.attendance.ApproveImVo;
import jnpf.model.attendance.vo.attendance.AttendanceApproveImVo;
import jnpf.model.workflow.dto.AttendanceWorkOvertimeApproveDto;
import jnpf.model.workflow.vo.AttendanceWorkOvertimeApproveVo;
import jnpf.permission.model.user.PartUserInfoVo;
import jnpf.util.*;
import jnpf.workflow.mapper.AttendanceWorkOvertimeApproveMapper;
import jnpf.workflow.service.FlowTaskService;
import jnpf.workflow.service.WorkOvertimeApproveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * describe
 *
 * @author HuangLinPan
 * @date 2023/12/12
 */
@Service
public class WorkOvertimeApproveServiceImpl extends SuperServiceImpl<AttendanceWorkOvertimeApproveMapper, AttendanceWorkOvertimeApprove> implements WorkOvertimeApproveService {


    @Autowired
    private UserAntifreeze userAntifreeze;

    @Resource
    private FlowTaskService flowTaskService;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AttendanceNoticeHandler attendanceNoticeHandler;

    @Resource
    private CustomTenantUtil customTenantUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(String id, AttendanceWorkOvertimeApprove entity, AttendanceWorkOvertimeApproveDto attendanceWorkOvertimeApproveDto) {
        //表单信息
        if (StringUtil.isEmpty(entity.getId())) {
            entity.setId(id);
            save(entity);
//            String tenantId = userProvider.get().getTenantId();
//            new Thread(()->{
//                // 睡眠1秒，确保事务提交完成
//                try {
//                    Thread.sleep(1000);
//                    workSendIm(entity,tenantId);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }).start();
        } else {
            entity.setId(id);
            updateById(entity);
        }
    }

    private void workSendIm(AttendanceWorkOvertimeApprove entity,String tenantId) {
        //张三的【加班】审批
        //选择日期：2024年5月16日
        //开始时间：22:00
        //结束时间：次日08:00
        customTenantUtil.checkOutTenant(tenantId);
        // 查询第一节点审批人
        ApproverByTaskIdAndNodeIdVo data = flowTaskService.getApproveInfo(entity.getId(), null, tenantId,null);
        if (null == data) {
            return;
        }
        AttendanceApproveImVo jsonToBean = JsonUtil.getJsonToBean(data, AttendanceApproveImVo.class);
        jsonToBean.setId(data.getTaskId());
        List<PartUserInfoVo> allByIds = userAntifreeze.getAllByIds(CollUtil.newArrayList(entity.getUserId()), tenantId);
        PartUserInfoVo partUserInfoVo = allByIds.stream().findFirst().orElse(null);
        // 组装消息
        ApproveImVo approveImVo = new ApproveImVo();
        approveImVo.setTenantId(tenantId);
        approveImVo.setAttendanceNoticeEnum(AttendanceNoticeEnum.APPROVE);
        ApproveBaseImVo approveBaseImVo = new ApproveBaseImVo();
        approveBaseImVo.setType(ApprovalSettingTypeEnum.OVERTIME.getCode());
//        approveBaseImVo.setSelectTime(entity.getWorkDay());
        approveBaseImVo.setStartTime(entity.getStartTime());
        approveBaseImVo.setEndTime(entity.getEndTime());
        StringBuilder stringBuffer = new StringBuilder();
        if (!Objects.isNull(partUserInfoVo)) {
            stringBuffer.append(partUserInfoVo.getRealName());
        }
        approveBaseImVo.setTitle(stringBuffer.append("的【加班】审批").toString());
        data.getUserOperators().forEach(v->{
            jsonToBean.setTaskId(v.getTaskOperatorId());
            approveImVo.setUserIds(CollUtil.newArrayList(v.getUserId()));
            // URL 拼接
//                String encode = Base64Util.encode(JSONUtil.toJsonStr(jsonToBean));
            String encode = FtbUtil.encodeJson(jsonToBean);
            String url = AttendanceConstant.APPROVE_URL + encode;
            approveBaseImVo.setUrl(url);
            approveImVo.setApproveBaseImVo(approveBaseImVo);
            attendanceNoticeHandler.send(approveImVo);
        });
    }

    @Override
    public void submit(String id, AttendanceWorkOvertimeApprove entity, AttendanceWorkOvertimeApproveDto attendanceWorkOvertimeApproveDto) {
        //表单信息
        if (StringUtil.isEmpty(entity.getId())) {
            entity.setId(id);
            save(entity);
//            String tenantId = userProvider.get().getTenantId();
//            new Thread(()->{
//                // 睡眠1秒，确保事务提交完成
//                try {
//                    Thread.sleep(1000);
//                    workSendIm(entity,tenantId);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }).start();
        } else {
            entity.setId(id);
            updateById(entity);
        }
    }

    @Override
    public AttendanceWorkOvertimeApproveVo getAttendanceLeave(String id) {
        AttendanceWorkOvertimeApprove attendanceWorkOvertimeApprove = this.getById(id);
        AttendanceWorkOvertimeApproveVo jsonToBean = JsonUtil.getJsonToBean(attendanceWorkOvertimeApprove, AttendanceWorkOvertimeApproveVo.class);
        // 当审核未通过时动态取值
//        if (1 != jsonToBean.getStatus()){
            // 动态获取涉及班次/借调班次
//        }
        return jsonToBean;
    }

    @Override
    public void saveForOa(AttendanceWorkOvertimeApprove entity) {
        save(entity);
    }
}
