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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.module.common.api.dto.FailureVerifyDto;
import com.yeejoin.amos.boot.module.common.api.dto.FailureDetailsDto;
import com.yeejoin.amos.boot.module.common.api.dto.FailureRepairlogDto;
import com.yeejoin.amos.boot.module.common.api.entity.FailureVerify;
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.FailureVerifyMapper;
import com.yeejoin.amos.boot.module.common.api.service.IFailureVerifyService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

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

/**
 * 故障报修验收记录服务实现类
 *
 * @author system_generator
 * @date 2021-08-18
 */
@Service
public class FailureVerifyServiceImpl extends BaseService<FailureVerifyDto, FailureVerify, FailureVerifyMapper> implements IFailureVerifyService {
    @Autowired
    FailureDetailsServiceImpl failureDetailsService;
    @Autowired
    FailureRepairlogServiceImpl failureRepairlogService;

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

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

    @Transactional
    public Object savemodel(FailureVerifyDto model, ReginParams userInfo) throws Exception {

        int condition = Integer.parseInt(model.getCondition());
        model.setVerifyTime(new Date());
        model.setVerifyDepartmentId(userInfo.getDepartment().getSequenceNbr());
        model.setAcceptor(userInfo.getUserModel().getUserName());
        model.setVerifyDepartment(userInfo.getDepartment().getDepartmentName());

        FailureDetailsDto failureDetailsDto = failureDetailsService.queryBySeq(model.getFaultId());

        int verifyResult = 0;
        boolean result = failureDetailsService.checkExcuteTaskAuth(failureDetailsDto.getSequenceNbr(), userInfo);
        if (!result) {
            return new RuntimeException("无权限");
        }
        Boolean repairResult = null;
        //根据验收的结果进行业务操作
        if (condition == (AuditResultEnum.REFUSE.getCode())) {
            verifyResult = AuditResultEnum.REFUSE.getCode();
            repairResult = updateStatus(model, FailureStatuEnum.REFUSE, userInfo, condition);
        }  else if (condition == AuditResultEnum.AGREE.getCode()) {
            verifyResult = AuditResultEnum.AGREE.getCode();
            repairResult = updateStatus(model, FailureStatuEnum.FINISH, userInfo, condition);
        }

        model.setVerifyResult(verifyResult);

            this.createWithModel(model);
            if (!failureDetailsService.excuteTask(failureDetailsDto.getSequenceNbr(), userInfo, condition + "")) {
                throw new Exception("执行流程失败");
            }

        return true;
    }


    /**
     * 修改故障保修单任务状态
     */
    @Transactional
    public Boolean updateStatus(FailureVerifyDto model, FailureStatuEnum status, ReginParams userInfo, int condition) throws Exception {

        FailureDetailsDto failureDetailsDto = failureDetailsService.queryBySeq(model.getFaultId());
        //当前角色部门id为应急指挥科的时候 并且同意时 不修改主表状态 依然为待验收
        //当前角色部门id为维修部门的时候 修改状态
        List<FailureVerify> byfaultId = findByfaultId(failureDetailsDto.getSequenceNbr());

        if (byfaultId.size() != 0) {
            failureDetailsDto.setCurrentStatus(status.getCode());
        }

        failureDetailsDto.setSequenceNbr(model.getFaultId());
        failureDetailsService.updateWithModel(failureDetailsDto);

        String conditionText;

        //添加报修日志
        Long faultId = model.getFaultId();
        Date processTime = model.getVerifyTime();
        String processDepartment = model.getVerifyDepartment();
        Integer processAuditorId = Integer.parseInt(userInfo.getUserModel().getUserId());
        String processAuditorCid = userInfo.getUserModel().getRealName();
        Long auditDepartmentId = (userInfo.getDepartment().getSequenceNbr());
        Boolean repairlog = null;
        if (condition == AuditResultEnum.AGREE.getCode()) {
            conditionText = AuditResultEnum.AGREE.getName();
            repairlog = repairlog(faultId, processAuditorId, auditDepartmentId, processTime, processDepartment, conditionText, processAuditorCid);
        } else if (condition == AuditResultEnum.REFUSE.getCode()) {
            conditionText = AuditResultEnum.REFUSE.getName();
            repairlog = repairlog(faultId,  processAuditorId, auditDepartmentId, processTime, processDepartment, conditionText, processAuditorCid);
        }
        if (!repairlog) {
            throw new Exception("执行流程失败");
        } else {
            return true;
        }


    }

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

    /**
     * 根据FaultId查询
     */
    public List<FailureVerify> findByfaultId(Long faultId) {
        QueryWrapper<FailureVerify> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fault_id", faultId).orderByDesc("verify_time");
        return baseMapper.selectList(queryWrapper);
    }

    public FailureVerify findByFaultId(Long faultId) {
        LambdaQueryWrapper<FailureVerify> wrapper = new LambdaQueryWrapper<FailureVerify>();
        wrapper.eq(FailureVerify::getIsDelete, false);
        wrapper.eq(FailureVerify::getFaultId, faultId);
        wrapper.orderByAsc(FailureVerify::getVerifyTime);
        wrapper.last("LIMIT 1");
        return this.baseMapper.selectOne(wrapper);
    }
}