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

import java.util.ArrayList;
import java.util.Date;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.entity.SourceFile;
import org.apache.commons.lang3.ObjectUtils;


import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import org.typroject.tyboot.core.rdbms.service.BaseService;

import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.workflow.feign.WorkflowFeignService;
import com.yeejoin.amos.boot.module.common.api.dto.FailureDetailsDto;

import com.yeejoin.amos.boot.module.common.api.dto.FailureMaintainDto;

import com.yeejoin.amos.boot.module.common.api.dto.FailureRepairlogDto;

import com.yeejoin.amos.boot.module.common.api.entity.FailureMaintain;

import com.yeejoin.amos.boot.module.common.api.enums.FailureStatuEnum;

import com.yeejoin.amos.boot.module.common.api.mapper.FailureMaintainMapper;

import com.yeejoin.amos.boot.module.common.api.service.IFailureMaintainService;

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2021-08-04
 */

@Service

@Transactional

public class FailureMaintainServiceImpl extends BaseService<FailureMaintainDto, FailureMaintain, FailureMaintainMapper>
        implements IFailureMaintainService {

    @Autowired

    SourceFileServiceImpl sourceFileServiceImpl;

    @Autowired

    FailureDetailsServiceImpl failureDetailsService;

    @Autowired

    FailureRepairlogServiceImpl failureRepairlogService;

    @Autowired
    WorkflowFeignService workflowFeignService;

    @Autowired
    OrgUsrServiceImpl iOrgUsrService;

    private static String RECORE_TYPE = "维修记录";

    private static String[] MAINTENANCE_STATUS = {"维修完成", "维修中"};

    private static int MAINTENANCE_COMPLETE = 0;

    private static int MAINTENANCE_ADD = 1;

    private static String[] PROCESS_RESULT = {"验证通过", "验证未通过"};



    /**
     * 添加维修记录
     */

    public Object savemodel(FailureMaintainDto failureMaintainDto, ReginParams userInfo) throws Exception {

        String condition = failureMaintainDto.getCondition();
        int conditionStatus = Integer.parseInt(condition);
        if (conditionStatus == MAINTENANCE_ADD) {
            boolean result = failureDetailsService.checkExcuteTaskAuth(failureMaintainDto.getFaultId(), userInfo);
            if (!result) {
                throw new RuntimeException("无维修权限");
            }
            failureMaintainDto.setMaintainMan(userInfo.getUserModel().getRealName());
            failureMaintainDto.setMaintainTime(new Date());
            String parentId = iOrgUsrService.getParentId(userInfo.getUserModel().getUserId());
            OrgUsr orgUsr = iOrgUsrService.getById(parentId);
            failureMaintainDto.setDepartment(orgUsr.getBizOrgName());
            failureMaintainDto.setBizId(userInfo.getDepartment().getSequenceNbr());
            failureMaintainDto.setRecoreType(RECORE_TYPE);
            this.createWithModel(failureMaintainDto);
            // 添加完成后修改保修单状态为维修中
            FailureDetailsDto failureDetailsDto = failureDetailsService.queryBySeq(failureMaintainDto.getFaultId());
            failureDetailsDto.setCurrentStatus(FailureStatuEnum.IN_MAINTENANCE.getCode());
            failureDetailsService.updateWithModel(failureDetailsDto);
            // 添加报修日志
            String processResult = MAINTENANCE_STATUS[1];// 维修中
            Integer processAuditorId = Integer.parseInt(failureMaintainDto.getRecUserId());
            String processAuditorName = userInfo.getUserModel().getRealName();
            repairlog(failureMaintainDto.getFaultId(), processAuditorId,
                    userInfo.getDepartment().getSequenceNbr(), failureMaintainDto.getMaintainTime(),
                    failureMaintainDto.getDepartment(), processResult, processAuditorName);
            if (ObjectUtils.isNotEmpty(failureMaintainDto.getAttachment())) {
                sourceFileServiceImpl.saveSourceFile(failureMaintainDto.getSequenceNbr(),
                        failureMaintainDto.getAttachment());
            }
            String nextTaskId = failureDetailsService.checkIsInMaintenance(failureDetailsDto.getSequenceNbr());
            if (nextTaskId == null) {
                if (failureDetailsService.excuteTask(failureMaintainDto.getFaultId(), userInfo, condition)) {
                } else {
                    throw new RuntimeException("执行维修中流程失败");
                }
            } else {
                // 判断下一个节点是不是维修中,如果是则添加当前任务的执行人
                workflowFeignService.pickuptask(nextTaskId);
            }
            return true;
        }
        return this.updateStatus(failureMaintainDto, userInfo);
    }
    /**
     * 更新状态维修完成
     */

    public Boolean updateStatus(FailureMaintainDto failureMaintainDto, ReginParams userInfo) throws Exception {
        String condition = failureMaintainDto.getCondition();
        int conditionStatus = Integer.parseInt(condition);
        if (conditionStatus == MAINTENANCE_COMPLETE) {
            boolean result = failureDetailsService.checkExcuteTaskAuth(failureMaintainDto.getFaultId(), userInfo);
            if (!result) {
                return false;
            }
            failureMaintainDto.setMaintainMan(userInfo.getUserModel().getUserName());
            failureMaintainDto.setMaintainTime(new Date());
            String parentId = iOrgUsrService.getParentId(userInfo.getUserModel().getUserId());
            OrgUsr orgUsr = iOrgUsrService.getById(parentId);
            failureMaintainDto.setDepartment(orgUsr.getBizOrgName());
            failureMaintainDto.setBizId(userInfo.getDepartment().getSequenceNbr());
            failureMaintainDto.setRecoreType(RECORE_TYPE);
            this.createWithModel(failureMaintainDto);
            // 添加完成后修改保修单状态为维修完成
            FailureDetailsDto failureDetailsDto = failureDetailsService.queryBySeq(failureMaintainDto.getFaultId());
            failureDetailsDto.setCurrentStatus(FailureStatuEnum.WAITING_ACCEPTANCE.getCode());
            failureDetailsService.updateWithModel(failureDetailsDto);
            // 添加报修日志
            String processResult = MAINTENANCE_STATUS[0];// 维修完成
            Integer processAuditorId = Integer.parseInt(failureMaintainDto.getRecUserId());
            String processAuditorName = userInfo.getUserModel().getRealName();
            repairlog(failureMaintainDto.getFaultId(),  processAuditorId,
                    userInfo.getDepartment().getSequenceNbr(), failureMaintainDto.getMaintainTime(),
                    failureMaintainDto.getDepartment(), processResult, processAuditorName);
            if (ObjectUtils.isNotEmpty(failureMaintainDto.getAttachment())) {
                sourceFileServiceImpl.saveSourceFile(failureMaintainDto.getSequenceNbr(),
                        failureMaintainDto.getAttachment());
            }
            if (failureDetailsService.excuteTask(failureMaintainDto.getFaultId(), userInfo, condition)) {
            } else {
                throw new RuntimeException("执行维修完成流程失败");
            }
        }
        return true;
    }


    /**
     * 根据FaultId查询
     */
    public List<FailureMaintainDto> findByfaultId(Long faultId) {
        LambdaQueryWrapper<FailureMaintain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FailureMaintain::getFaultId, faultId).orderByDesc(FailureMaintain::getMaintainTime);
        List<FailureMaintain> failureMaintains = baseMapper.selectList(lambdaQueryWrapper);
        List<FailureMaintainDto> failureMaintainDtos = new ArrayList<>();
        for (FailureMaintain failureMaintain : failureMaintains) {
            FailureMaintainDto failureMaintainDto = new FailureMaintainDto();
            BeanUtils.copyProperties(failureMaintain,failureMaintainDto);
            List<SourceFile> attachment = sourceFileServiceImpl.findBySourceId(failureMaintain.getSequenceNbr());
            if (attachment .size()>0){
                failureMaintainDto.setAttachment(attachment);
            }

            failureMaintainDtos.add(failureMaintainDto);
        }
        return failureMaintainDtos;
    }

    /**
     * 查询当前故障报修单的流程的审批历史节点
     *
     * @param sequenceNbr
     * @return
     */

    public List<Object> getProcessHistoryList(Long sequenceNbr) {

        // TODO Auto-generated method stub

        return null;

    }

    /**
     * 添加报修日志
     */
    public Boolean repairlog(Long faultId,  Integer processAuditorId, Long departmentId,
                             Date processTime, String processDepartment, String processResult, String processAuditorName) {

        FailureRepairlogDto failureRepairlogDto = new FailureRepairlogDto();
        failureRepairlogDto.setFaultId(faultId);
        failureRepairlogDto.setProcessAuditorId(processAuditorId);
        failureRepairlogDto.setProcessDepartmentId(departmentId);
        failureRepairlogDto.setProcessTime(processTime);
        failureRepairlogDto.setProcessDepartment(processDepartment);
        failureRepairlogDto.setProcessResult(processResult);
        failureRepairlogDto.setProcessAuditorName(processAuditorName);
        failureRepairlogService.createWithModel(failureRepairlogDto);
        if (ObjectUtils.isNotEmpty(failureRepairlogDto)) {
            return true;
        }
        return false;

    }

}
