package com.rongwei.bscommon.sys.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwei.bscommon.sys.dao.SrmIssuesListDao;
import com.rongwei.bscommon.sys.service.SrmIssuesListService;
import com.rongwei.bsentity.domin.SrmIssuesListDo;
import com.rongwei.commonservice.service.SysConfigService;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.rwcommonentity.commonservers.domain.SysFileItemDo;
import com.rongwei.rwcommonentity.commonservers.vo.SysNotifyAnnounceVo;
import com.rongwei.safecommon.utils.CXCommonUtils;
import dto.SysNoticeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 问题列表 服务实现类
 * </p>
 *
 * @author fpy
 * @since 2023-03-20
 */
@Service
public class SrmIssuesListServiceImpl extends ServiceImpl<SrmIssuesListDao, SrmIssuesListDo> implements SrmIssuesListService {

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private SrmIssuesListDao srmIssuesListDao;

    @Override
    public void saveFishBoneImg(SrmIssuesListDo srmIssuesListDo) throws IOException {
        if(srmIssuesListDo.getCauseanalysisimg() != null){
            String imgUrl = this.base64ImgSave(srmIssuesListDo.getCauseanalysisimg());
            srmIssuesListDo.setCauseanalysisimg(imgUrl.split("@_@")[0]);
            srmIssuesListDo.setCauseanalysisimgurl(imgUrl.split("@_@")[1]);
        }
        if(srmIssuesListDo.getUndetectedanalysisimg() != null){
            String imgUrl = this.base64ImgSave(srmIssuesListDo.getUndetectedanalysisimg());
            srmIssuesListDo.setUndetectedanalysisimg(imgUrl.split("@_@")[0]);
            srmIssuesListDo.setUndetectedanalysisimgurl(imgUrl.split("@_@")[1]);
        }
        this.updateById(srmIssuesListDo);
    }

    private String base64ImgSave(String imgContent) throws IOException {
        // 替换到头部标识信息
        imgContent = imgContent.replace("data:image/png;base64,","");
        // 获取存储文件路径
        String fileRootPath = sysConfigService.getContentByConfigCode("fileRootPath");
        String fileName = SecurityUtil.getUUID() + ".png";
        String imgPath = fileRootPath + File.separator + "mindImg" + File.separator + fileName;
        // 写入文件内容
        File file = new File(imgPath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        byte[] buffer = new BASE64Decoder().decodeBuffer(imgContent);
        FileOutputStream out = new FileOutputStream(imgPath);
        out.write(buffer);
        out.close();

        //成功存储图片后，将文件存入系统文件中（sys_file_item），组装返回图片字段
        SysUserVo currentUser = CXCommonUtils.getCurrentUser();
        SysFileItemDo sysFileItemDo = new SysFileItemDo();
        sysFileItemDo.setId(SecurityUtil.getUUID());
        sysFileItemDo.setFilename(fileName);
        //文件大小
        sysFileItemDo.setFilesize(file.length());
        sysFileItemDo.setFiletype("png");
        sysFileItemDo.setStoragetype("1");
        sysFileItemDo.setFilefolderid("83968772af5042f4b09168e1ee74eac8");
        sysFileItemDo.setRelationid("83968772af5042f4b09168e1ee74eac8");
        sysFileItemDo.setFullpath(imgPath);
        sysFileItemDo.setUrlpath("/files/mindImg/"+fileName);
        sysFileItemDo.setExtends1("files");
        sysFileItemDo.setDeleted("0");
        sysFileItemDo.setCreatedate(DateUtil.date());
        sysFileItemDo.setCreateuserid(currentUser.getId());
        sysFileItemDo.setModifydate(DateUtil.date());
        sysFileItemDo.setModifyuserid(currentUser.getId());
        sysFileItemDo.setCreateusername(currentUser.getName());
        sysFileItemDo.setModifyusername(currentUser.getName());
        this.baseMapper.insertFile(sysFileItemDo);
        //打包文件名称和ID
        String imgUrl = fileName + "-;-" + sysFileItemDo.getId();
        imgPath = imgPath + "@_@" + imgUrl;

        return imgPath;
    }

    /**
     * 获取问题列表
     * @param mesIds
     * @return
     */
    public List<SrmIssuesListDo> getListByMesId(List<String> mesIds){
        return srmIssuesListDao.getListByMesId(mesIds);
    }

    @Override
    public void productionOverdue() {
        //查询需要推送和修改的消息
        List<SysNoticeVo> list = this.baseMapper.selectNoticeByProduct();
        //没有消息，直接结束
        if (list.size() <= 0){
            return;
        }
        //有消息将消息的NOTIFYTYPE改为production_overdue
        List<String> idList = list.stream().map(SysNotifyAnnounceVo::getId).collect(Collectors.toList());
        this.baseMapper.updateNoticeByProduct(idList);
        //将消息发送给app
        for (SysNoticeVo sysNoticeVo : list) {
            String title = sysNoticeVo.getNotifytitle();
            String content = sysNoticeVo.getNotifycontent();
            List<String> userIdList = Arrays.asList(sysNoticeVo.getRecipientIds().split(","));
            CXCommonUtils.pushApp(title,content,userIdList);
        }

    }
}
