package com.yeejoin.amos.boot.module.ugp.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.boot.module.ugp.api.Enum.ProblemProcessEnum;
import com.yeejoin.amos.boot.module.ugp.api.Enum.ProblemTypeEnum;
import com.yeejoin.amos.boot.module.ugp.api.entity.Project;
import com.yeejoin.amos.boot.module.ugp.api.entity.QualityProblem;
import com.yeejoin.amos.boot.module.ugp.api.mapper.QualityProblemMapper;
import com.yeejoin.amos.boot.module.ugp.api.service.IQualityProblemService;
import com.yeejoin.amos.boot.module.ugp.api.dto.QualityProblemDto;
import org.apache.lucene.search.similarities.Lambda;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 质量问题表服务实现类
 *
 * @author system_generator
 * @date 2022-09-29
 */
@Service
public class QualityProblemServiceImpl extends BaseService<QualityProblemDto,QualityProblem,QualityProblemMapper> implements IQualityProblemService {

    @Autowired
    QualityProblemMapper qualityProblemMapper;

    @Autowired
    ProblemInitiationServiceImpl problemInitiationService;

    @Autowired
    OrgServiceImpl orgService;

    @Autowired
    ProjectResourceServiceImpl projectResourceService;

    /**
     * 分页查询
     */
    public Page<QualityProblemDto> queryForQualityProblemPage(Page<QualityProblemDto> page)   {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<QualityProblemDto> queryForQualityProblemList()   {
        return this.queryForList("" , false);
    }

    @Override
    public IPage<QualityProblemDto> getItems(String current, String size,QualityProblemDto qualityProblemDto) {
        LocalDateTime now = LocalDateTime.now();
        ZoneId zoneId = ZoneId.systemDefault();
        Set<String> projectIds = new HashSet<>();
        for(Project project:projectResourceService.getProjectList()){
            projectIds.add(String.valueOf(project.getSequenceNbr()));
        }
        List<QualityProblemDto> list = new ArrayList<>();
        IPage<QualityProblemDto> page = new Page<>();
        page.setCurrent(Long.parseLong(current));
        page.setSize(Long.parseLong(size));
        page = qualityProblemMapper.getItems(page,qualityProblemDto,projectIds);
        List<QualityProblemDto> qualityProblemDtoList = page.getRecords();
        for (QualityProblemDto qualityProblemDto1 : qualityProblemDtoList) {
            if(!ValidationUtil.isEmpty(qualityProblemDto1.getLevel())){
                qualityProblemDto1.setLevel(ProblemTypeEnum.map.get(qualityProblemDto1.getLevel()));
            }
            //是否限期整改
            Boolean bool = true;
            if(!ValidationUtil.isEmpty(qualityProblemDto1.getRectifyWithinTime())){
                if(!qualityProblemDto1.getRectifyWithinTime()){
                    bool = false;
                }
            }else {
                if(!ValidationUtil.isEmpty(qualityProblemDto1.getReformLimitDate())){
                    LocalDateTime localDateTime = LocalDateTime.ofInstant(qualityProblemDto1.getReformLimitDate().toInstant(),zoneId);
                    if(now.isAfter(localDateTime)){
                        bool = false;
                    }
                }
            }
            if(bool){
                qualityProblemDto1.setRectifyWithingName("是");
            } else {
                qualityProblemDto1.setRectifyWithingName("否");
            }

            //评审意见
            if(!ValidationUtil.isEmpty(qualityProblemDto1.getReviewStatus())){
                if(!qualityProblemDto1.getReviewStatus()){
                    qualityProblemDto1.setReviewStatusName("存在问题");
                }else {
                    qualityProblemDto1.setReviewStatusName("不存在问题");
                }
            }

            if(!ValidationUtil.isEmpty(qualityProblemDto1.getChargerPersonId())){
                if(!ValidationUtil.isEmpty(orgService.getOrgUsrById(qualityProblemDto1.getChargerPersonId()))){
                    qualityProblemDto1.setChargerPersonName(orgService.getOrgUsrById(qualityProblemDto1.getChargerPersonId()).getBizOrgName());
                }
            }
            if(!ValidationUtil.isEmpty(qualityProblemDto1.getInspectorId())){
                if(!ValidationUtil.isEmpty(orgService.getOrgUsrById(qualityProblemDto1.getInspectorId()))){
                    qualityProblemDto1.setInspectorName(orgService.getOrgUsrById(qualityProblemDto1.getInspectorId()).getBizOrgName());
                }
            }
            if (!ValidationUtil.isEmpty(qualityProblemDto1.getVerifyUnitId())) {
                if(!ValidationUtil.isEmpty(orgService.getOrgUsrById(qualityProblemDto1.getVerifyUnitId()))){
                    qualityProblemDto1.setVerifyUnitName(orgService.getOrgUsrById(qualityProblemDto1.getVerifyUnitId()).getBizOrgName());
                }
            }
            list.add(qualityProblemDto1);
        }
        page.setRecords(list);
        return page;
    }

    public String updateItem(QualityProblemDto qualityProblem, Long sequenceNbr){
        QualityProblem quality = this.getById(sequenceNbr);
        if(ProblemProcessEnum.确定问题.getName().equals(quality.getStatus())) {
            //监检机构确定问题
            quality.setLevel(qualityProblem.getLevel());
            quality.setReformLimitDate(qualityProblem.getReformLimitDate());
            if(ProblemTypeEnum.一般问题.getCode().equals(quality.getLevel())){
                //流程执行一次
                problemInitiationService.execute(quality.getInstanceId(),quality,"1");
            }
            if(ProblemTypeEnum.重大问题.getCode().equals(quality.getLevel())){
                //流程执行两次
                problemInitiationService.execute(quality.getInstanceId(),quality,"0");
                problemInitiationService.execute(quality.getInstanceId(),quality,"1");
            }
        }else if(ProblemProcessEnum.编制处理方案.getName().equals(quality.getStatus())) {
            //编制处理方案
            quality.setSolution(qualityProblem.getSolution());
            quality.setSolutionDesc(qualityProblem.getSolutionDesc());
            //执行一次
            problemInitiationService.execute(quality.getInstanceId(),quality,"1");
        }else if (ProblemProcessEnum.审查处理方案.getName().equals(quality.getStatus())){
            quality.setHandingOpinion(qualityProblem.getHandingOpinion());
            quality.setHandingOpinionDesc(qualityProblem.getHandingOpinionDesc());
            //执行一次
            problemInitiationService.execute(quality.getInstanceId(),quality,"1");
        }else if(ProblemProcessEnum.提交整改书.getName().equals(quality.getStatus())) {
            //上传整改书
            quality.setReformDoc(qualityProblem.getReformDoc());
            quality.setReformDesc(qualityProblem.getReformDesc());
            quality.setRectifyWithinTime(quality.getReformLimitDate().after(new Date()));
            //审核通过
            if (quality.getRectifyWithinTime()) {
                //执行流程 option=1
                problemInitiationService.execute(quality.getInstanceId(),quality,"1");
            } else {
                //执行两次流程 option=2
                problemInitiationService.execute(quality.getInstanceId(),quality,"0");
                problemInitiationService.execute(quality.getInstanceId(),quality,"1");
            }
        }else if(ProblemProcessEnum.问题分类.getName().equals(quality.getStatus())) {
            quality.setHandingOpinion(qualityProblem.getHandingOpinion());
            quality.setHandingOpinionDesc(qualityProblem.getHandingOpinionDesc());
            quality.setProblemType(qualityProblem.getProblemType());
            //执行两次
            //获取ProblemType状态
            if(quality.getProblemType()){
                //拿到qualityProblem更新到数据库
                quality.setReformLimitDate(qualityProblem.getDateTime());
                problemInitiationService.execute(quality.getInstanceId(),quality,"0");

            }else {
                problemInitiationService.execute(quality.getInstanceId(),quality,"1");
            }
        }else if(ProblemProcessEnum.审查整改过程.getName().equals(quality.getStatus())) {
            quality.setReviewStatus(qualityProblem.getReviewStatus());
            if(quality.getReviewStatus()){
                if(ProblemTypeEnum.一般问题.getName().equals(quality.getLevel())){
                    //执行一次
                    problemInitiationService.execute(quality.getInstanceId(),quality,"1");
                }else {
                    //执行两次
                    problemInitiationService.execute(quality.getInstanceId(),quality,"2");
                    problemInitiationService.execute(quality.getInstanceId(),quality,"1");
                }
            }else {
                problemInitiationService.execute(quality.getInstanceId(),quality,"0");

            }
        }
//        else if (ProblemProcessEnum.超期整改发送短信.getName().equals(quality.getStatus())) {
////            problemInitiationService.execute(quality.getInstanceId(),quality,"1");
////        }
        return "0k";
    }

    @Override
    public QualityProblemDto getInfoBySequenceNbr(String sequenceNbr){
        QualityProblemDto qualityProblemDto = qualityProblemMapper.getInfoBySequenceNbr(sequenceNbr);
        qualityProblemDto.setSolutionList(JSON.parseArray(qualityProblemDto.getSolution()));
        qualityProblemDto.setReformDocList(JSON.parseArray(qualityProblemDto.getReformDoc()));
        qualityProblemDto.setHandingOpinionList(JSON.parseArray(qualityProblemDto.getHandingOpinion()));
        qualityProblemDto.setReviewStatusString(String.valueOf(qualityProblemDto.getReviewStatus()));
        return qualityProblemDto;
    }


    public List<Map<String,String>> qualityProblemStatistics() {
        Set<String> projectIds = new HashSet<>();
        for(Project project:projectResourceService.getProjectList()){
            projectIds.add(String.valueOf(project.getSequenceNbr()));
        }
        qualityProblemMapper.getItems(new Page<>(1,2),new QualityProblemDto(),projectIds);
        return qualityProblemMapper.qualityProblemStatistics(projectIds);
    }
}