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.CarDinnerExamineUser;
import com.ruoyi.system.domain.stamp.CarDinnerExamineUserExample;
import com.ruoyi.system.domain.stamp.DinnerExamine;
import com.ruoyi.system.domain.stamp.enums.ExamineStatusEnum;
import com.ruoyi.system.domain.stamp.request.CarDinnerExamineRequest;
import com.ruoyi.system.domain.stamp.request.DinnerExamineSaveRequest;
import com.ruoyi.system.domain.stamp.vo.*;
import com.ruoyi.system.mapper.stamp.CarDinnerExamineUserMapper;
import com.ruoyi.system.mapper.stamp.CarExamineExtMapper;
import com.ruoyi.system.mapper.stamp.DinnerExamineMapper;
import com.ruoyi.system.service.stamp.CarDinnerExamineUserService;
import com.ruoyi.system.service.stamp.DinnerExamineService;
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/10
 **/
@Service
public class DinnerExamineServiceImpl implements DinnerExamineService {

    @Autowired
    DinnerExamineMapper dinnerExamineMapper;
    @Autowired
    private CarDinnerExamineUserService carDinnerExamineUserService;
    @Autowired
    private CarExamineExtMapper carExamineExtMapper;
    @Autowired
    private CarDinnerExamineUserMapper carDinnerExamineUserMapper;
    @Autowired
    private ISysUserService userService;
    @Value("${app.msg.appUrl}")
    private String gridAppUrl;

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

    private void saveOtherInfo(DinnerExamineSaveRequest request){
        ExamineSaveOtherBusInfo busInfo = new ExamineSaveOtherBusInfo();
        busInfo.setBusId(request.getId());
        busInfo.setTitle(request.getTitle());
        busInfo.setAppUrl(gridAppUrl+"/eatApply/detail?id="+request.getId());
        busInfo.setCreateBy(request.getCreateUser());
        String content = "用餐人数："+ request.getPersonCount()+",\n用餐时间："+request.getDinnerTime()+",\n备注："+request.getRemark();
        busInfo.setContent(content);
        busInfo.setType("DINNER");
        carDinnerExamineUserService.saveExamineInfo(request.getExamineUserList(), busInfo);
    }

    @Override
    @Transactional
    public void apply(CarDinnerExamineRequest request) {
        DinnerExamine dinnerExamine = dinnerExamineMapper.selectByPrimaryKey(request.getBusId());
        ExamineSaveOtherBusInfo busInfo = new ExamineSaveOtherBusInfo();
        busInfo.setCreateBy(dinnerExamine.getCreateUser());
        busInfo.setTitle(dinnerExamine.getTitle());
        busInfo.setBusId(dinnerExamine.getId());
        String content = "用餐人数："+ dinnerExamine.getPersonCount()+",\n用餐时间："+dinnerExamine.getDinnerTime()+",\n备注："+dinnerExamine.getRemark();
        busInfo.setContent(content);
        busInfo.setAppUrl(gridAppUrl+"/eatApply/detail?id="+dinnerExamine.getId());
        busInfo.setType("DINNER");
        request.setType("DINNER");
        request.setBusInfo(busInfo);
        boolean isFinished = carDinnerExamineUserService.apply(request);
        dinnerExamine.setUpdateTime(new Date());
        if(request.getStatus().equals(ExamineStatusEnum.BACK.getCode())){
            dinnerExamine.setStatus(ExamineStatusEnum.BACK.getCode());
        }else{
            if(isFinished){
                dinnerExamine.setStatus(ExamineStatusEnum.FINISHED.getCode());
            }
        }
        dinnerExamineMapper.updateByPrimaryKeySelective(dinnerExamine);
    }

    @Override
    public DinnerExamineDetail detail(String id, String userId) {
        DinnerExamine dinnerExamine = dinnerExamineMapper.selectByPrimaryKey(id);
        DinnerExamineDetail detail = BeanCopyUtil.toBean(dinnerExamine, DinnerExamineDetail.class);
        ExamineStatusEnum statusEnum = ExamineStatusEnum.getByCode(detail.getStatus());
        detail.setStatusValue(statusEnum == null?"":statusEnum.getValue());
        //已审批的
        detail.setApplyList(carDinnerExamineUserService.hasExamined(id, "DINNER"));
        //全部步骤
        detail.setExamineUserList(carDinnerExamineUserService.allExamineList(id,"DINNER"));
        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, "DINNER"));
        }
        return detail;
    }

    @Override
    public PageInfo<DinnerExaminePageItem> page(String title, String status, String userId) {
        List<DinnerExamine> dinnerExamineList = carExamineExtMapper.listDinnerExamineByParam(title, status, userId);
        List<DinnerExaminePageItem> items = new ArrayList<>();
        if(CollectionUtils.isEmpty(dinnerExamineList)){
            return new PageInfo<>(items);
        }
        for(DinnerExamine dinnerExamine : dinnerExamineList){
            DinnerExaminePageItem pageItem = BeanCopyUtil.toBean(dinnerExamine, DinnerExaminePageItem.class);
            ExamineStatusEnum examineStatusEnum = ExamineStatusEnum.getByCode(dinnerExamine.getStatus());
            pageItem.setStatusValue(examineStatusEnum == null?"":examineStatusEnum.getValue());
            CarDinnerExamineUserExample example = new CarDinnerExamineUserExample();
            CarDinnerExamineUserExample.Criteria criteria = example.createCriteria();
            criteria.andTypeEqualTo("DINNER");
            criteria.andBusIdEqualTo(dinnerExamine.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<DinnerExaminePageItem> pageInfo = ZQTPageUtil.build(dinnerExamineList, items);
        return pageInfo;
    }

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