package com.baichuanxin.openrestapi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baichuanxin.openrestapi.common.OnlineTaskConstant;
import com.baichuanxin.openrestapi.common.utils.DateUtil;
import com.baichuanxin.openrestapi.common.utils.FileHandleUtil;
import com.baichuanxin.openrestapi.common.utils.OnlineTaskUtil;
import com.baichuanxin.openrestapi.configs.OneTaskConfig;
import com.baichuanxin.openrestapi.dao.mapper.AttachMapper;
import com.baichuanxin.openrestapi.dao.mapper.CertificateServiceMapper;
import com.baichuanxin.openrestapi.dtos.AttachDto;
import com.baichuanxin.openrestapi.dtos.CertificateServiceDto;
import com.baichuanxin.openrestapi.entity.Attach;
import com.baichuanxin.openrestapi.entity.CertificateService;
import com.baichuanxin.openrestapi.entity.Notice;
import com.baichuanxin.openrestapi.entity.RegionCode;
import com.baichuanxin.openrestapi.service.TaskInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
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/8/24
 */
@Slf4j
@Service
public class ExamTaskInfoServiceImpl extends ServiceImpl<CertificateServiceMapper,CertificateService> implements TaskInfoService  {

    @Autowired
    private OneTaskConfig oneTaskConfig;
    @Autowired
    private AttachTaskInfoServiceImpl  attachTaskInfoService;
    @Autowired
    private RegionCodeServiceImpl regionCodeService;
    @Autowired
    private NationDicServiceImpl nationDicService;
    @Override
    @Transactional
    public boolean saveTaskInfo(Notice  notice ) {
        //获取业务数据
        Map<String, Object> formJson = notice.getFormJson();
        CertificateServiceDto certificateServiceDto = JSON.parseObject(JSON.toJSONString(formJson), CertificateServiceDto.class);
        CertificateService certificateService = certificateServiceDto.convert(notice);
        //区域赋值
        RegionCode regionCode = regionCodeService.getRegionCode(certificateService.getItemExamArea());
        certificateService.setItemOfficePoliceAddress(regionCode.getName());
        certificateService.setItemExamArea(regionCode.getName());
        certificateService.setItemOfficePoliceAddressid(regionCode.getId());
        certificateService.setItemOfficePoliceidindex(regionCode.getIndexTree());
        //编码转换成文字
        certificateService.setItemNation(nationDicService.getValue(certificateService.getItemNation()));
        certificateService.setItemPoliticalOutlook(OnlineTaskUtil.identConvert(certificateService.getItemPoliticalOutlook()));
        certificateService.setItemEducation(OnlineTaskUtil.eduConvert(certificateService.getItemEducation()));
        //保存附件信息
        List<AttachDto> attachList = notice.getAttachList();
        Map<String, List<AttachDto>> map = attachList.stream().collect(Collectors.groupingBy(AttachDto::getMaterialId));
        for (String key :map.keySet()){
            if (key.equals(OnlineTaskConstant.FILE_1)){
                List<AttachDto> attachDtos = map.get(key);
                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);
                    try {
                        FileHandleUtil.saveApplyFileHandle(StrUtil.join("",oneTaskConfig.getDownloadUrl(),attachDto.getAttachPath())
                                ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId(),i)
                                ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId(),i
                                        ,StrUtil.join(".",attachDto.getMaterialName(),attachDto.getAttachType())));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    ++i;
                }
                certificateService.setItemPhysicalFile(JSON.toJSONString(lists));
            }
            if (key.equals(OnlineTaskConstant.FILE_2)){
                List<AttachDto> attachDtos = map.get(key);
                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);
                    try {
                        FileHandleUtil.saveApplyFileHandle(StrUtil.join("",oneTaskConfig.getDownloadUrl(),attachDto.getAttachPath())
                                ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId(),i)
                                ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId(),i
                                        ,StrUtil.join(".",attachDto.getMaterialName(),attachDto.getAttachType())));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    ++i;
                }
                certificateService.setItemEducationFile(JSON.toJSONString(lists));
            }
            if (key.equals(OnlineTaskConstant.FILE_3)){
                List<AttachDto> attachDtos = map.get(key);
                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);
                    try {
                        FileHandleUtil.saveApplyFileHandle(StrUtil.join("",oneTaskConfig.getDownloadUrl(),attachDto.getAttachPath())
                                ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId(),i)
                                ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId(),i
                                        ,StrUtil.join(".",attachDto.getMaterialName(),attachDto.getAttachType())));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    ++i;
                }
                certificateService.setItemIdcardFile(JSON.toJSONString(lists));
            }
            if (key.equals(OnlineTaskConstant.FILE_4)){
                List<AttachDto> attachDtos = map.get(key);
                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);
                    try {
                        FileHandleUtil.saveApplyFileHandle(StrUtil.join("",oneTaskConfig.getDownloadUrl(),attachDto.getAttachPath())
                                ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId(),i)
                                ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId(),i
                                        ,StrUtil.join(".",attachDto.getMaterialName(),attachDto.getAttachType())));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    ++i;
                }
                certificateService.setItemInchFile(JSON.toJSONString(lists));
            }
        }


//        for (AttachDto attachDto : attachList) {
//            List<Map<String, Object>> materials = attachDto.getMaterials(notice);
//            if (attachDto.getMaterialId().equals(OnlineTaskConstant.FILE_1)){
//                certificateService.setItemPhysicalFile(JSON.toJSONString(materials));
//            }
//            if (attachDto.getMaterialId().equals(OnlineTaskConstant.FILE_2)){
//                certificateService.setItemEducationFile(JSON.toJSONString(materials));
//            }
//            if (attachDto.getMaterialId().equals(OnlineTaskConstant.FILE_3)){
//                certificateService.setItemIdcardFile(JSON.toJSONString(materials));
//            }
//        }
        //保存业务数据到业务表
        boolean saveResult = this.save(certificateService);
        //保存文件到服务器
//        for (AttachDto attachDto : attachList) {
//            try {
//                FileHandleUtil.saveApplyFileHandle(StrUtil.join("",oneTaskConfig.getDownloadUrl(),attachDto.getAttachPath())
//                        ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId())
//                        ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),attachDto.getMaterialId()
//                                ,StrUtil.join(".",attachDto.getMaterialName(),attachDto.getAttachType())));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        if (saveResult){
            return true;
        }else {
            return false;
        }

    }

    @Override
    public List<String> returnTaskResult(List<Notice> noticeList) {
        List<String>  taskIds  =new ArrayList<>();
        //根据taskID获取
        List<String>  taskIdList = new ArrayList<>();
        for (Notice notice : noticeList) {
            taskIdList.add(notice.getTaskId());
        }
        QueryWrapper<CertificateService> queryWrapper  = new QueryWrapper<>();
        queryWrapper.in("taskId",taskIdList);
        queryWrapper.in("item_approval_status","0","1");
        List<CertificateService> certificateServiceList = this.list(queryWrapper);
        for (CertificateService certificateService:certificateServiceList){
            Map<String,Object> map1 =new HashMap<>();
            Map<String,String> map = new HashMap<>();
            map.put("taskId",certificateService.getTaskId());
            map.put("userName","湖南省保安监管信息系统");
            map.put("eventName", OnlineTaskUtil.convertStatus(certificateService.getItemApprovalStatus()));
//            map.put("opinion",certificateService.getItemApprovalRemark());
            map.put("opinion","无");
            log.info("审核时间回传：{}",DateUtil.dateFormatter(certificateService.getItemApprovalTime(),"yyyy-MM-dd HH:mm:ss"));
            map.put("endTime", DateUtil.dateFormatter(certificateService.getItemApprovalTime(),"yyyy-MM-dd HH:mm:ss"));
            map.put("isdelivery","0");
            boolean result = OnlineTaskUtil.returnResult(JSON.toJSONString(map));
            if (result){
                taskIds.add(certificateService.getTaskId());
            }
        }
        return taskIds;
    }


}
