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

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
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.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.zb.*;
import com.ruoyi.system.domain.zb.vo.DutyWorkConfigVO;
import com.ruoyi.system.domain.zb.vo.DutyWorkVO;
import com.ruoyi.system.mapper.publicservice.TOtherappAttachmentMapper;
import com.ruoyi.system.mapper.system.SysRoleMenuMapper;
import com.ruoyi.system.mapper.zb.ZbDutyWorkConfigMapper;
import com.ruoyi.system.mapper.zb.ZbDutyWorkRecordMapper;
import com.ruoyi.system.mapper.zb.ZbDutyWorkRuleMapper;
import com.ruoyi.system.service.md.NewMsgService;
import com.ruoyi.system.service.zb.DutyWorkService;
import org.springframework.beans.BeanUtils;
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.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * * Author: brenda
 * * 2025/1/21
 **/
@Service
public class DutyWorkServiceImpl implements DutyWorkService {

    @Autowired
    private ZbDutyWorkRuleMapper ruleMapper;
    @Autowired
    private ZbDutyWorkConfigMapper configMapper;
    @Autowired
    private TOtherappAttachmentMapper otherappAttachmentMapper;
    @Autowired
    private ZbDutyWorkRecordMapper recordMapper;
    @Autowired
    private SysRoleMenuMapper roleMenuMapper;
    @Value("${app.msg.pcUrl}")
    private String gridPcUrl;
    @Value("${app.msg.appUrl}")
    private String gridAppUrl;
    @Autowired
    private NewMsgService newMsgService;

    @Override
    @Transactional
    public void save(DutyWorkConfigVO request) {
        if(request.getDays() == null || request.getDays() == 0){
            throw new ServiceException("参数错误！");
        }
        if(CollectionUtils.isEmpty(request.getDutyWorkVOList())){
            throw new ServiceException("参数错误！");
        }
        ZbDutyWorkRule workRule = new ZbDutyWorkRule();
        workRule.setDays(request.getDays());
        workRule.setId(UUID.randomUUID().toString());
        workRule.setCreateTime(new Date());
        workRule.setFirstDay(request.getFirstDay());
        workRule.setLastDay(request.getLastDay());
        workRule.setAutoFlag(request.getAutoFlag());
        workRule.setCreateUser(request.getCreateUser());
        workRule.setCreateUserName(request.getCreateUserName());
        ruleMapper.insert(workRule);
        for(DutyWorkVO workVO : request.getDutyWorkVOList()){
            ZbDutyWorkConfig zbDutyWorkConfig = new ZbDutyWorkConfig();
            String id = java.util.UUID.randomUUID().toString();
            BeanUtils.copyProperties(workVO, zbDutyWorkConfig);
            if(workVO.getPublishFlag() == null){
                zbDutyWorkConfig.setPublishFlag(0);
            }
            zbDutyWorkConfig.setId(id);
            zbDutyWorkConfig.setCreateTime(new Date());
            zbDutyWorkConfig.setCreateUser(request.getCreateUser());
            zbDutyWorkConfig.setCreateUserName(request.getCreateUserName());
            configMapper.insert(zbDutyWorkConfig);
            if(!CollectionUtils.isEmpty(workVO.getFileList())){
                for(TOtherappAttachment e : workVO.getFileList()){
                    e.setAttachType(AttachEnums.AttachType.ON_DUTY.name());
                    e.setAttachId(null);
                    e.setValid(1);
                    e.setBusinessId(id);
                    otherappAttachmentMapper.insertSelective(e);
                }
            }
            //如果是当天的值班任务，立马发布掉
            if(zbDutyWorkConfig.getPublishFlag() == 0 && DateUtils.isToday(zbDutyWorkConfig.getPublishDate())){
                workVO.setId(id);
                workVO.setCreateUser(request.getCreateUser());
                workVO.setCreateUserName(request.getCreateUserName());
                saveDutyWorkRecord(workVO);
            }
        }
    }

    @Override
    @Transactional
    public void update(DutyWorkConfigVO request) {
        List<ZbDutyWorkConfig> configList = configMapper.selectByExample(new ZbDutyWorkConfigExample());
        TOtherappAttachmentExample otherappAttachmentExample = new TOtherappAttachmentExample();
        TOtherappAttachmentExample.Criteria criteria = otherappAttachmentExample.createCriteria();
        criteria.andBusinessIdIn(configList.stream().map(ZbDutyWorkConfig::getId).collect(Collectors.toList()));
        criteria.andAttachTypeEqualTo(AttachEnums.AttachType.ON_DUTY.name());
        otherappAttachmentMapper.deleteByExample(otherappAttachmentExample);
        configMapper.deleteByExample(new ZbDutyWorkConfigExample());
        ruleMapper.deleteByExample(new ZbDutyWorkRuleExample());
        save(request);
    }

    @Override
    public DutyWorkConfigVO configDetail() {
        List<ZbDutyWorkRule> ruleList = ruleMapper.selectByExample(new ZbDutyWorkRuleExample());
        if(ruleList.isEmpty()){
            return null;
        }
        DutyWorkConfigVO vo = BeanCopyUtil.toBean(ruleList.get(0), DutyWorkConfigVO.class);
        List<ZbDutyWorkConfig> configList = configMapper.selectByExampleWithBLOBs(new ZbDutyWorkConfigExample());
        if(CollectionUtils.isEmpty(configList)){
            return null;
        }
        List<DutyWorkVO> workVOList = new ArrayList<>();
        for(ZbDutyWorkConfig config : configList){
            DutyWorkVO workVO = BeanCopyUtil.toBean(config, DutyWorkVO.class);
            TOtherappAttachmentExample otherappAttachmentExample = new TOtherappAttachmentExample();
            TOtherappAttachmentExample.Criteria criteria = otherappAttachmentExample.createCriteria();
            criteria.andBusinessIdEqualTo(config.getId());
            criteria.andAttachTypeEqualTo(AttachEnums.AttachType.ON_DUTY.name());
            workVO.setFileList(otherappAttachmentMapper.selectByExample(otherappAttachmentExample));
            workVOList.add(workVO);
        }
        workVOList.sort(Comparator.comparing(DutyWorkVO::getPublishDate));
        vo.setDutyWorkVOList(workVOList);
        return vo;
    }

    @Override
    @Transactional
    public void saveDutyWorkRecord(DutyWorkVO workVO) {
        ZbDutyWorkRecord dutyWorkRecord = new ZbDutyWorkRecord();
        String id = UUID.randomUUID().toString();
        dutyWorkRecord.setId(id);
        dutyWorkRecord.setContent(workVO.getContent());
        dutyWorkRecord.setCreateTime(new Date());
        dutyWorkRecord.setTitle(workVO.getTitle());
        dutyWorkRecord.setPublishDate(workVO.getPublishDate());
        dutyWorkRecord.setCreateUser(workVO.getCreateUser());
        dutyWorkRecord.setCreateUserName(workVO.getCreateUserName());
        recordMapper.insert(dutyWorkRecord);
        if(!CollectionUtils.isEmpty(workVO.getFileList())){
            for(TOtherappAttachment e : workVO.getFileList()){
                e.setAttachId(null);
                e.setAttachType(AttachEnums.AttachType.ON_DUTY.name());
                e.setValid(1);
                e.setBusinessId(id);
                otherappAttachmentMapper.insertSelective(e);
            }
        }
        ZbDutyWorkConfig zbDutyWorkConfig = configMapper.selectByPrimaryKey(workVO.getId());
        zbDutyWorkConfig.setPublishFlag(1);
        configMapper.updateByPrimaryKey(zbDutyWorkConfig);
        List<String> dutyPersonList = roleMenuMapper.listDutyWorkPerson();
        if(CollectionUtils.isEmpty(dutyPersonList)){
            return;
        }
        List<NewMsgUser> toUserLists = new ArrayList<>();
        for(String user: dutyPersonList){
            NewMsgUser toMsgUser = new NewMsgUser();
            toMsgUser.setUserid(user);
            toUserLists.add(toMsgUser);
        }
        NewMsgSendRequest request = new NewMsgSendRequest();
        String typeName = "值班任务";
        String titleName = workVO.getTitle();
        String body = workVO.getContent();
        request.setSendData(buildSendDate(titleName, body, typeName, workVO.getCreateUserName(),id));
        NewMsgUser user = new NewMsgUser();
        user.setUserid(workVO.getCreateUser());
        request.setFrom(user);
        request.setTo(toUserLists);
        newMsgService.send(request);
    }

    private NewMsgSendData buildSendDate(String title, String body, String msgcategory, String sender, 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 = gridAppUrl+"/dutydetail?id="+id;
        String appUrl = gridAppUrl+"/duty/detail/"+id;
        map.put("redirect_pc", pcUrl);
        map.put("redirect_app", appUrl);
        data.setParams(map);
        return data;
    }

    @Override
    public PageInfo<ZbDutyWorkRecord> dutyRecordPage(String title) {
        ZbDutyWorkRecordExample example = new ZbDutyWorkRecordExample();
        ZbDutyWorkRecordExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(title)){
            criteria.andTitleLike("%"+ title + "%");
        }
        example.setOrderByClause("publish_date desc");
        List<ZbDutyWorkRecord> recordList = recordMapper.selectByExample(example);
        PageInfo<ZbDutyWorkRecord> pageInfo = new PageInfo<>(recordList);
        return pageInfo;
    }

    @Override
    public DutyWorkVO dutyWorkDetail(String id) {
        ZbDutyWorkRecord record = recordMapper.selectByPrimaryKey(id);
        DutyWorkVO workVO = BeanCopyUtil.toBean(record, DutyWorkVO.class);
        TOtherappAttachmentExample otherappAttachmentExample = new TOtherappAttachmentExample();
        TOtherappAttachmentExample.Criteria criteria = otherappAttachmentExample.createCriteria();
        criteria.andBusinessIdEqualTo(id);
        criteria.andAttachTypeEqualTo(AttachEnums.AttachType.ON_DUTY.name());
        workVO.setFileList(otherappAttachmentMapper.selectByExample(otherappAttachmentExample));
        return workVO;
    }

}
