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.RegistrationBranchMapper;
import com.baichuanxin.openrestapi.dtos.AttachDto;
import com.baichuanxin.openrestapi.dtos.CrossRegionalFilingDto;
import com.baichuanxin.openrestapi.dtos.FileDto;
import com.baichuanxin.openrestapi.dtos.RegisterBranchDto;
import com.baichuanxin.openrestapi.entity.*;
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 RegistrationBranchTaskInfoServiceImpl extends ServiceImpl<RegistrationBranchMapper, RegistrationBranch> 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<RegistrationBranch> queryWrapper  = new QueryWrapper<>();
        queryWrapper.eq("taskId",notice.getTaskId());
        RegistrationBranch one = this.getOne(queryWrapper);
        if (one!= null){
            log.info("==数据已经存在:taskId:{}", notice.getTaskId());
            return true;
        }else {
            //获取业务数据
            Map<String, Object> formJson = notice.getFormJson();
            RegisterBranchDto registerBranchDto = JSON.parseObject(JSON.toJSONString(formJson), RegisterBranchDto.class);
            RegistrationBranch registrationBranch = registerBranchDto.convert(notice);
            //区域赋值
            RegionCode regionCode = regionCodeService.getRegionCode(registrationBranch.getItemOfficePoliceAddress());
            registrationBranch.setItemOfficePoliceAddress(regionCode.getName());
            registrationBranch.setItemitemOfficePoliceAddressid(regionCode.getId());
            registrationBranch.setItemOfficePoliceidindex(regionCode.getIndexTree());
            //保存业务数据到业务表
            boolean saveResult = this.save(registrationBranch);
            //保存业务数据到业务表
            boolean saveManResult = securityManTaskInfoService.saveOtherInfo(notice.getTaskId(),registerBranchDto.getBayxx(),registrationBranch.getId());
            //保存文件数据
            boolean saveFileDataResult = attachTaskInfoService.saveOtherInfo(notice,registrationBranch.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&&saveManResult){
                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<RegistrationBranch> queryWrapper = new QueryWrapper();
        queryWrapper.in("taskId", taskIdList);
        queryWrapper.in("ITEM_AUDITSTATUS","0","1");
//        queryWrapper.isNotNull("item_Service_File");
        List<RegistrationBranch> list = this.list(queryWrapper);
        for (RegistrationBranch registrationBranch : list) {
            Map<String, String> map = new HashMap<>();
            map.put("taskId",registrationBranch.getTaskId());
            map.put("userName","湖南省保安监管信息系统");
            map.put("eventName", OnlineTaskUtil.convertStatus(registrationBranch.getItemAuditStatus()));
            map.put("opinion",OnlineTaskUtil.convertStatus(OnlineTaskUtil.convertStatus(registrationBranch.getItemAuditStatus())));
            map.put("endTime", DateUtil.dateFormatter(registrationBranch.getItemOverTime(),"yyyy-MM-dd HH:mm:ss"));
            map.put("isdelivery",registrationBranch.getIsdelivery());
            //先不回传附件
//            List<FileDto> fileDtos = JSON.parseArray(registrationBranch.getItemServiceFile(), FileDto.class);
//            boolean b = OnlineTaskUtil.returnResultFile(registrationBranch.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){
            if (b1){
                mapList.add(registrationBranch.getTaskId() );
            }
        }
        return mapList;
    }

}
