package com.hz.pm.api.scheduler.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hz.pm.api.common.model.constant.BizConst;
import com.hz.pm.api.common.model.constant.ProjectDeclareConst;
import com.hz.pm.api.common.model.constant.RegionConst;
import com.hz.pm.api.common.statemachine.util.StateMachineUtil;
import com.hz.pm.api.projectlib.model.enumeration.ProjectStatusEnum;
import com.hz.pm.api.projectlib.model.entity.Project;
import com.hz.pm.api.projectlib.service.IProjectService;
import com.hz.pm.api.provincial.model.res.ProcessCommentRes;
import com.hz.pm.api.provincial.model.res.ProvincialProjectRes;
import com.hz.pm.api.provincial.model.res.SjApiResponse;
import com.hz.pm.api.provincial.service.IJoinReviewProvincialBureauService;
import com.hz.pm.api.scheduler.contants.TaskContant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @Classname CheckProvincialReviewResultTask
 * @Description 去获取省级联审结果任务
 * @Date 2023/3/16 10:12
 * @Author PoffyZhang
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CheckProvincialReviewResultTask {

    private final IJoinReviewProvincialBureauService reviewProvincialBureauService;

    private final IProjectService projectService;
    private final StateMachineUtil stateMachineUtil;

    @Value("${hostname}")
    private String HOST_NAME;

    @Value("${spring.profiles.active}")
    private String active;

    @Scheduled(cron = "0 */1 * * * ?")
    public void statusFlow() throws UnknownHostException {
        if(BizConst.DEV.equals(active)){
            log.info("测试环境 省局 接口 暂时关闭");
            return;
        }
        //
        if (HOST_NAME.equals(InetAddress.getLocalHost().getHostName())) {
            //1. 定时取 省级部门联审中的项目 去取项目
            List<Project> projectList = projectService.list(Wrappers.lambdaQuery(Project.class)
                            .eq(Project::getStage, ProjectStatusEnum.NOT_APPROVED.getCode())
                            .eq(Project::getStatus, ProjectStatusEnum.JOINT_REVIEW_BY_PROVINCIAL_DEPARTMENTS.getCode())
                            .ge(Project::getDeclareAmount, ProjectDeclareConst.Number.DECLARE_AMOUNT_JUDGEMENT)
                            .eq(Project::getAreaCode, RegionConst.RC_HZ)
                            .eq(Project::getNewest,Boolean.TRUE)
                    .orderByAsc(Project::getCreateOn));

            log.info("需要去查询省级联审结果的项目 size:{}",projectList.size());
            if(CollUtil.isEmpty(projectList)){
                log.info("没有正在省级联审中的项目!");
                return;
            }

            //遍历
            for(Project project: projectList){
                try{
                    SjApiResponse apiResponse = reviewProvincialBureauService.processInfo(project.getProjectCode());
                    log.info("项目 【{}】 去获取省局联审结果 :{}",project.getId(),apiResponse);
                    if(Objects.isNull(apiResponse) || !Integer.valueOf(HttpStatus.HTTP_OK).equals(apiResponse.getCode())){
                        log.info("项目 【{}】 去获取省局联审结果失败",project.getId());
                        continue;
                    }
                    ProvincialProjectRes projectRes = JSON.parseObject(JSON.toJSONString(apiResponse.getData()),
                            ProvincialProjectRes.class);

                    if(CollUtil.isNotEmpty(projectRes.getProcessComment())){
                        List<ProcessCommentRes> processComments = projectRes.getProcessComment();
                        log.info("此项目 【{}】 返回了审批信息",projectRes.getProjectId());
                        //取到最后一个审批元素
                        ProcessCommentRes lastProcessComment = processComments.get(processComments.size() - 1);
                        //最后一个 节点 nodeId 是结束 说明已经批完
                        if(StringUtils.isNotBlank(lastProcessComment.getStepName()) &&
                                TaskContant.ProvinceReview.END_STEP.equals(lastProcessComment.getStepName())){
                            //在省级联审 才调状态机 否则 只改变 联审结果
                            if(ProjectStatusEnum.JOINT_REVIEW_BY_PROVINCIAL_DEPARTMENTS.getCode().equals(
                                    project.getStatus())){
                                stateMachineUtil.pass(project);
                            }
                            log.info("已经审批完成 进入下一状态");
                        }
                        project.setUpdateOn(LocalDateTime.now());
                        //保存审核结果
                        project.setSjlsResult(CollUtil.isNotEmpty(projectRes.getProcessComment())
                                ? JSON.toJSONString(projectRes.getProcessComment()) : StringUtils.EMPTY);
                        projectService.updateById(project);
                    }else{
                        log.info("此项目 【{}】 还没有审批信息",projectRes.getProjectId());
                    }
                }catch (Exception e){
                    log.error("项目审核信息获取异常 projectId:【" + project.getId() + "】 异常内容:" + e.getMessage());
                }
            }
        }
    }
}
