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.StringUtils;
import com.ruoyi.common.utils.bean.BeanCopyUtil;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.common.zqt.ZQTPageUtil;
import com.ruoyi.system.domain.md.dto.JbReceiver;
import com.ruoyi.system.domain.md.dto.JbWorkBean;
import com.ruoyi.system.domain.publicservice.TOtherappAttachment;
import com.ruoyi.system.domain.publicservice.TOtherappAttachmentExample;
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.StampExamineSaveRequest;
import com.ruoyi.system.domain.stamp.vo.*;
import com.ruoyi.system.domain.system.enums.AttachEnums;
import com.ruoyi.system.domain.zb.vo.SpecialWorkVO;
import com.ruoyi.system.mapper.publicservice.TOtherappAttachmentMapper;
import com.ruoyi.system.mapper.stamp.*;
import com.ruoyi.system.service.md.JbTodoService;
import com.ruoyi.system.service.other.BsCommonService;
import com.ruoyi.system.service.stamp.CarDinnerExamineUserService;
import com.ruoyi.system.service.stamp.StampExamineService;
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 javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * * Author: brenda
 * * 2025/1/22
 **/
@Service
public class StampExamineServiceImpl implements StampExamineService {

    @Autowired
    private StampExamineMapper stampExamineMapper;
    @Autowired
    private TOtherappAttachmentMapper otherappAttachmentMapper;
    @Value("${app.msg.appUrl}")
    private String gridAppUrl;
    @Autowired
    private BsCommonService bsCommonService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private StampExamineExtMapper examineExtMapper;
    @Autowired
    private StampUserConfigMapper stampUserConfigMapper;
    @Autowired
    private CarDinnerExamineUserService carDinnerExamineUserService;
    @Autowired
    private CarDinnerExamineUserMapper carDinnerExamineUserMapper;

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

    private void saveOtherInfo(StampExamineSaveRequest request){
        if(!CollectionUtils.isEmpty(request.getFileList())){
            for(TOtherappAttachment e : request.getFileList()){
                e.setAttachType(AttachEnums.AttachType.STAMP_EXAMINE.name());
                e.setAttachId(null);
                e.setValid(1);
                e.setBusinessId(request.getId());
                otherappAttachmentMapper.insertSelective(e);
            }
        }
        ExamineSaveOtherBusInfo busInfo = new ExamineSaveOtherBusInfo();
        busInfo.setBusId(request.getId());
        busInfo.setTitle(request.getTitle());
        busInfo.setAppUrl(gridAppUrl+"/yzApply/detail?id="+request.getId());
        busInfo.setCreateBy(request.getCreateUser());
        busInfo.setContent(request.getContent());
        busInfo.setType("STAMP");
        carDinnerExamineUserService.saveExamineInfo(request.getExamineUserList(), busInfo);
    }

    @Override
    @Transactional
    public void apply(CarDinnerExamineRequest request) {
        StampExamine stampExamine = stampExamineMapper.selectByPrimaryKey(request.getBusId());
        ExamineSaveOtherBusInfo busInfo = new ExamineSaveOtherBusInfo();
        busInfo.setCreateBy(stampExamine.getCreateUser());
        busInfo.setTitle(stampExamine.getTitle());
        busInfo.setBusId(stampExamine.getId());
        busInfo.setContent(stampExamine.getContent());
        busInfo.setAppUrl(gridAppUrl+"/yzApply/detail?id="+stampExamine.getId());
        busInfo.setType("STAMP");
        request.setType("STAMP");
        request.setBusInfo(busInfo);
        boolean isFinished = carDinnerExamineUserService.apply(request);
        stampExamine.setUpdateTime(new Date());
        if(request.getStatus().equals(ExamineStatusEnum.BACK.getCode())){
            stampExamine.setStatus(ExamineStatusEnum.BACK.getCode());
        }else{
            if(isFinished){
                stampExamine.setStatus(ExamineStatusEnum.FINISHED.getCode());
            }
        }
        stampExamineMapper.updateByPrimaryKeySelective(stampExamine);
    }

    @Override
    public StampExamineDetail detail(String stampId, String userId) {
        StampExamine stampExamine = stampExamineMapper.selectByPrimaryKey(stampId);
        StampExamineDetail detail = new StampExamineDetail();
        BeanUtils.copyProperties(stampExamine, detail);
        if(StringUtils.isNotBlank(detail.getType())){
            detail.setTypeValue(bsCommonService.getName(detail.getType()));
        }
        TOtherappAttachmentExample attachmentExample = new TOtherappAttachmentExample();
        TOtherappAttachmentExample.Criteria attachCriteria = attachmentExample.createCriteria();
        attachCriteria.andBusinessIdEqualTo(stampId);
        attachCriteria.andAttachTypeEqualTo(AttachEnums.AttachType.STAMP_EXAMINE.name());
        detail.setFileList(otherappAttachmentMapper.selectByExample(attachmentExample));
        ExamineStatusEnum examineStatusEnum = ExamineStatusEnum.getByCode(detail.getStatus());
        detail.setStatusValue(examineStatusEnum == null?"":examineStatusEnum.getValue());
        //审批过程
        detail.setApplyList(carDinnerExamineUserService.hasExamined(stampId, "STAMP"));
        //全部步骤
        detail.setExamineUserList(carDinnerExamineUserService.allExamineList(stampId,"STAMP"));
        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(stampId, userId, "STAMP"));
        }
        return detail;
    }

    @Override
    public PageInfo<StampExaminePageItem> page(String title, String userId, String status) {
        StampUserConfigExample configExample = new StampUserConfigExample();
        StampUserConfigExample.Criteria configC = configExample.createCriteria();
        configC.andValidEqualTo((byte)1);
        List<StampUserConfig> userConfigs = stampUserConfigMapper.selectByExample(configExample);
        if(!CollectionUtils.isEmpty(userConfigs)){
            List<String> userIds = userConfigs.stream().map(StampUserConfig::getUserId).collect(Collectors.toList());
            //配置了可以查看全部就不传参
            userId = userIds.contains(userId)?"":userId;
        }
        List<StampExamine> list = examineExtMapper.listByParam(title, userId, status);
        List<StampExaminePageItem> items = new ArrayList<>();
        if(CollectionUtils.isEmpty(list)){
            return new PageInfo<>(items);
        }
        for(StampExamine examine : list){
            StampExaminePageItem pageItem = BeanCopyUtil.toBean(examine, StampExaminePageItem.class);
            ExamineStatusEnum statusEnum = ExamineStatusEnum.getByCode(examine.getStatus());
            pageItem.setStatusValue(statusEnum == null?"":statusEnum.getValue());
            pageItem.setTypeValue(bsCommonService.getName(pageItem.getType()));
            CarDinnerExamineUserExample example = new CarDinnerExamineUserExample();
            CarDinnerExamineUserExample.Criteria criteria = example.createCriteria();
            criteria.andTypeEqualTo("STAMP");
            criteria.andBusIdEqualTo(examine.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.setUserNames(String.join(",", userNames));
            }
            items.add(pageItem);
        }
        PageInfo<StampExaminePageItem> pageInfo = ZQTPageUtil.build(list, items);
        return pageInfo;
    }

    @Override
    @Transactional
    public void reSubmit(StampExamineSaveRequest request) {
        request.setStatus(ExamineStatusEnum.PROCESSING.getCode());
        stampExamineMapper.updateByPrimaryKeySelective(request);
        TOtherappAttachmentExample otherappAttachmentExample = new TOtherappAttachmentExample();
        TOtherappAttachmentExample.Criteria criteria = otherappAttachmentExample.createCriteria();
        criteria.andBusinessIdEqualTo(request.getId());
        criteria.andAttachTypeEqualTo(AttachEnums.AttachType.STAMP_EXAMINE.name());
        otherappAttachmentMapper.deleteByExample(otherappAttachmentExample);
        CarDinnerExamineUserExample userExample = new CarDinnerExamineUserExample();
        CarDinnerExamineUserExample.Criteria criteria1 = userExample.createCriteria();
        criteria1.andBusIdEqualTo(request.getId());
        criteria1.andTypeEqualTo("STAMP");
        carDinnerExamineUserMapper.deleteByExample(userExample);
        saveOtherInfo(request);
    }
}
