package com.baichuanxin.openrestapi.scheduling;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baichuanxin.openrestapi.common.OnlineTaskConstant;
import com.baichuanxin.openrestapi.common.utils.FileHandleUtil;
import com.baichuanxin.openrestapi.common.utils.OnlineTaskUtil;
import com.baichuanxin.openrestapi.configs.OneTaskConfig;
import com.baichuanxin.openrestapi.dtos.AttachDto;
import com.baichuanxin.openrestapi.dtos.FileDto;
import com.baichuanxin.openrestapi.entity.ChangeLegalPerson;
import com.baichuanxin.openrestapi.entity.Notice;
import com.baichuanxin.openrestapi.entity.SecurityServicek;
import com.baichuanxin.openrestapi.factorys.TaskFactory;
import com.baichuanxin.openrestapi.service.NoticeService;
import com.baichuanxin.openrestapi.service.TaskInfoService;
import com.baichuanxin.openrestapi.service.impl.ChangeLegalPersonTaskInfoServiceImpl;
import com.baichuanxin.openrestapi.service.impl.NoticeServiceImpl;
import com.baichuanxin.openrestapi.service.impl.SecurityServicekTaskInfoServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;


/**
 *@Author duxiangyun
 *@Description 定时任务执行一网通办任务
 *@Date 2024/8/22
 */
@Slf4j
@Component
public class OnlineServiceTask {

    @Autowired
    private NoticeService noticeService;
    @Autowired
    private OneTaskConfig oneTaskConfig;
    @Autowired
    private SecurityServicekTaskInfoServiceImpl servicekServiceImpl;
    @Autowired
    private ChangeLegalPersonTaskInfoServiceImpl   changeLegalPersonImpl;

    /**
     *@Author duxiangyun
     *@Description  获取办件数据
     *@Date 2024/8/22
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void getDataTask() {
        log.info("========================开始获取办件数据========================");
        Notice unGetTask = noticeService.getUnFinishTask();  //拿到未获取数据的办件ID
        if (unGetTask==null){
            log.info("=================结束获取办件数据，0个办件=============================");
        }else {
            //调用接口获取数据 ,返回业务数据响应体
            String taskResultData = OnlineTaskUtil.getTaskInfo(unGetTask.getTaskId());
            if (!taskResultData.equals("false")){
                Notice notice = JSON.parseObject(taskResultData, Notice.class);
                //根据办件类型调用不同Service  service工厂 输入不同的matId 返回不同Service
                TaskInfoService taskInfoService = TaskFactory.creatTaskService(notice.getMatId());
                log.info("==================================开始保存业务数据、以及文件taskID=={}",notice.getTaskId());
                boolean saveResult = taskInfoService.saveTaskInfo(notice);
                log.info("==================================响应体Data=={}",taskResultData);
                if (saveResult){
                    Map<String ,Object> confirmMap=new HashMap<>();
                    confirmMap.put("confirmType", OnlineTaskConstant.CONFIRM_TYPE_0);
                    //业务数据保存成功，告诉第三方已经接受数据
                    boolean b = OnlineTaskUtil.taskConfirm(notice.getTaskId(), confirmMap);
                    log.info("=======确认确认结果{}",b);
                    if (b){
                        notice.setStatus(1);    //业务数据保存成功则修改办件通知表状态，修改为1 代表已收办件
                        noticeService.updateNoticeOneByTaskId(notice);
                    }
                }
                log.info("============办件数据获取完成办件ID：{}======================",unGetTask.getTaskId());
            }else{
                log.info("=========办件数据获取失败办件ID：{}==========================",unGetTask.getTaskId());
            }
        }
    }
    /**
     *@Author duxiangyun
     *@Description  保安员资格证返回办件状态
     *@Date 2024/8/22
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void certificateReturnResultTask() {
        //办件通知表取回还没返回状态的保安员申办数据
        List<Notice> noticeList = noticeService.getUnReturnList(1,0, OnlineTaskConstant.MAT_ID_2);
        if (noticeList.size()!=0) {
            TaskInfoService taskInfoService = TaskFactory.creatTaskService(OnlineTaskConstant.MAT_ID_2);
            List<String> taskIdList = taskInfoService.returnTaskResult(noticeList);
            for (String taskId : taskIdList) {
                    noticeService.updateNoticeStatus(taskId, 2,2);

            }
        }
    }

    /**
     *@Author duxiangyun
     *@Description  保安服务公司设立返回办件状态和结果物
     *@Date 2024/8/22
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void securityServicekReturnResultTask() {
        //办件通知表取回还没返回状态的保安员申办数据
        List<Notice> noticeList = noticeService.getUnReturnList(1,1, OnlineTaskConstant.MAT_ID_0);
        if (noticeList.size()>0){
            TaskInfoService taskInfoService = TaskFactory.creatTaskService(OnlineTaskConstant.MAT_ID_0);
            List<String> taskIdList = taskInfoService.returnTaskResult(noticeList);
            for (String taskId: taskIdList) {
                noticeService.updateNoticeStatus(taskId,2,2);
            }
        }
    }

    /**
     *@Author duxiangyun
     *@Description  法人变更返回办件状态和结果物
     *@Date 2024/8/22
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void changeLegalReturnResultTask() {
        //办件通知表取回还没返回状态的保安员申办数据
        log.info("=======================法人变更结果物返回====================");
        List<Notice> noticeList = noticeService.getUnReturnList(1,1, OnlineTaskConstant.MAT_ID_1);
        if (noticeList.size()>0){
            TaskInfoService taskInfoService = TaskFactory.creatTaskService(OnlineTaskConstant.MAT_ID_1);
            List<String> taskIdList = taskInfoService.returnTaskResult(noticeList);
            for (String taskId: taskIdList) {
                noticeService.updateNoticeStatus(taskId,2,2);
            }
        }
    }

    /**
     *@Author duxiangyun
     *@Description  备案事项返回办件状态和办件物
     *@Date 2024/8/22
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void returnResultAndFile1Task() {
        log.info("=======================自招单位备案结果物返回开始====================");
        List<Notice> noticeList3 = noticeService.getUnReturnList(1,0, OnlineTaskConstant.MAT_ID_3);
        if (noticeList3.size()>0){
            TaskInfoService taskInfoService = TaskFactory.creatTaskService(OnlineTaskConstant.MAT_ID_3);
            List<String> taskIds = taskInfoService.returnTaskResult(noticeList3);
            for (String taskId: taskIds) {
                noticeService.updateNoticeStatus(taskId,2,2);
            }
            log.info("=====================自招单位备案结果物返回结束=====================");
        }
    }
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void returnResultAndFile2Task() {
        List<Notice> noticeList4 = noticeService.getUnReturnList(1,0, OnlineTaskConstant.MAT_ID_4);
        if (noticeList4.size()>0){
            TaskInfoService taskInfoService = TaskFactory.creatTaskService(OnlineTaskConstant.MAT_ID_4);
            List<String> taskIds = taskInfoService.returnTaskResult(noticeList4);
            for (String taskId: taskIds) {
                noticeService.updateNoticeStatus(taskId,2,2);
            }
        }
    }
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void returnResultAndFile3Task() {
        List<Notice> noticeList5 = noticeService.getUnReturnList(1,0, OnlineTaskConstant.MAT_ID_5);
        if (noticeList5.size()>0){
            TaskInfoService taskInfoService = TaskFactory.creatTaskService(OnlineTaskConstant.MAT_ID_5);
            List<String> taskIds = taskInfoService.returnTaskResult(noticeList5);
            for (String taskId: taskIds) {
                noticeService.updateNoticeStatus(taskId,2,2);
            }
        }
    }

    /**
     * 扫描办件流程已经结束，还未发送办件状态和办件结果物给用户的办件
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void checkTaskFile() {
        log.info("====检查需要发送结果物的任务==========");
        List<Notice> checkTaskFile = noticeService.getCheckTaskFile();
        for (Notice notice : checkTaskFile) {
            //根据taskId 查找
            if (notice.getMatId().equals(OnlineTaskConstant.MAT_ID_0)){
                log.info("====检查需要发送结果物的任务：保安服务公司设立==========");
                SecurityServicek securityServicek = servicekServiceImpl.getById(StrUtil.join("--", notice.getTaskId(),
                        OnlineTaskConstant.SECURITY_SERVICE_K));
                if (!Objects.isNull(securityServicek)&&securityServicek.getItemAuditStatus().equals("0")){
                    if (StrUtil.isNotBlank(securityServicek.getItemAcceptanceFile())){
                        noticeService.updateNoticeStatus(notice.getTaskId(),1,1);
                    }
                } else if (!Objects.isNull(securityServicek)&&securityServicek.getItemAuditStatus().equals("1")) {
                    if (StrUtil.isNotBlank(securityServicek.getItemAcceptanceFile())&&
                            StrUtil.isNotBlank(securityServicek.getItemPublicReachFile())&&
                            StrUtil.isNotBlank(securityServicek.getItemPublicCompletionFile())
//                            && StrUtil.isNotBlank(securityServicek.getItemServiceFile())
                    ){
                        List<FileDto> acceptanceFile = JSON.parseArray(securityServicek.getItemAcceptanceFile(), FileDto.class);
                        List<FileDto> publicReachFile = JSON.parseArray(securityServicek.getItemPublicReachFile(), FileDto.class);
                        List<FileDto> publicCompletion = JSON.parseArray(securityServicek.getItemPublicCompletionFile(), FileDto.class);
//                        List<FileDto> serviceFile = JSON.parseArray(securityServicek.getItemServiceFile(), FileDto.class);
                        try {
                            FileHandleUtil.moveFile(StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId()),
                                    StrUtil.join("/",oneTaskConfig.getResultFilePath(),acceptanceFile.get(0).getPath()),
                                    StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId(),acceptanceFile.get(0).getName()));
                            FileHandleUtil.moveFile(StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId()),
                                    StrUtil.join("/",oneTaskConfig.getResultFilePath(),publicReachFile.get(0).getPath()),
                                    StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId(),publicReachFile.get(0).getName()));
                            FileHandleUtil.moveFile(StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId()),
                                    StrUtil.join("/",oneTaskConfig.getResultFilePath(),publicCompletion.get(0).getPath()),
                                    StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId(),publicCompletion.get(0).getName()));
//                            FileHandleUtil.moveFile(StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId()),
//                                    StrUtil.join("/",oneTaskConfig.getResultFilePath(),serviceFile.get(0).getPath()),
//                                    StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId(),serviceFile.get(0).getName()));
                            FileHandleUtil.filePackage(StrUtil.join("/",oneTaskConfig.getResultPackagePath(),StrUtil.join(".",notice.getTaskId(),"zip"))
                                    ,StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId()));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        noticeService.updateNoticeStatus(notice.getTaskId(),1,1);
                    }
                }
            }else if (notice.getMatId().equals(OnlineTaskConstant.MAT_ID_1)){
                log.info("====检查需要发送结果物的任务：法人变更==========");
                ChangeLegalPerson changeLegal = changeLegalPersonImpl.getById(StrUtil.join("--", notice.getTaskId(),
                        OnlineTaskConstant.CHANGE_LEGAL_PERSON));
                log.info("检查办件状态：{}",changeLegal.getItemAuditStatus());
                if (!Objects.isNull(changeLegal)&&changeLegal.getItemAuditStatus().equals("0")){
                    if (StrUtil.isNotBlank(changeLegal.getItemAcceptanceFile())){
                        noticeService.updateNoticeStatus(notice.getTaskId(),1,1);
                    }
                    break;
                } else if (!Objects.isNull(changeLegal)&&changeLegal.getItemAuditStatus().equals("1")) {
                    log.info("进入到文件判断：{}",changeLegal.getItemAuditStatus());
                    if (StrUtil.isNotBlank(changeLegal.getItemAcceptanceFile())&&
                            StrUtil.isNotBlank(changeLegal.getItemPublicReachFile())&&
                            StrUtil.isNotBlank(changeLegal.getItemPublicCompletionFile())&&
                            StrUtil.isNotBlank(changeLegal.getItemServiceFile())){
                        List<FileDto> acceptanceFile = JSON.parseArray(changeLegal.getItemAcceptanceFile(), FileDto.class);
                        List<FileDto> publicReachFile = JSON.parseArray(changeLegal.getItemPublicReachFile(), FileDto.class);
                        List<FileDto> publicCompletion = JSON.parseArray(changeLegal.getItemPublicCompletionFile(), FileDto.class);
                        List<FileDto> serviceFile = JSON.parseArray(changeLegal.getItemServiceFile(), FileDto.class);
                        try {
                            FileHandleUtil.moveFile(StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId()),
                                    StrUtil.join("/",oneTaskConfig.getResultFilePath(),acceptanceFile.get(0).getPath()),
                                    StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId(),acceptanceFile.get(0).getName()));
                            FileHandleUtil.moveFile(StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId()),
                                    StrUtil.join("/",oneTaskConfig.getResultFilePath(),publicReachFile.get(0).getPath()),
                                    StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId(),publicReachFile.get(0).getName()));
                            FileHandleUtil.moveFile(StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId()),
                                    StrUtil.join("/",oneTaskConfig.getResultFilePath(),publicCompletion.get(0).getPath()),
                                    StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId(),publicCompletion.get(0).getName()));
                            FileHandleUtil.moveFile(StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId()),
                                    StrUtil.join("/",oneTaskConfig.getResultFilePath(),serviceFile.get(0).getPath()),
                                    StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId(),serviceFile.get(0).getName()));
                            FileHandleUtil.filePackage(StrUtil.join("/",oneTaskConfig.getResultPackagePath(),StrUtil.join(".",notice.getTaskId(),"zip")),
                                    StrUtil.join("/",oneTaskConfig.getResultPackagePath(),notice.getTaskId()));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        noticeService.updateNoticeStatus(notice.getTaskId(),1,1);
                    }
                }
            }
        }
    }




    /***
     *@Author duxiangyun
     *@Description  保安服务公司设立许可 扫描已经发送办结文书但还未接收到用户回执的任务
     *@Date 2024/11/18
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void getFeedBack() throws IOException {
        List<Notice> unReturnList = noticeService.getUnReturnList(2, 2, OnlineTaskConstant.MAT_ID_0);
        for (Notice notice : unReturnList) {
            int i =1;
            String feedBackString = OnlineTaskUtil.getFeedBack(notice.getTaskId());
            if (!feedBackString.equals("false")){
                List<Map<String,Object>> list = JSON.parseObject(feedBackString, List.class);
                List<Map<String,Object>> lists = new ArrayList<>();
                for (Map<String, Object> stringMap : list) {
                    String attachUrl = stringMap.get("feedbackAttachUrl").toString();
                    //保存文件
                    //获取文件后缀名
                    String fileSuffix = FileUtil.getSuffix(attachUrl);
                    log.info("用户回执文件后缀名{}",fileSuffix);
                    FileHandleUtil.saveApplyFileHandle(StrUtil.join("",oneTaskConfig.getDownloadUrl(),attachUrl)
                            ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),stringMap.get("feedbackId"),i)
                            ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),stringMap.get("feedbackId"),i
                                    ,StrUtil.join(".","回执",fileSuffix)));
                    //将文件封装成数据库保存格式
                    Map<String,Object>  map1  = new HashMap<>();
                    map1.put("uid","");
                    map1.put("path", StrUtil.join("/","/uploads/onetask",notice.getMatId(),notice.getTaskId(),
                            stringMap.get("feedbackId"),i,StrUtil.join(".","回执",fileSuffix)));
                    map1.put("originalPath",StrUtil.join("/","/uploads/onetask",notice.getMatId(),notice.getTaskId(),
                            stringMap.get("feedbackId"),i,StrUtil.join(".","回执",fileSuffix)));
                    map1.put("name",StrUtil.join(".","回执",fileSuffix));
                    lists.add(map1);
                    ++i;
                }
                boolean b = servicekServiceImpl.updateByFeedBack(notice.getTaskId(), JSON.toJSONString(lists));
                if (b){
                    noticeService.updateNoticeStatus(notice.getTaskId(),3,3);
                }
            }
        }
    }

    /***
     *@Author duxiangyun
     *@Description  保安服务公司法人变更 扫描已经发送办结文书但还未接收到用户回执的任务
     *@Date 2024/11/18
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void getChangeKFeedBack() throws IOException {
        List<Notice> unReturnList = noticeService.getUnReturnList(2, 2, OnlineTaskConstant.MAT_ID_1);
        for (Notice notice : unReturnList) {
            int i =1;
            String feedBackString = OnlineTaskUtil.getFeedBack(notice.getTaskId());
            if (!feedBackString.equals("false")){
                List<Map<String,Object>> list = JSON.parseObject(feedBackString, List.class);
                List<Map<String,Object>> lists = new ArrayList<>();
                for (Map<String, Object> stringMap : list) {
                    String attachUrl = stringMap.get("feedbackAttachUrl").toString();
                    //保存文件
                    //获取文件后缀名
                    String fileSuffix = FileUtil.getSuffix(attachUrl);
                    log.info("用户回执文件后缀名{}",fileSuffix);
                    FileHandleUtil.saveApplyFileHandle(StrUtil.join("",oneTaskConfig.getDownloadUrl(),attachUrl)
                            ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),stringMap.get("feedbackId"),i)
                            ,StrUtil.join("/",oneTaskConfig.getSaveFile(),notice.getMatId(),notice.getTaskId(),stringMap.get("feedbackId"),i
                                    ,StrUtil.join(".","回执",fileSuffix)));
                    //将文件封装成数据库保存格式
                    Map<String,Object>  map1  = new HashMap<>();
                    map1.put("uid","");
                    map1.put("path", StrUtil.join("/","/uploads/onetask",notice.getMatId(),notice.getTaskId(),
                            stringMap.get("feedbackId"),i,StrUtil.join(".","回执",fileSuffix)));
                    map1.put("originalPath",StrUtil.join("/","/uploads/onetask",notice.getMatId(),notice.getTaskId(),
                            stringMap.get("feedbackId"),i,StrUtil.join(".","回执",fileSuffix)));
                    map1.put("name",StrUtil.join(".","回执",fileSuffix));
                    lists.add(map1);
                    ++i;
                }
                boolean b = changeLegalPersonImpl.updateByFeedBack(notice.getTaskId(), JSON.toJSONString(lists));
                if (b){
                    noticeService.updateNoticeStatus(notice.getTaskId(),3,3);
                }
            }
        }
    }
}
