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.AttendanceBusinessTripApprove;
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.AttendanceBusinessTripApproveDto;
import jnpf.model.workflow.dto.AttendanceBusinessTripApproveOaDto;
import jnpf.model.workflow.vo.AttendanceBusinessTripApproveVo;
import jnpf.permission.model.user.PartUserInfoVo;
import jnpf.util.*;
import jnpf.workflow.mapper.BusinessTripApproveMapper;
import jnpf.workflow.service.BusinessTripApproveService;
import jnpf.workflow.service.FlowTaskService;
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:33
 * @Version 1.0 （版本号）
 */
@Service
@Slf4j
public class BusinessTripApproveServiceImpl extends SuperServiceImpl<BusinessTripApproveMapper, AttendanceBusinessTripApprove> implements BusinessTripApproveService {


    @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, AttendanceBusinessTripApprove entity, AttendanceBusinessTripApproveDto dto) {
        //表单信息
        if (StringUtil.isEmpty(entity.getId())) {
            entity.setId(id);
            save(entity);
            String tenantId = userProvider.get().getTenantId();
            new Thread(()->{
                // 睡眠1秒，确保事务提交完成
                try {
                    Thread.sleep(1000);
                    businessSendIm(entity,tenantId);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();

        } else {
            entity.setId(id);
            updateById(entity);
        }
    }

    private void businessSendIm(AttendanceBusinessTripApprove entity,String tenantId) {
        // 张三的【出差】审批
        // 出发地：地点名称地点名称地点名称地点名称
        // 目的地：地点名称地点名称地点名称地点名称
        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);
            StringBuilder stringBuffer = new StringBuilder();
            if (!Objects.isNull(partUserInfoVo)) {
                stringBuffer.append(partUserInfoVo.getRealName());
            }
            ApproveBaseImVo approveBaseImVo = new ApproveBaseImVo();
            approveBaseImVo.setType(ApprovalSettingTypeEnum.BUSINESS_TRIP.getCode());
            approveBaseImVo.setDestination(entity.getDestination());
            approveBaseImVo.setDeparture(entity.getDeparture());
            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;
                approveImVo.setUserIds(CollUtil.newArrayList(v.getUserId()));
                approveBaseImVo.setUrl(url);
                approveImVo.setApproveBaseImVo(approveBaseImVo);
                attendanceNoticeHandler.send(approveImVo);
            });
        }
    }

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

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

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

    @Override
    public void saveForOa(AttendanceBusinessTripApproveOaDto approveOaDto) {
        AttendanceBusinessTripApprove entity = JsonUtil.getJsonToBean(approveOaDto, AttendanceBusinessTripApprove.class);
        // 计算两个时间戳之间的日期差

        log.error("FoeOa开始存数据库出差了参数................: {}", entity);
        save(entity);
    }

    @Override
    public void submitForOa(String id, AttendanceBusinessTripApproveOaDto approveOaDto) {
        AttendanceBusinessTripApprove entity = JsonUtil.getJsonToBean(approveOaDto, AttendanceBusinessTripApprove.class);
        log.error("FoeOa开始x修改数据库出差了参数................: {}", entity);
        entity.setId(id);
        updateById(entity);
    }


}
