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

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanCopyUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.common.zqt.ZQTPageUtil;
import com.ruoyi.system.domain.stamp.*;
import com.ruoyi.system.domain.stamp.enums.ExamineStatusEnum;
import com.ruoyi.system.domain.stamp.request.CarDinnerExamineRequest;
import com.ruoyi.system.domain.stamp.request.CarExamineSaveRequest;
import com.ruoyi.system.domain.stamp.vo.CarExamineDetail;
import com.ruoyi.system.domain.stamp.vo.CarExaminePageItem;
import com.ruoyi.system.domain.stamp.vo.ExamineSaveOtherBusInfo;
import com.ruoyi.system.mapper.stamp.CarDinnerExamineUserMapper;
import com.ruoyi.system.mapper.stamp.CarExamineExtMapper;
import com.ruoyi.system.mapper.stamp.CarExamineMapper;
import com.ruoyi.system.service.stamp.CarDinnerExamineUserService;
import com.ruoyi.system.service.stamp.CarExamineService;
import com.ruoyi.system.service.system.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * * Author: brenda
 * * 2025/2/8
 **/
@Service
public class CarExamineServiceImpl implements CarExamineService {
    @Autowired
    private CarExamineMapper carExamineMapper;
    @Autowired
    private CarDinnerExamineUserMapper carDinnerExamineUserMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private CarExamineExtMapper carExamineExtMapper;
    @Autowired
    private CarDinnerExamineUserService carDinnerExamineUserService;
    @Value("${app.msg.appUrl}")
    private String gridAppUrl;

    @Override
    @Transactional
    public void save(CarExamineSaveRequest request) {
        if(CollectionUtils.isEmpty(request.getExamineUserList())){
            throw new ServiceException("审批人不能为空！");
        }
        String id = UUID.randomUUID().toString();
        request.setId(id);
        request.setStatus(ExamineStatusEnum.PROCESSING.getCode());
        carExamineMapper.insertSelective(request);
        saveOtherInfo(request);
    }

    private void saveOtherInfo(CarExamineSaveRequest request){
        ExamineSaveOtherBusInfo busInfo = new ExamineSaveOtherBusInfo();
        busInfo.setBusId(request.getId());
        busInfo.setTitle(request.getTitle());
        busInfo.setAppUrl(gridAppUrl+"/carApply/detail?id="+request.getId());
        busInfo.setCreateBy(request.getCreateUser());
        String content = "用车人数："+ request.getPersonCount()+",\n往返地点："+request.getPlace()+",\n备注："+request.getRemark();
        busInfo.setContent(content);
        busInfo.setType("CAR");
        carDinnerExamineUserService.saveExamineInfo(request.getExamineUserList(), busInfo);
    }

    @Override
    @Transactional
    public void apply(CarDinnerExamineRequest request) {
        CarExamine carExamine = carExamineMapper.selectByPrimaryKey(request.getBusId());
        ExamineSaveOtherBusInfo busInfo = new ExamineSaveOtherBusInfo();
        busInfo.setBusId(carExamine.getId());
        busInfo.setTitle(carExamine.getTitle());
        busInfo.setCreateBy(carExamine.getCreateUser());
        busInfo.setAppUrl(gridAppUrl+"/carApply/detail?id="+carExamine.getId());
        String content = "用车人数："+ carExamine.getPersonCount()+",\n往返地点："+carExamine.getPlace()+",\n备注："+carExamine.getRemark();
        busInfo.setContent(content);
        busInfo.setType("CAR");
        request.setType("CAR");
        request.setBusInfo(busInfo);
        boolean isFinished = carDinnerExamineUserService.apply(request);
        carExamine.setUpdateTime(new Date());
        if(request.getStatus().equals(ExamineStatusEnum.BACK.getCode())){
            carExamine.setStatus(ExamineStatusEnum.BACK.getCode());
        }else{
            if(isFinished){
                carExamine.setStatus(ExamineStatusEnum.FINISHED.getCode());
            }
        }
        carExamineMapper.updateByPrimaryKeySelective(carExamine);
    }

    @Override
    public CarExamineDetail detail(String id, String userId) {
        CarExamine carExamine = carExamineMapper.selectByPrimaryKey(id);
        CarExamineDetail detail = BeanCopyUtil.toBean(carExamine, CarExamineDetail.class);
        ExamineStatusEnum statusEnum = ExamineStatusEnum.getByCode(detail.getStatus());
        detail.setStatusValue(statusEnum == null?"":statusEnum.getValue());
        //已审批的
        detail.setApplyList(carDinnerExamineUserService.hasExamined(id, "CAR"));
        //全部步骤
        detail.setExamineUserList(carDinnerExamineUserService.allExamineList(id,"CAR"));
        if(ExamineStatusEnum.FINISHED.getCode().equals(detail.getStatus())){
            return detail;
        }
        if(ExamineStatusEnum.BACK.getCode().equals(detail.getStatus())){
            if(userId.equals(detail.getCreateUser())){
                detail.setCanResubmit(true);
            }
        }else{
            detail.setCanApply(carDinnerExamineUserService.canApply(id, userId, "CAR"));
        }
        return detail;
    }

    @Override
    public PageInfo<CarExaminePageItem> page(String title, String status, String userId) {
        List<CarExamine> carExamineList = carExamineExtMapper.listCarExamineByParam(title, status, userId);
        List<CarExaminePageItem> items = new ArrayList<>();
        if(CollectionUtils.isEmpty(carExamineList)){
            return new PageInfo<>(items);
        }
        for(CarExamine carExamine : carExamineList){
            CarExaminePageItem pageItem = BeanCopyUtil.toBean(carExamine, CarExaminePageItem.class);
            ExamineStatusEnum examineStatusEnum = ExamineStatusEnum.getByCode(carExamine.getStatus());
            pageItem.setStatusValue(examineStatusEnum == null?"":examineStatusEnum.getValue());
            CarDinnerExamineUserExample example = new CarDinnerExamineUserExample();
            CarDinnerExamineUserExample.Criteria criteria = example.createCriteria();
            criteria.andTypeEqualTo("CAR");
            criteria.andBusIdEqualTo(carExamine.getId());
            example.setOrderByClause("sort asc");
            List<CarDinnerExamineUser> examineUserList = carDinnerExamineUserMapper.selectByExample(example);
            if(!CollectionUtils.isEmpty(examineUserList)){
                List<String> userNames = new ArrayList<>();
                for(CarDinnerExamineUser examineUser : examineUserList){
                    SysUser sysUser = userService.selectUserById(examineUser.getUserId());
                    userNames.add(sysUser.getNickName());
                }
                pageItem.setExamineUserNames(String.join(",", userNames));
            }
            items.add(pageItem);
        }
        PageInfo<CarExaminePageItem> pageInfo = ZQTPageUtil.build(carExamineList, items);
        return pageInfo;
    }

    @Override
    public void reSubmit(CarExamineSaveRequest request) {
        request.setStatus(ExamineStatusEnum.PROCESSING.getCode());
        carExamineMapper.updateByPrimaryKeySelective(request);
        CarDinnerExamineUserExample userExample = new CarDinnerExamineUserExample();
        CarDinnerExamineUserExample.Criteria criteria = userExample.createCriteria();
        criteria.andBusIdEqualTo(request.getId());
        criteria.andTypeEqualTo("CAR");
        carDinnerExamineUserMapper.deleteByExample(userExample);
        saveOtherInfo(request);
    }
}
