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

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
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.md.request.NewMsgSendData;
import com.ruoyi.system.domain.md.request.NewMsgSendRequest;
import com.ruoyi.system.domain.md.request.NewMsgUser;
import com.ruoyi.system.domain.publicservice.TOtherappAttachment;
import com.ruoyi.system.domain.publicservice.TOtherappAttachmentExample;
import com.ruoyi.system.domain.system.enums.AttachEnums;
import com.ruoyi.system.domain.task.utils.WorkMSGUtils;
import com.ruoyi.system.domain.zb.ZbSpecialWork;
import com.ruoyi.system.domain.zb.ZbSpecialWorkExample;
import com.ruoyi.system.domain.zb.ZbWorkRange;
import com.ruoyi.system.domain.zb.ZbWorkRangeExample;
import com.ruoyi.system.domain.zb.enums.ZbSpecialWorkEnum;
import com.ruoyi.system.domain.zb.request.SpecialWorkSaveRequest;
import com.ruoyi.system.domain.zb.vo.SpecialWorkVO;
import com.ruoyi.system.mapper.publicservice.TOtherappAttachmentMapper;
import com.ruoyi.system.mapper.zb.WeekReportExtMapper;
import com.ruoyi.system.mapper.zb.ZbSpecialWorkMapper;
import com.ruoyi.system.mapper.zb.ZbWorkRangeMapper;
import com.ruoyi.system.service.md.NewMsgService;
import com.ruoyi.system.service.publicservice.TOtherappAttachmentService;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.system.service.zb.SpecialWorkService;
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.*;
import java.util.stream.Collectors;

/**
 * * Author: brenda
 * * 2025/1/7
 **/
@Service
public class SpecialWorkServiceImpl implements SpecialWorkService {

    @Autowired
    private ZbSpecialWorkMapper specialWorkMapper;
    @Autowired
    private ZbWorkRangeMapper workRangeMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private TOtherappAttachmentService otherappAttachmentService;
    @Autowired
    private TOtherappAttachmentMapper otherappAttachmentMapper;
    @Autowired
    private NewMsgService newMsgService;
    @Autowired
    private WorkMSGUtils workMSGUtils;
    @Value("${app.msg.pcUrl}")
    private String gridPcUrl;
    @Value("${app.msg.appUrl}")
    private String gridAppUrl;
    @Autowired
    private WeekReportExtMapper extMapper;

    @Override
    @Transactional
    public void save(SpecialWorkSaveRequest request) {
        String id = UUID.randomUUID().toString();
        request.setId(id);
        request.setCreateTime(new Date());
        specialWorkMapper.insert(request);
        if(!CollectionUtils.isEmpty(request.getUserIdList())){
            saveUserInfo(request.getUserIdList(), id, request);
        }
        if(!CollectionUtils.isEmpty(request.getFileList())){
            saveFile(request.getFileList(), request.getType(), id);
        }
    }

    private void saveUserInfo(List<String> userIds, String workId, SpecialWorkSaveRequest saveRequest){
        List<SysUser> sysUserList = getUserList(userIds);
        if(!CollectionUtils.isEmpty(sysUserList)){
            List<NewMsgUser> toUserLists = new ArrayList<>();
            for(SysUser sysUser : sysUserList){
                ZbWorkRange workRange = new ZbWorkRange();
                workRange.setId(java.util.UUID.randomUUID().toString());
                workRange.setWorkId(workId);
                workRange.setUserId(sysUser.getUserId());
                workRange.setUserName(sysUser.getNickName());
                workRange.setType(saveRequest.getType());
                NewMsgUser toMsgUser = new NewMsgUser();
                toMsgUser.setUserid(sysUser.getUserId());
                toUserLists.add(toMsgUser);
                workRangeMapper.insert(workRange);
                //发短信
                if(saveRequest.getSmsFlag() != null && saveRequest.getSmsFlag() == 1){
                    if (saveRequest.getSmsFlag() != null && saveRequest.getSmsFlag() == 1) {
                        String content = "【万事通】"+"您有一条新的" + (ZbSpecialWorkEnum.SPECIAL_WORK.getCode().equals(saveRequest.getType())?"专项工作":"值班任务")+"待完成";
                        workMSGUtils.sendDXSMSCurrency(sysUser, content);
                    }
                }
            }
            //消息
            NewMsgSendRequest request = new NewMsgSendRequest();
            String typeName = ZbSpecialWorkEnum.SPECIAL_WORK.getCode().equals(saveRequest.getType())?"专项工作":"值班任务";
            String titleName = saveRequest.getTitle();
            String body = saveRequest.getContent();
            request.setSendData(buildSendDate(titleName, body, typeName, saveRequest.getCreateUserName(), saveRequest.getType(),workId ));
            NewMsgUser user = new NewMsgUser();
            user.setUserid(saveRequest.getCreateUser());
            request.setFrom(user);
            request.setTo(toUserLists);
            newMsgService.send(request);
        }
    }

    private NewMsgSendData buildSendDate(String title, String body, String msgcategory, String sender, String type, String id) {
        NewMsgSendData data = new NewMsgSendData();
        data.setTitle(title);
        data.setBody(body);
        data.setMsgtype((byte) 0);
        data.setNeedpush((byte) 0);
        JSONObject map = new JSONObject();
        map.put("needreply", "0");
        map.put("hasatt", "0");
        map.put("sender", sender);
        map.put("msgcategory", msgcategory);
        map.put("needsms", "0");
        String pcUrl = ZbSpecialWorkEnum.SPECIAL_WORK.getCode().equals(type)?gridAppUrl +"/weeklydetail?id="+id:gridAppUrl+"/dutydetail?id="+id;
        String appUrl = ZbSpecialWorkEnum.SPECIAL_WORK.getCode().equals(type)?gridAppUrl +"/specificWork/detail/"+id:gridAppUrl+"/duty/detail/"+id;
        map.put("redirect_pc", pcUrl);
        map.put("redirect_app", appUrl);
        data.setParams(map);
        return data;
    }

    private void saveFile(List<TOtherappAttachment> attachments, String type, String id){
        String attachType = AttachEnums.AttachType.SPECIAL_WORK.name();
        if(ZbSpecialWorkEnum.DUTY.getCode().equals(type)){
            attachType = AttachEnums.AttachType.ON_DUTY.name();
        }
        for(TOtherappAttachment e : attachments){
            e.setAttachType(attachType);
            e.setValid(1);
            e.setBusinessId(id);
            otherappAttachmentMapper.insertSelective(e);
        }
    }

    private List<SysUser> getUserList(List<String> userIds){
        SysUser sysUser = new SysUser();
        sysUser.setUserIds(userIds);
        return userService.selectUserList(sysUser);
    }

    @Override
    @Transactional
    public void delete(String id) {
        ZbSpecialWork specialWork = specialWorkMapper.selectByPrimaryKey(id);
        specialWork.setValid((byte) 0);
        specialWorkMapper.updateByPrimaryKeySelective(specialWork);
        ZbWorkRangeExample workRangeExample = new ZbWorkRangeExample();
        ZbWorkRangeExample.Criteria criteria = workRangeExample.createCriteria();
        criteria.andWorkIdEqualTo(id);
        workRangeMapper.deleteByExample(workRangeExample);
    }

    @Override
    @Transactional
    public void update(SpecialWorkSaveRequest request) {
        specialWorkMapper.updateByPrimaryKeySelective(request);
        ZbWorkRangeExample workRangeExample = new ZbWorkRangeExample();
        ZbWorkRangeExample.Criteria criteria = workRangeExample.createCriteria();
        criteria.andWorkIdEqualTo(request.getId());
        workRangeMapper.deleteByExample(workRangeExample);
        if(!CollectionUtils.isEmpty(request.getUserIdList())){
            saveUserInfo(request.getUserIdList(), request.getId(),request);
        }
        String attachType = AttachEnums.AttachType.SPECIAL_WORK.name();
        if(ZbSpecialWorkEnum.DUTY.getCode().equals(request.getType())){
            attachType = AttachEnums.AttachType.ON_DUTY.name();
        }
        otherappAttachmentService.deleteFiles(request.getId(), attachType);
        if(!CollectionUtils.isEmpty(request.getFileList())){
            saveFile(request.getFileList(), request.getType(), request.getId());
        }
    }

    @Override
    public SpecialWorkVO detail(String id) {
        ZbSpecialWork specialWork = specialWorkMapper.selectByPrimaryKey(id);
        return convertToVO(specialWork);
    }

    private SpecialWorkVO convertToVO(ZbSpecialWork work){
        SpecialWorkVO specialWorkVO = BeanCopyUtil.toBean(work, SpecialWorkVO.class);
        ZbWorkRangeExample workRangeExample = new ZbWorkRangeExample();
        ZbWorkRangeExample.Criteria criteria = workRangeExample.createCriteria();
        criteria.andWorkIdEqualTo(work.getId());
        List<ZbWorkRange> workRangeList = workRangeMapper.selectByExample(workRangeExample);
        specialWorkVO.setWorkRangeList(workRangeList);
        specialWorkVO.setPublishUserNameStr(CollectionUtils.isEmpty(workRangeList)?"":workRangeList.stream().map(ZbWorkRange::getUserName).collect(Collectors.joining(",")));
        TOtherappAttachmentExample otherappAttachmentExample = new TOtherappAttachmentExample();
        TOtherappAttachmentExample.Criteria criteria1 = otherappAttachmentExample.createCriteria();
        criteria1.andBusinessIdEqualTo(work.getId());
        String attachType = AttachEnums.AttachType.SPECIAL_WORK.name();
        if(ZbSpecialWorkEnum.DUTY.getCode().equals(work.getType())){
            attachType = AttachEnums.AttachType.ON_DUTY.name();
        }
        criteria1.andAttachTypeEqualTo(attachType);
        specialWorkVO.setFileList(otherappAttachmentMapper.selectByExample(otherappAttachmentExample));
        return specialWorkVO;
    }

    @Override
    public PageInfo<SpecialWorkVO> page(String title, String username, String type, String userId) {
        List<ZbSpecialWork> workList = extMapper.specialList(title, username, type, userId);
        List<SpecialWorkVO> workVOS = new ArrayList<>();
        if(!CollectionUtils.isEmpty(workList)){
            for(ZbSpecialWork work : workList){
                SpecialWorkVO vo = convertToVO(work);
                workVOS.add(vo);
            }
        }
        PageInfo<SpecialWorkVO> pageInfo = ZQTPageUtil.build(workList, workVOS);
        return pageInfo;
    }
}
