package net.northking.cctp.se.plan.servcie;

import com.alibaba.fastjson.JSON;
import net.northking.cctp.common.enums.FileBusinessTypeEnum;
import net.northking.cctp.common.http.ResultWrapper;
import net.northking.cctp.common.util.UUIDUtil;
import net.northking.cctp.se.config.AtuServerConfig;
import net.northking.cctp.se.file.Attachment;
import net.northking.cctp.se.plan.bean.EnginePlanInfo;
import net.northking.cctp.se.plan.bean.EnginePlanQuery;
import net.northking.cctp.se.plan.bean.PlanDeviceInfo;
import net.northking.cctp.se.repository.EnginePlanInfoRepository;
import net.northking.cctp.se.util.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EnginePlanInfoServiceImpl implements EnginePlanInfoService {

    private static final Logger logger = LoggerFactory.getLogger(EnginePlanInfoServiceImpl.class);

    @Autowired
    private EnginePlanInfoRepository repository;

    @Autowired
    private PlanDeviceService planDeviceService;

    @Autowired
    private AtuServerConfig atuServerConfig;

    @Override
    public Integer entrustEnginPlan(EnginePlanQuery planParam) {
        logger.debug("任务计划委托开始。。。。。。。");
        List<PlanDeviceInfo> deviceIdList = planParam.getDeviceList();
        int count = 0;
        if(CollectionUtils.isEmpty(deviceIdList)){
            return count;
        }
        logger.debug("任务计划委托信息 ------>: "+ JSON.toJSONString(planParam));
        try {
            for (int i = 0; i < deviceIdList.size(); i++) {
                PlanDeviceInfo s =  deviceIdList.get(i);
                EnginePlanInfo info = new EnginePlanInfo();
                BeanUtils.copyProperties(planParam,info);
                info.setId(UUIDUtil.create32UUID());
                info.setDeviceId(s.getDeviceId());
                if(StringUtils.isNotBlank(s.getBrowserType())){
                    info.setBrowserType(s.getBrowserType());
                }
                info.setCreatedTime(new Date());
                info.setSort(0l);
                repository.save(info);
                count++;
            }
        } catch (Exception e) {
            logger.error("委托计划失败：",e);
        }
        logger.debug("任务计划委托结束。。。。。。。");
        return count;
    }

    @Override
    public Integer removeEnginePlan(String batchId) {
        try {
            repository.deletePlanInfoByBatchId(batchId);
            
            planDeviceService.stopRunningExec(batchId);
        } catch (Exception e) {
            logger.error("移除计划批次信息失败：",e);
            return 0;
        }
        return 1;
    }

    @Override
    public void removeEnginePlanByType(String batchId, String type) {
        try {
            repository.removeEnginePlanByType(batchId,type);
        } catch (Exception e) {
            logger.error("移除类型为："+type+"的计划批次信息失败：",e);
        }
    }

    @Override
    public List<EnginePlanInfo> queryInfoByDeviceId(String deviceId,String type) {
        List<EnginePlanInfo> info = null;
        try {
            info = repository.getOneInfoByDeviceId(deviceId,type);
        } catch (Exception e) {
            logger.error("查询计划批次信息失败：",e);
        }
        return info;
    }

    @Override
    public List<String> queryAllDeviceId(String type) {
        return repository.getAllDeviceId(type);
    }

    @Override
    public List<EnginePlanInfo> queryAllPlanInfo() {
        return repository.selectAllPlanInfo();
    }

    @Override
    public void deletePlanInfoById(String id) {
        repository.deleteById(id);
    }

    @Override
    public void uploadFinishedFile() {

        logger.debug("检查是否存在未上传的任务结果文件开始。。。。");
        try {
            String rootPath = System.getProperty("user.dir");
            String filePath = rootPath + File.separator + "tmp";
            logger.debug("未完成的结果文件路径：{}", filePath);
            File file = new File(filePath);
            if(!file.exists()){
                return;
            }
            RestTemplate restTemplate = new RestTemplate();
            String url = atuServerConfig.getServerUrl() + atuServerConfig.getTaskCancelResultUrl();
            if(file.isDirectory()){
                File[] listFiles = file.listFiles();
                if(listFiles.length>0){
                    logger.debug("检查存在未上传的任务结果文件个数: "+listFiles.length);
                    for (int i = 0; i < listFiles.length; i++) {
                        File taskFile = listFiles[i];
                        if (taskFile.isDirectory()) {
                            // 如果时文件夹跳过
                            continue;
                        }
                        try {
                            String name = taskFile.getName();
                            String fileName = name.substring(0, name.length() - 4);
                            String[] split = fileName.split("_");
                            String tenantId = split[0];
                            String taskId = split[1];
                            String fileId = null;
                            Map<String,String> paramMap = new HashMap<>();

                            Attachment upload = HttpUtils.upload(taskFile.getAbsolutePath(), tenantId, taskId, FileBusinessTypeEnum.TASK_EXECUTE_RESULT.getCode());
                            if (upload != null && StringUtils.isNotBlank(upload.getId())) {
                                fileId = upload.getId();
                            }
                            boolean delete = taskFile.delete();
                            logger.info("删除 taskFile:{}",delete);
                            paramMap.put("taskId",taskId);
                            paramMap.put("filePath",fileId);
                            if(null!=fileId){
                                ResponseEntity<ResultWrapper> fileResult = restTemplate.postForEntity(url, paramMap, ResultWrapper.class);
                                if(HttpStatus.OK.equals(fileResult.getStatusCode())){
                                    logger.debug("任务结果文件补充上传成功。。。");
                                }
                            }
                        }catch (Exception e2){
                            logger.error("任务结果文件补充上传失败：",e2);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("校验未上传文件失败：",e);
        }
        logger.debug("检查是否存在未上传的任务结果文件结束。。。。");
    }

    @Override
    public void updatePlanInfoSort(String id) {
        repository.updatePlanInfoSort(id);
    }
}
