package jnpf.workflow.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.AttendanceGoOutApprove;
import jnpf.enums.attendance.ApprovalSettingTypeEnum;
import jnpf.enums.attendance.AttendanceNoticeEnum;
import jnpf.model.attendance.dto.GoOutApproveForOaDto;
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.AttendanceGoOutApproveDto;
import jnpf.model.workflow.vo.AttendanceGoOutApproveVo;
import jnpf.permission.model.user.PartUserInfoVo;
import jnpf.util.*;
import jnpf.workflow.mapper.GoOutApproveMapper;
import jnpf.workflow.service.FlowTaskService;
import jnpf.workflow.service.GoOutApproveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @Author huanglinpan
 * @Date 2024/5/14 18:32
 * @Version 1.0 （版本号）
 */
@Service
@Slf4j
public class GoOutApproveServiceImpl extends SuperServiceImpl<GoOutApproveMapper, AttendanceGoOutApprove> implements GoOutApproveService {

    @Autowired
    private UserAntifreeze userAntifreeze;

    @Resource
    private FlowTaskService flowTaskService;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AttendanceNoticeHandler attendanceNoticeHandler;

    @Resource
    private CustomTenantUtil customTenantUtil;

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

    private void goOutSendIm(AttendanceGoOutApprove entity, String tenantId) {
        //张三的【外出】审批
        //开始时间：2024年5月16日
        //结束时间：2024年5月17日
        //时长：2天
        customTenantUtil.checkOutTenant(tenantId);
        // 查询第一节点审批人
        ApproverByTaskIdAndNodeIdVo data = flowTaskService.getApproveInfo(entity.getId(), null, tenantId, null);
        if (null != data) {
            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.GO_OUT.getCode());
            approveBaseImVo.setStartTime(entity.getStartTime());
            approveBaseImVo.setEndTime(entity.getEndTime());
            approveBaseImVo.setDuration(entity.getDayNum() + "天");
            StringBuilder stringBuffer = new StringBuilder();
            if (!Objects.isNull(partUserInfoVo)) {
                stringBuffer.append(partUserInfoVo.getRealName());
            }
            approveBaseImVo.setTitle(stringBuffer.append("的【外出】审批").toString());
            data.getUserOperators().forEach(v -> {
                // 每个人的这个Id不同，所以轮询触发
                jsonToBean.setTaskId(v.getTaskOperatorId());
                // URL 拼接
//                String encode = Base64Util.encode(JSONUtil.toJsonStr(jsonToBean));
                String encode = FtbUtil.encodeJson(jsonToBean);
                String url = AttendanceConstant.APPROVE_URL + encode;
                approveBaseImVo.setUrl(url);
                approveImVo.setUserIds(CollUtil.newArrayList(v.getUserId()));
                approveImVo.setApproveBaseImVo(approveBaseImVo);
                attendanceNoticeHandler.send(approveImVo);
            });
        }
    }

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

    @Override
    public AttendanceGoOutApproveVo getOne(String id) {
        AttendanceGoOutApprove attendanceLeaveApprove = this.getById(id);
        return JsonUtil.getJsonToBean(attendanceLeaveApprove, AttendanceGoOutApproveVo.class);
    }

    @Override
    public List<AttendanceGoOutApprove> getBatchByIds(List<String> groupIds, List<String> ids) {
        LambdaQueryWrapper<AttendanceGoOutApprove> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(AttendanceGoOutApprove::getId, ids);
        queryWrapper.in(CollUtil.isNotEmpty(groupIds), AttendanceGoOutApprove::getGroupId, groupIds);
        List<AttendanceGoOutApprove> list = this.list(queryWrapper);
        return CollUtil.isNotEmpty(list) ? list : new ArrayList<>();
    }

    @Override
    public void saveForOa(GoOutApproveForOaDto dto) {
        AttendanceGoOutApprove entity = JsonUtil.getJsonToBean(dto, AttendanceGoOutApprove.class);
        entity.setGroupId(dto.getGroupId());
        log.error("FoeOa开始存数据库出差了参数................: {}", entity);
        save(entity);
    }
}
