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

import java.util.Date;
import java.util.List;

import com.yeejoin.amos.boot.module.common.api.dto.FailureAuditDto;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
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.AuditResultEnum;
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;

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

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

    private static String[] MAINTENANCE_STATUS= {"维修完成","维修中"};
    private static String[] PROCESS_RESULT = {"验证通过","验证未通过"};

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

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

    /**
     * 添加维修记录
     */
    public Object savemodel(FailureMaintainDto failureMaintainDto,ReginParams userInfo)   {

        boolean result = failureDetailsService.checkExcuteTaskAuth(failureMaintainDto.getFaultId(), userInfo);
        if (!result){
            return false;
        }
        try {
            failureMaintainDto.setMaintainMan(userInfo.getUserModel().getUserName());
            failureMaintainDto.setMaintainTime(new Date());
            failureMaintainDto.setDepartment(userInfo.getDepartment().getDepartmentName());
            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[1];//维修中
            Integer processAuditorId = Integer.parseInt(failureMaintainDto.getRecUserId());
            String processAuditorCid = userInfo.getUserModel().getUserName();
            repairlog(failureMaintainDto.getFaultId(),failureMaintainDto.getMaintainMan(),processAuditorId,userInfo.getDepartment().getSequenceNbr(),failureMaintainDto.getMaintainTime(),
                    failureMaintainDto.getDepartment(),processResult,processAuditorCid);

            if (ObjectUtils.isNotEmpty(failureMaintainDto.getAttachment())){
                sourceFileServiceImpl.saveSourceFile(failureMaintainDto.getSequenceNbr(),failureMaintainDto.getAttachment());
            }
            failureDetailsService.excuteTask(failureMaintainDto.getFaultId(), userInfo, failureMaintainDto.getCondition());
        }catch (Exception e){
            e.printStackTrace();
            e.printStackTrace();
            logger.info("添加故障维修信息到数据库失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false ;
        }

        return true;
    }



    /**
     * 更新状态维修完成
     */
    public Boolean updateStatus(FailureMaintainDto failureMaintainDto,ReginParams userInfo) {
        try {
        FailureDetailsDto failureDetailsDto = failureDetailsService.queryBySeq(failureMaintainDto.getFaultId());
        failureDetailsDto.setCurrentStatus(FailureStatuEnum.IN_MAINTENANCE.getCode());
        this.updateWithModel(failureMaintainDto);

        //添加报修日志
        String processResult = MAINTENANCE_STATUS[0];//维修完成
        Integer processAuditorId = Integer.parseInt(failureMaintainDto.getRecUserId());
            String processAuditorCid = userInfo.getUserModel().getUserName();
        repairlog(failureMaintainDto.getFaultId(),failureMaintainDto.getMaintainMan(),processAuditorId,userInfo.getDepartment().getSequenceNbr(),failureMaintainDto.getMaintainTime(),
                failureMaintainDto.getDepartment(),processResult,processAuditorCid);

        if (ObjectUtils.isNotEmpty(failureMaintainDto.getAttachment())){
            sourceFileServiceImpl.saveSourceFile(failureMaintainDto.getSequenceNbr(),failureMaintainDto.getAttachment());
        }
        failureDetailsService.excuteTask(failureMaintainDto.getFaultId(), userInfo, failureMaintainDto.getCondition());
    }catch (Exception e){
        e.printStackTrace();
        logger.info("更新故障验收信息到数据库失败");
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return false ;
    }

        return true;
    }

    /**
     *根据审核结果更新维修表
     */
    public Boolean updateModel(FailureMaintainDto failureMaintainDto, Integer status, ReginParams userInfo)   {

        boolean result = failureDetailsService.checkExcuteTaskAuth(failureMaintainDto.getFaultId(), userInfo);
        FailureDetailsDto failureDetailsDto = failureDetailsService.queryBySeq(failureMaintainDto.getFaultId());
        if (result){
            this.updateWithModel(failureMaintainDto);
            //根据status修改状态
            String processResult = new String();
            String condition = new String();
            if (status == AuditResultEnum.AGREE.getCode() && userInfo.getDepartment().getSequenceNbr()
                    == failureDetailsDto.getBizCode()) {//同意状态为已完结
                failureDetailsDto.setCurrentStatus(failureDetailsDto.getCurrentStatus());
                failureDetailsService.updateWithModel(failureDetailsDto);
                processResult =PROCESS_RESULT[0] ;
                condition= AuditResultEnum.AGREE.getName();
            }  else if (status == AuditResultEnum.AGREE.getCode() ) {//同意状态为已完结
                failureDetailsDto.setCurrentStatus(failureDetailsDto.getCurrentStatus());
                failureDetailsService.updateWithModel(failureDetailsDto);
                processResult =PROCESS_RESULT[0] ;
                condition= AuditResultEnum.AGREE.getName();
            }  else {//不同意状态为已拒绝
                failureDetailsDto.setCurrentStatus(FailureStatuEnum.REFUSE.getCode());
                failureDetailsService.updateWithModel(failureDetailsDto);
                processResult = PROCESS_RESULT[1];
                condition = AuditResultEnum.REFUSE.getName();
            }
            //添加报修日志
            Integer processAuditorId = Integer.parseInt(failureMaintainDto.getRecUserId());
            String processAuditorCid = userInfo.getUserModel().getUserName();
            repairlog(failureMaintainDto.getFaultId(),failureMaintainDto.getMaintainMan(),processAuditorId, userInfo.getDepartment().getSequenceNbr(),failureMaintainDto.getMaintainTime(),
                    failureMaintainDto.getDepartment(),processResult,processAuditorCid);
            failureDetailsService.excuteTask(failureMaintainDto.getFaultId(), userInfo, condition);
            return true;
        }
            return false;

    }
   /**
    * 查询当前故障报修单的流程的审批历史节点
    * @param sequenceNbr
    * @return
    */
	public List<Object> getProcessHistoryList(Long sequenceNbr) {
		// TODO Auto-generated method stub
		return null;
	}

    /**
     * 添加报修日志
     */
    @Transactional
    public Boolean repairlog(Long faultId, String processAuditor,Integer processAuditorId,Long departmentId,Date processTime,
                          String processDepartment, String processResult,String processAuditorCid) {
        FailureRepairlogDto failureRepairlogDto = new FailureRepairlogDto();
        failureRepairlogDto.setFaultId(faultId);
        failureRepairlogDto.setProcessAuditor(processAuditor);
        failureRepairlogDto.setProcessAuditorId(processAuditorId);
        failureRepairlogDto.setProcessDepartmentId(departmentId);
        failureRepairlogDto.setProcessTime(processTime);
        failureRepairlogDto.setProcessDepartment(processDepartment);
        failureRepairlogDto.setProcessResult(processResult);
        failureRepairlogDto.setProcessAuditorCid(processAuditorCid);
        failureRepairlogService.createWithModel(failureRepairlogDto);
        if (ObjectUtils.isNotEmpty(failureRepairlogDto)){
            return true;
        }
        return false;
    }
}