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.SecurityServicekMapper;
import com.baichuanxin.openrestapi.dtos.*;
import com.baichuanxin.openrestapi.entity.*;
import com.baichuanxin.openrestapi.service.TaskInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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 SecurityServicekTaskInfoServiceImpl  extends ServiceImpl<SecurityServicekMapper, SecurityServicek> implements TaskInfoService {

    @Autowired
    private OneTaskConfig oneTaskConfig;
    @Autowired
    private AttachTaskInfoServiceImpl  attachTaskInfoService;
    @Autowired
    private ShareholderTaskInfoServiceImpl shareholderTaskInfoService;
    @Autowired
    private ManagerInfoTaskInfoServiceImpl managerInfoTaskInfoService;
    @Autowired
    private RegionCodeServiceImpl regionCodeService;


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

        log.info("=====判断数据是否已经存在:taskId:{}", notice.getTaskId());
        QueryWrapper<SecurityServicek> queryWrapper  = new QueryWrapper<>();
        queryWrapper.eq("taskId",notice.getTaskId());
        SecurityServicek one = this.getOne(queryWrapper);
        if (one!= null){
            log.info("==数据已经存在:taskId:{}", notice.getTaskId());
            return true;
        }else {
            //保存业务数据到业务表
            boolean saveResult = this.save(securityServicek);
            //保存业务数据到业务表
            boolean  saveShareResult= shareholderTaskInfoService.saveOtherInfo(notice.getTaskId(),securityServicekDto.getItem_shareholder(),securityServicek.getID());
            //保存业务数据到业务表
            boolean saveManageResult = managerInfoTaskInfoService.saveOtherInfo(notice.getTaskId(),securityServicekDto.getTxzyglry(),securityServicek.getID());
            //保存文件数据
            boolean saveFileDataResult = attachTaskInfoService.saveOtherInfo(notice,securityServicek.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 (saveResult&&saveShareResult&&saveManageResult&&saveFileDataResult){
                return true;
            }else {
                return false;
            }
        }
    }

    @Override
    public List<String> returnTaskResult(List<Notice> noticeList) {
        List<String> taskList = new ArrayList<>();

        //获取办件ID
        List<String>  taskIdList = new ArrayList<>();
        for (Notice notice : noticeList) {
            taskIdList.add(notice.getTaskId());
        }
        QueryWrapper<SecurityServicek> queryWrapper  = new QueryWrapper<>();
        queryWrapper.in("taskId",taskIdList);
        queryWrapper.in("ITEM_AUDITSTATUS","0","1");
        List<SecurityServicek> securityServicekList = this.list(queryWrapper);
        for (SecurityServicek securityServicek : securityServicekList) {
            Map<String,String> map = new HashMap<>();
            map.put("taskId",securityServicek.getTaskId());
            map.put("userName","湖南省保安监管信息系统");
            map.put("eventName", OnlineTaskUtil.convertStatus(securityServicek.getItemAuditStatus()));
            map.put("opinion",OnlineTaskUtil.convertStatus(OnlineTaskUtil.convertStatus(securityServicek.getItemAuditStatus())));
            map.put("endTime", DateUtil.dateFormatter(securityServicek.getItemOverTime(),"yyyy-MM-dd HH:mm:ss"));
            map.put("isdelivery",securityServicek.getIsdelivery());
            log.info("发送审核结果");
            boolean b = OnlineTaskUtil.returnResult(JSON.toJSONString(map));
            if (b){
                taskList.add(securityServicek.getTaskId());
            }
            log.info("发送结果物");
            if (securityServicek.getItemAuditStatus()=="0"){
                boolean result0 = this.sentResultFile(securityServicek.getTaskId(), securityServicek.getItemAcceptanceFile(),
                        "0");
                if (b&&result0){
                    taskList.add(securityServicek.getTaskId());
                }
            }else if (securityServicek.getItemAuditStatus()=="1"){
                boolean result=OnlineTaskUtil.returnResultFile(securityServicek.getTaskId(),securityServicek.getItemCompanyName(),
                        FileHandleUtil.fileHandle(
                                StrUtil.join("/",oneTaskConfig.getResultPackagePath(),
                                        StrUtil.join(".",securityServicek.getTaskId(),"zip"))),
                        "2");
                if (b&&result){
                    taskList.add(securityServicek.getTaskId());
                }
            }

        }
        return taskList;
    }
    /***
     *@Author duxiangyun
     *@Description   获取审核通过但未制作证书的数据
     *@Date 2024/11/13
     */
    public List<SecurityServicek> getUnGetEC(){
        QueryWrapper<SecurityServicek> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("item_isec","1");  //审核通过且获取信用代码的数据
        queryWrapper.eq("licenseStatus","0");
//        queryWrapper.isNotNull("ITEM_USCC");
        List<SecurityServicek> list = this.list(queryWrapper);
        return list;
    }
    /***
     *@Author duxiangyun
     *@Description
     *@Date 2024/11/13
     */
    public  boolean updateLicenseStatus(String id,String status){
        UpdateWrapper<SecurityServicek> serviceUpdateWrapper = new UpdateWrapper<>();
        serviceUpdateWrapper.eq("id",id);
        serviceUpdateWrapper.set("licenseStatus",status);
        boolean updateStatus = this.update(serviceUpdateWrapper);
        return updateStatus;
    }
    /***
     *@Author duxiangyun
     *@Description
     *@Date 2024/11/13
     */
    public  boolean updateStatusAndfile(String id,String status,String filePath){
        UpdateWrapper<SecurityServicek> serviceUpdateWrapper = new UpdateWrapper<>();
        serviceUpdateWrapper.set("licenseStatus",status);
        serviceUpdateWrapper.set("item_service_file",filePath);
        serviceUpdateWrapper.eq("id",id);
        boolean updateStatus = this.update(serviceUpdateWrapper);
        return updateStatus;
    }
    /***
     *@Author duxiangyun
     *@Description 接收用户回执后更新数据
     *@Date 2024/11/18
     */

    public boolean updateByFeedBack(String taskId,String filePath){
        UpdateWrapper<SecurityServicek> servicekUpdateWrapper =new UpdateWrapper<>();
        servicekUpdateWrapper.eq("taskId",taskId);
        servicekUpdateWrapper.set("item_notice_state","已签收");
        servicekUpdateWrapper.set("item_reach_state","已签收");
        servicekUpdateWrapper.set("item_service_state","已签收");
        servicekUpdateWrapper.set("item_completion_state","已签收");
        servicekUpdateWrapper.set("item_public_completion_file ",filePath);
        servicekUpdateWrapper.set("item_public_reach_file ",filePath);
        boolean status = this.update(servicekUpdateWrapper);
        return status;
    }
//    @Override
//    public boolean getUnsentResultFile(String taskID) {
//        boolean  result = false;
//        QueryWrapper<SecurityServicek>  queryWrapper  = new QueryWrapper<>();
//        queryWrapper.eq("taskId",taskID);
//        queryWrapper.in("ITEM_AUDITSTATUS","0","1");  //其他条件待补充
//        SecurityServicek securityServicek = this.getOne(queryWrapper);
//        if (securityServicek==null){
//            log.info("=================已查询，没有需要发送结果物给用户的办件================");
//        }else {
//            log.info("==========================开始发送结果物================taskid={}",securityServicek.getTaskId());
//            // 审批通过或者不通过要都要发送受理文书
//            // 发送受理文书
//            result = this.sentResultFile(securityServicek.getTaskId(), securityServicek.getItemAcceptanceFile(), "N");
//            if (securityServicek.getItemAuditStatus().equals("1")){
//                boolean result1=this.sentResultFile(securityServicek.getTaskId(), securityServicek.getItemNoticeFile(), "N");
//                boolean result2=this.sentResultFile(securityServicek.getTaskId(), securityServicek.getItemPublicCompletionFile(), "Y");
//                boolean result3=this.sentResultFile(securityServicek.getTaskId(), securityServicek.getItemPublicReachFile(), "Y");
//                boolean result4=this.sentResultFile(securityServicek.getTaskId(), securityServicek.getItemServiceFile(), "N");
//                // boolean sentAcceptanceFile ，boolean sentNoticeFile ,boolean sentPublicCompletion,boolean sentPublicReachFile, boolean sentServiceFile
//                if (result1&&result2&&result3&&result4){
//                    return result;
//                }
//            }
//        }
//        return result;
//    }
    public boolean sentResultFile(String taskID,String fileListString,String specialResultFile) {
        List<FileDto> fileDtos = JSON.parseArray(fileListString, FileDto.class);
        boolean resultNoticeFile = false;
        for (FileDto fileDto : fileDtos) {
            resultNoticeFile = OnlineTaskUtil.returnResultFile(taskID
                    , fileDto.getName()
                    , FileHandleUtil.fileHandle(FileHandleUtil.strHandle(oneTaskConfig.getFilePath(),StrUtil.replace(fileDto.getPath(),"\\","") ))
                    , specialResultFile);
        }
        return resultNoticeFile ;
    }
}
