package com.baichuanxin.openrestapi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baichuanxin.openrestapi.dao.mapper.AttachMapper;
import com.baichuanxin.openrestapi.dtos.AttachDto;
import com.baichuanxin.openrestapi.entity.Attach;
import com.baichuanxin.openrestapi.entity.Notice;
import com.baichuanxin.openrestapi.service.TaskInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/***
 *@Author duxiangyun
 *@Description 所有事项附件信息保存到库
 *@Date 2024/9/3
 */
@Service
public class AttachTaskInfoServiceImpl extends ServiceImpl<AttachMapper, Attach> implements TaskInfoService {

    @Override
    public boolean saveTaskInfo(Notice notice) {
        return true;
    }

    @Override
    public List<String> returnTaskResult(List<Notice> noticeList) {
        return null;
    }


    public boolean saveOtherInfo(Notice notice,String topId){
        List<AttachDto> attachList = notice.getAttachList();
        List<Attach>  attaches = new ArrayList<>();
        Map<String, List<AttachDto>> map = attachList.stream().collect(Collectors.groupingBy(AttachDto::getMaterialId));
        for (String key :map.keySet()){
            List<AttachDto> attachDtos = map.get(key);
            Attach attache = attachDtos.get(0).convert(notice);
            List<Map<String,Object>> lists = new ArrayList<>();
            int i =1;
            for (AttachDto attachDto : attachDtos) {
                Map<String,Object>  map1  = new HashMap<>();
                map1.put("uid","");
                map1.put("path", StrUtil.join("/","/uploads/onetask",notice.getMatId(),notice.getTaskId(),
                        attachDto.getMaterialId(),i,StrUtil.join(".",attachDto.getMaterialName(),attachDto.getAttachType())));
                map1.put("originalPath",StrUtil.join("/","/uploads/onetask",notice.getMatId(),notice.getTaskId(),
                        attachDto.getMaterialId(),i,StrUtil.join(".",attachDto.getMaterialName(),attachDto.getAttachType())));
                map1.put("name",StrUtil.join(".",attachDto.getMaterialName(),attachDto.getAttachType()));
                lists.add(map1);
                ++i;
            }
            attache.setItemMaterials(JSON.toJSONString(lists));
            attache.setItemTopid(topId);
            attaches.add(attache);
        }


//        for (AttachDto attachDto : attachList) {
//            Attach attache = attachDto.convert(notice);
//            attache.setItemTopid(topId);
//            attaches.add(attache);
//        }
        return this.saveBatch(attaches);

    }
}
