package com.baichuanxin.openrestapi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
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.CrossRegionalFilingMapper;
import com.baichuanxin.openrestapi.dtos.AttachDto;
import com.baichuanxin.openrestapi.dtos.CrossRegionalFilingDto;
import com.baichuanxin.openrestapi.dtos.FileDto;
import com.baichuanxin.openrestapi.entity.CrossRegionalFiling;
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 CrossRegionalFilingTaskInfoServiceImpl extends ServiceImpl<CrossRegionalFilingMapper,CrossRegionalFiling> implements TaskInfoService {
    @Autowired
    private OneTaskConfig oneTaskConfig;
    @Autowired
    private AttachTaskInfoServiceImpl  attachTaskInfoService;
    @Autowired
    private SecurityManTaskInfoServiceImpl securityManTaskInfoService;
    @Autowired
    private RegionCodeServiceImpl regionCodeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveTaskInfo(Notice  notice) {
        QueryWrapper<CrossRegionalFiling> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("taskId", notice.getTaskId());
        CrossRegionalFiling one = this.getOne(queryWrapper);
        //判断业务数据是否存在
        if (one!=null) {
            log.info("==数据已经存在:taskId:{}", notice.getTaskId());
            return true;
        }else {
            //获取业务数据
            Map<String, Object> formJson = notice.getFormJson();
            CrossRegionalFilingDto crossRegionalFilingDto = JSON.parseObject(JSON.toJSONString(formJson), CrossRegionalFilingDto.class);
            CrossRegionalFiling crossRegionalFiling = crossRegionalFilingDto.convert(notice);
            //区域赋值
            RegionCode regionCode = regionCodeService.getRegionCode(crossRegionalFiling.getItemOfficePoliceAddress());
            crossRegionalFiling.setItemOfficePoliceAddress(regionCode.getName());
            crossRegionalFiling.setItemitemOfficePoliceAddressid(regionCode.getId());
            crossRegionalFiling.setItemOfficePoliceidindex(regionCode.getIndexTree());
            //保存业务数据到业务表
            boolean saveResult = this.save(crossRegionalFiling);
            //保存业务其他数据，如保安人员信息
            //保安员人数
            boolean saveOther =securityManTaskInfoService.saveOtherInfo(notice.getTaskId(),crossRegionalFilingDto.getBayxx(),crossRegionalFiling.getId());
            //保存文件数据
            boolean saveFileDataResult = attachTaskInfoService.saveOtherInfo(notice,crossRegionalFiling.getId());
            //保存文件到服务器
            List<AttachDto> attachList = notice.getAttachList();
            Map<String, List<AttachDto>> map = attachList.stream().collect(Collectors.groupingBy(AttachDto::getMaterialId));
            for (String key :map.keySet()){
                List<AttachDto> attachDtos = map.get(key);
                int i = 1 ;
                for (AttachDto attachDto : attachDtos) {
                    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())));
                        ++i;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
//            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 (saveFileDataResult&&saveResult&&saveOther){
                return true;
            }else {
                return false;
            }
        }
    }



    @Override
    public List<String> returnTaskResult(List<Notice> noticeList) {
        List<String> mapList = new ArrayList<>();
        //获取办件ID
        List<String>  taskIdList = new ArrayList<>();
        for (Notice notice : noticeList) {
            taskIdList.add(notice.getTaskId());
        }
        QueryWrapper<CrossRegionalFiling> queryWrapper = new QueryWrapper();
        queryWrapper.in("taskId", taskIdList);
        queryWrapper.in("ITEM_AUDITSTATUS","0","1");
//        queryWrapper.isNotNull("item_Service_File");
        List<CrossRegionalFiling> list = this.list(queryWrapper);
        for (CrossRegionalFiling crossRegionalFiling : list) {
            Map<String, String> map = new HashMap<>();
            map.put("taskId",crossRegionalFiling.getTaskId());
            map.put("userName","湖南省保安监管信息系统");
            map.put("eventName", OnlineTaskUtil.convertStatus(crossRegionalFiling.getItemAuditStatus()));
            map.put("opinion",OnlineTaskUtil.convertStatus(OnlineTaskUtil.convertStatus(crossRegionalFiling.getItemAuditStatus())));
            map.put("endTime", DateUtil.dateFormatter(crossRegionalFiling.getItemOverTime(),"yyyy-MM-dd HH:mm:ss"));
            map.put("isdelivery",crossRegionalFiling.getIsdelivery());
            List<FileDto> fileDtos = JSON.parseArray(crossRegionalFiling.getItemServiceFile(), FileDto.class);
            boolean b = OnlineTaskUtil.returnResultFile(crossRegionalFiling.getTaskId(), fileDtos.get(0).getName(),
                    FileHandleUtil.fileHandle(FileHandleUtil.strHandle(oneTaskConfig.getResultFilePath(),
                            fileDtos.get(0).getPath())), "0");
            boolean b1 = OnlineTaskUtil.returnResult(JSON.toJSONString(map));
            if (b&&b1){
                mapList.add(crossRegionalFiling.getTaskId() );
            }
        }
        return mapList;

    }
}
