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.SelfRecruitmentFilingMapper;
import com.baichuanxin.openrestapi.dtos.AttachDto;
import com.baichuanxin.openrestapi.dtos.FileDto;
import com.baichuanxin.openrestapi.dtos.SecurityServicekDto;
import com.baichuanxin.openrestapi.dtos.SelfRecruitmentFilingDto;
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 jdk.nashorn.internal.ir.CallNode;
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 SelfRecruitmentFilingTaskInfoImpl extends ServiceImpl<SelfRecruitmentFilingMapper, SelfRecruitmentFiling> implements TaskInfoService  {
    @Autowired
    private OneTaskConfig oneTaskConfig;
    @Autowired
    private AttachTaskInfoServiceImpl attachTaskInfoService;
    @Autowired
    private RegionCodeServiceImpl regionCodeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveTaskInfo(Notice notice) {
        //获取业务数据
        Map<String, Object> formJson = notice.getFormJson();
        SelfRecruitmentFilingDto selfRecruitmentFilingDto = JSON.parseObject(JSON.toJSONString(formJson), SelfRecruitmentFilingDto.class);
        SelfRecruitmentFiling selfRecruitmentFiling = selfRecruitmentFilingDto.convert(notice);
        //区域赋值
        RegionCode regionCode = regionCodeService.getRegionCode(selfRecruitmentFilingDto.getYlcsjyssq());
        selfRecruitmentFiling.setItemOfficePoliceAddress(regionCode.getName());
        selfRecruitmentFiling.setItemitemOfficePoliceAddressid(regionCode.getId());
        selfRecruitmentFiling.setItemOfficePoliceidindex(regionCode.getIndexTree());

        log.info("=====判断数据是否已经存在:taskId:{}", notice.getTaskId());
        QueryWrapper<SelfRecruitmentFiling> queryWrapper  = new QueryWrapper<>();
        queryWrapper.eq("taskId",notice.getTaskId());
        SelfRecruitmentFiling one = this.getOne(queryWrapper);
        if (one!= null){
            log.info("==数据已经存在:taskId:{}", notice.getTaskId());
            return true;
        }else {
            //保存业务数据到业务表
            boolean saveResult = this.save(selfRecruitmentFiling);
            //保存文件数据
            boolean saveFileDataResult = attachTaskInfoService.saveOtherInfo(notice,selfRecruitmentFiling.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();
                    }
                }
            }
            if (saveFileDataResult&&saveResult){
                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<SelfRecruitmentFiling> queryWrapper = new QueryWrapper();
        queryWrapper.in("taskId", taskIdList);
        queryWrapper.in("ITEM_AUDITSTATUS","0","1");
//        queryWrapper.isNotNull("item_Service_File");
        List<SelfRecruitmentFiling> list = this.list(queryWrapper);
        for (SelfRecruitmentFiling selfRecruitmentFiling : list) {
            Map<String, String> map = new HashMap<>();
            map.put("taskId",selfRecruitmentFiling.getTaskId());
            map.put("userName","湖南省保安监管信息系统");
            map.put("eventName", OnlineTaskUtil.convertStatus(selfRecruitmentFiling.getItemAuditStatus()));
            map.put("opinion",OnlineTaskUtil.convertStatus(OnlineTaskUtil.convertStatus(selfRecruitmentFiling.getItemAuditStatus())));
            map.put("endTime", DateUtil.dateFormatter(selfRecruitmentFiling.getItemOverTime(),"yyyy-MM-dd HH:mm:ss"));
            map.put("isdelivery",selfRecruitmentFiling.getIsdelivery());
            //先不返回文件
//            List<FileDto> fileDtos = JSON.parseArray(selfRecruitmentFiling.getItemServiceFile(), FileDto.class);
//            boolean b = OnlineTaskUtil.returnResultFile(selfRecruitmentFiling.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(selfRecruitmentFiling.getTaskId() );
            }
        }
        return mapList;
    }
}
