package jnpf.workflow.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import jnpf.attendance.antifreeze.UserAntifreeze;
import jnpf.attendance.service.AttendanceDailyRuleService;
import jnpf.attendance.service.handle.notice.AttendanceNoticeHandler;
import jnpf.base.service.SuperServiceImpl;
import jnpf.constants.AttendanceConstant;
import jnpf.engine.FlowTaskApi;
import jnpf.engine.vo.ApproverByTaskIdAndNodeIdVo;
import jnpf.entity.workflow.SelfApprove;
import jnpf.enums.attendance.ApprovalSettingTypeEnum;
import jnpf.enums.attendance.AttendanceNoticeEnum;
import jnpf.model.attendance.dto.WorkflowImQueryDto;
import jnpf.model.attendance.vo.AttendanceSelfApproveVo;
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.SelfApproveDto;
import jnpf.model.workflow.dto.UserSelfDto;
import jnpf.model.workflow.vo.SelfApproveVo;
import jnpf.permission.model.user.PartUserInfoVo;
import jnpf.util.*;
import jnpf.workflow.mapper.SelfApproveMapper;
import jnpf.workflow.mapper.SelfApproveUserMapper;
import jnpf.workflow.service.FlowTaskService;
import jnpf.workflow.service.SelfApproveService;
import org.apache.logging.log4j.util.Base64Util;
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/13
 */
@Service
public class SelfApproveServiceImpl extends SuperServiceImpl<SelfApproveMapper, SelfApprove> implements SelfApproveService {

    @Resource
    private SelfApproveUserMapper selfApproveUserMapper;

    @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, SelfApprove entity, SelfApproveDto selfApproveDto) {
        //表单信息
        if (StringUtil.isEmpty(entity.getId())) {
            entity.setId(id);
            save(entity);
            // 保存对应的用户集合
//            selfApproveUserMapper.addList(selfApproveDto.getUserIds(),id);
            selfApproveUserMapper.addUserList(selfApproveDto.getUserSelfDtos(),id);
            // 发送消息
//            String tenantId = userProvider.get().getTenantId();
//            new Thread(()->{
//                // 睡眠1秒，确保事务提交完成
//                try {
//                    Thread.sleep(1000);
//                    secondedSendIm(entity,tenantId);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }).start();
        } else {
            entity.setId(id);
            updateById(entity);
            // 删除以前绑定的用户集合
            selfApproveUserMapper.deleteById(id);
            // 保存对应的用户集合
//            selfApproveUserMapper.addList(selfApproveDto.getUserIds(),id);
            selfApproveUserMapper.addUserList(selfApproveDto.getUserSelfDtos(),id);
        }
    }

    private void secondedSendIm(SelfApprove entity,String tenantId) {
        //张三的【借调】审批
        //借调开始时间：2024年5月16日 16:23
        //借调结束时间：2024年5月17日 09:00
        //借调考勤组：小露测试考勤组
        //被借调考勤组：小露验收考勤组
        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.getCreatorUserId()), 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.SECONDED.getCode());
            approveBaseImVo.setStartTime(entity.getStartTime());
            approveBaseImVo.setEndTime(entity.getEndTime());
            approveBaseImVo.setGroupName(entity.getGroupName());
            approveBaseImVo.setSecondedGroupName(entity.getSelfGroupName());
            StringBuilder stringBuffer = new StringBuilder();
            if (!Objects.isNull(partUserInfoVo)) {
                stringBuffer.append(partUserInfoVo.getRealName());
            }
            approveBaseImVo.setTitle(stringBuffer.append("的【借调】审批").toString());
            data.getUserOperators().forEach(v->{
                approveImVo.setUserIds(CollUtil.newArrayList(v.getUserId()));
                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.setApproveBaseImVo(approveBaseImVo);
                // 发送消息
                attendanceNoticeHandler.send(approveImVo);
            });
        }
    }

    @Override
    public void submit(String id, SelfApprove entity, SelfApproveDto selfApproveDto) {
        //表单信息
        if (StringUtil.isEmpty(entity.getId())) {
            entity.setId(id);
            save(entity);
            // 保存对应的用户集合
//            selfApproveUserMapper.addList(selfApproveDto.getUserIds(),id);
            selfApproveUserMapper.addUserList(selfApproveDto.getUserSelfDtos(),id);

            // 发送消息
//            String tenantId = userProvider.get().getTenantId();
//            new Thread(()->{
//                // 睡眠1秒，确保事务提交完成
//                try {
//                    Thread.sleep(1000);
//                    secondedSendIm(entity,tenantId);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }).start();
        } else {
            entity.setId(id);
            updateById(entity);
            // 删除以前绑定的用户集合
            selfApproveUserMapper.deleteById(id);
            // 保存对应的用户集合
//            selfApproveUserMapper.addList(selfApproveDto.getUserIds(),id);
            selfApproveUserMapper.addUserList(selfApproveDto.getUserSelfDtos(),id);
        }
    }

    @Override
    public SelfApproveVo getAttendanceLeave(String id) {
        SelfApprove selfApprove = this.getById(id);
        SelfApproveVo jsonToBean = JsonUtil.getJsonToBean(selfApprove, SelfApproveVo.class);
        if (null != jsonToBean) {
            // 获取对应的用户集合
            List<UserSelfDto> userSelfDtos = selfApproveUserMapper.getListById(id);
            jsonToBean.setUserSelfDtos(userSelfDtos);
//            List<String> userIds = selfApproveUserMapper.getIdListById(id);
//            jsonToBean.setUserIds(userIds);
        }
        return jsonToBean;
    }

    @Override
    public void saveForOa(SelfApprove entity,List<String> userIds) {
        save(entity);
        selfApproveUserMapper.addUserListForOa(userIds,entity.getId());
    }
}
