package com.ruoyi.system.service.stamp.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanCopyUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.md.dto.JbReceiver;
import com.ruoyi.system.domain.md.dto.JbWorkBean;
import com.ruoyi.system.domain.stamp.CarDinnerExamineUser;
import com.ruoyi.system.domain.stamp.CarDinnerExamineUserExample;
import com.ruoyi.system.domain.stamp.enums.ExamineStatusEnum;
import com.ruoyi.system.domain.stamp.request.CarDinnerExamineRequest;
import com.ruoyi.system.domain.stamp.vo.ExamineSaveOtherBusInfo;
import com.ruoyi.system.domain.stamp.vo.ExamineUserExt;
import com.ruoyi.system.domain.task.utils.WorkMSGUtils;
import com.ruoyi.system.mapper.stamp.CarDinnerExamineUserMapper;
import com.ruoyi.system.service.md.JbTodoService;
import com.ruoyi.system.service.stamp.CarDinnerExamineUserService;
import com.ruoyi.system.service.system.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * * Author: brenda
 * * 2025/2/8
 **/
@Service
public class CarDinnerExamineUserServiceImpl implements CarDinnerExamineUserService {

    @Autowired
    private CarDinnerExamineUserMapper carDinnerExamineUserMapper;
    @Resource
    private JbTodoService todoService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private WorkMSGUtils workMSGUtils;

    @Override
    @Transactional
    public boolean apply(CarDinnerExamineRequest request) {
        CarDinnerExamineUserExample example = new CarDinnerExamineUserExample();
        CarDinnerExamineUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(request.getUserId());
        criteria.andBusIdEqualTo(request.getBusId());
        criteria.andTypeEqualTo(request.getType());
        List<CarDinnerExamineUser> examineUsers = carDinnerExamineUserMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(examineUsers)){
            throw new ServiceException("该用户不需要审批！");
        }
        CarDinnerExamineUser user = examineUsers.get(0);
        user.setUpdateUser(request.getUserId());
        user.setUpdateTime(new Date());
        user.setOpinion(request.getOpinion());
        user.setStatus(request.getStatus());
        carDinnerExamineUserMapper.updateByPrimaryKeySelective(user);
        todoService.workUserStatus(1, user.getTodoId(), 1, request.getUserId());
        ExamineSaveOtherBusInfo busInfo = request.getBusInfo();
        if(request.getStatus().equals(ExamineStatusEnum.BACK.getCode())){
            //退回,其他正在审批的同一步骤的人待办删掉
            CarDinnerExamineUserExample example1 = new CarDinnerExamineUserExample();
            CarDinnerExamineUserExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andBusIdEqualTo(request.getBusId());
            criteria1.andStatusEqualTo(ExamineStatusEnum.PROCESSING.getCode());
            criteria1.andSortEqualTo(user.getSort());
            criteria1.andTodoIdIsNotNull();
            criteria1.andTypeEqualTo(request.getType());
            List<CarDinnerExamineUser> remainList = carDinnerExamineUserMapper.selectByExample(example1);
            if(!CollectionUtils.isEmpty(remainList)){
                for(CarDinnerExamineUser examineUser : remainList){
                    todoService.deleteTodo(examineUser.getTodoId(), Arrays.asList(examineUser.getUserId()));
                }
            }
        }else{
            //通过
            CarDinnerExamineUserExample userExample = new CarDinnerExamineUserExample();
            CarDinnerExamineUserExample.Criteria cookC = userExample.createCriteria();
            cookC.andBusIdEqualTo(request.getBusId());
            cookC.andTypeEqualTo(request.getType());
            cookC.andStatusNotEqualTo(ExamineStatusEnum.FINISHED.getCode());
            List<CarDinnerExamineUser> otherExamine = carDinnerExamineUserMapper.selectByExample(userExample);
            if(otherExamine.isEmpty()){
                //全部审批完
                return true;
            }else{
                CarDinnerExamineUserExample examineUserExample = new CarDinnerExamineUserExample();
                CarDinnerExamineUserExample.Criteria exampleCriteria = examineUserExample.createCriteria();
                exampleCriteria.andBusIdEqualTo(request.getBusId());
                //没有同一步骤的人，就去下一步骤
                exampleCriteria.andStatusNotEqualTo(ExamineStatusEnum.FINISHED.getCode());
                exampleCriteria.andSortEqualTo(user.getSort());
                exampleCriteria.andTypeEqualTo(request.getType());
                if(carDinnerExamineUserMapper.countByExample(examineUserExample) == 0){
                    otherExamine = otherExamine.stream().filter( e -> e.getSort() > user.getSort()).sorted(Comparator.comparing(CarDinnerExamineUser::getSort)).collect(Collectors.toList());
                    CarDinnerExamineUser nextExamine = otherExamine.get(0);
                    otherExamine = otherExamine.stream().filter( e -> nextExamine.getSort().equals(e.getSort())).collect(Collectors.toList());
                    for(CarDinnerExamineUser carDinnerExamineUser : otherExamine){
                        List<JbReceiver> receiverList = new ArrayList<>();
                        JbReceiver receiver = new JbReceiver();
                        receiver.setUid(carDinnerExamineUser.getUserId());
                        receiverList.add(receiver);
                        sendSms(carDinnerExamineUser.getUserId(), busInfo.getTitle(), busInfo.getType());
                        JbWorkBean daiBan = new JbWorkBean();
                        daiBan.setName(busInfo.getTitle());//待办标题
                        daiBan.setLevel(1);// 级别
                        daiBan.setCreatedby(busInfo.getCreateBy());//发送人用户ID
                        daiBan.setReceiver(receiverList);
                        daiBan.setContent(busInfo.getContent());//待办内容
                        daiBan.setUrl(busInfo.getAppUrl());
                        Integer todoId = todoService.save(daiBan);
                        carDinnerExamineUser.setTodoId(todoId);
                        carDinnerExamineUserMapper.updateByPrimaryKeySelective(carDinnerExamineUser);
                    }
                }
            }
        }
        return false;
    }

    @Override
    public void saveExamineInfo(List<CarDinnerExamineUser> examineUsers, ExamineSaveOtherBusInfo busInfo) {
        for(CarDinnerExamineUser examineUser : examineUsers){
            examineUser.setBusId(busInfo.getBusId());
            examineUser.setId(UUID.randomUUID().toString());
            examineUser.setCreateUser(busInfo.getCreateBy());
            examineUser.setCreateTime(new Date());
            examineUser.setStatus(ExamineStatusEnum.PROCESSING.getCode());
            examineUser.setType(busInfo.getType());
            List<JbReceiver> receiverList = new ArrayList<>();
            Integer todoId = null;
            //给第一步的人发待办和短信,可能是多个
            if(examineUser.getSort() == 1){
                JbReceiver receiver = new JbReceiver();
                receiver.setUid(examineUser.getUserId());
                receiverList.add(receiver);
                JbWorkBean daiBan = new JbWorkBean();
                daiBan.setName(busInfo.getTitle());//待办标题
                daiBan.setLevel(1);// 级别
                daiBan.setCreatedby(busInfo.getCreateBy());//发送人用户ID
                daiBan.setReceiver(receiverList);
                daiBan.setContent(busInfo.getContent());//待办内容"
                daiBan.setUrl(busInfo.getAppUrl());
                todoId = todoService.save(daiBan);
                sendSms(examineUser.getUserId(), busInfo.getTitle(), busInfo.getType());
            }
            examineUser.setTodoId(todoId);
            carDinnerExamineUserMapper.insertSelective(examineUser);
        }
    }

    private void sendSms(String examineUserId, String title, String type){
        SysUser examineUser = userService.selectUserById(examineUserId);
        if(examineUser != null && StringUtils.isNotBlank(examineUser.getPhonenumber())){
            String content = "";
            if(type.equals("CAR")){
                content = "【万事通】"+examineUser.getNickName()+"您好,您所在的万石镇有一条用车申请："+title+"，待审批，如用车申请指派错误或其他问题，请联系万事通指挥中心";
            }else if(type.equals("DINNER")){
                content = "【万事通】"+examineUser.getNickName()+"您好,您所在的万石镇有一条用餐申请："+title+"，待审批，如用餐申请指派错误或其他问题，请联系万事通指挥中心";
            }else{
                content = "【万事通】"+examineUser.getNickName()+"您好,您所在的万石镇有一条用章申请："+title+"，待审批，如用章申请指派错误或其他问题，请联系万事通指挥中心";
            }
            //短信
            workMSGUtils.sendDXSMSCurrency(examineUser, content);
        }
    }

    @Override
    public List<ExamineUserExt> hasExamined(String busId, String type) {
        CarDinnerExamineUserExample example = new CarDinnerExamineUserExample();
        CarDinnerExamineUserExample.Criteria criteria = example.createCriteria();
        criteria.andBusIdEqualTo(busId);
        criteria.andTypeEqualTo(type);
        criteria.andStatusNotEqualTo(ExamineStatusEnum.PROCESSING.getCode());
        example.setOrderByClause("update_time asc");
        List<CarDinnerExamineUser> applyExamineList = carDinnerExamineUserMapper.selectByExample(example);
        List<ExamineUserExt> extList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(applyExamineList)){
            extList = BeanCopyUtil.bathToBean(applyExamineList, ExamineUserExt.class);
            for(ExamineUserExt examineUserExt : extList){
                SysUser sysUser = userService.selectUserById(examineUserExt.getUserId());
                examineUserExt.setNickName(sysUser.getNickName());
                examineUserExt.setAvatar(sysUser.getAvatar());
            }
        }
        return extList;
    }

    @Override
    public List<ExamineUserExt> allExamineList(String busId, String type) {
        CarDinnerExamineUserExample example1 = new CarDinnerExamineUserExample();
        CarDinnerExamineUserExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andBusIdEqualTo(busId);
        criteria1.andTypeEqualTo(type);
        example1.setOrderByClause("sort asc");
        List<CarDinnerExamineUser> examineUserList = carDinnerExamineUserMapper.selectByExample(example1);
        List<ExamineUserExt> extList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(examineUserList)){
            extList = BeanCopyUtil.bathToBean(examineUserList, ExamineUserExt.class);
            for(ExamineUserExt examineUserExt : extList){
                SysUser sysUser = userService.selectUserById(examineUserExt.getUserId());
                examineUserExt.setNickName(sysUser.getNickName());
                examineUserExt.setAvatar(sysUser.getAvatar());
            }
        }
        return extList;
    }

    @Override
    public boolean canApply(String busId, String userId, String type) {
        CarDinnerExamineUserExample userExample = new CarDinnerExamineUserExample();
        CarDinnerExamineUserExample.Criteria userExampleCriteria = userExample.createCriteria();
        userExampleCriteria.andBusIdEqualTo(busId);
        userExampleCriteria.andTypeEqualTo(type);
        userExampleCriteria.andUserIdEqualTo(userId);
        userExampleCriteria.andStatusEqualTo(ExamineStatusEnum.PROCESSING.getCode());
        userExampleCriteria.andTodoIdIsNotNull();
        return carDinnerExamineUserMapper.countByExample(userExample) > 0;
    }
}
