package com.tuoheng.admin.service.inspectionfile.processing;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.InspectionFileStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.WorkOrderStatusEnum;
import com.tuoheng.admin.enums.code.inspectionfilehandle.InspectionFileProcessingCodeEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.request.inspectionfile.InspectionFileProcessingRresultRequest;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 任务问题处理业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-12-09
 */
@Slf4j
@Service
public class InspectionFileProcessingService {

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private InspectionFileHandleMapper inspectionFileHandleMapper;

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Autowired
    private WorkOrderFileMapper workOrderFileMapper;

    @Transactional
    public JsonResult processing(InspectionFileProcessingRresultRequest request) {
        log.info("进入任务问题处理业务：inspectionFileId:{}", request.getInspectionFileId());

        User user = CurrentUserUtil.getUserInfo();
        String userId = user.getId();
        String tenantId = user.getTenantId();

        JsonResult result = this.check(request);
        if (0 != result.getCode()) {
            log.info("进入任务问题处理业务：校验失败：{}", result.getMsg());
            return result;
        }

        result = this.addInspectionFileHandle(userId, tenantId, request);
        if (0 != result.getCode()) {
            log.info("进入任务问题处理业务：处理失败：{}", result.getMsg());
            return result;
        }

        result = this.updateInspectionFileStatus(userId, request);
        if (0 != result.getCode()) {
            log.info("进入任务问题处理业务：更新任务问题状态失败：{}", result.getMsg());
            return result;
        }

        result = this.updateWorkOrderStatus(userId, request);
        if (0 != result.getCode()) {
            log.info("进入任务问题处理业务：更新工单状态失败：{}", result.getMsg());
            return result;
        }
        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param request
     * @return
     */
    private JsonResult check(InspectionFileProcessingRresultRequest request) {
        // 判断工单id是否为空
        if (StringUtils.isEmpty(request.getWorkOrderId())) {
            return JsonResult.error(InspectionFileProcessingCodeEnum.WORK_ORDER_ID_IS_NULL.getCode(), InspectionFileProcessingCodeEnum.WORK_ORDER_ID_IS_NULL.getMsg());
        }
        // 判断工单是否存在
        WorkOrder workOrder = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrder>()
                                .eq(WorkOrder::getId, request.getWorkOrderId())
                                .eq(WorkOrder::getMark, MarkEnum.VALID.getCode()));
        if (ObjectUtil.isEmpty(workOrder)) {
            return JsonResult.error(InspectionFileProcessingCodeEnum.WORK_ORDER_IS_NOT_EXIST.getCode(), InspectionFileProcessingCodeEnum.WORK_ORDER_IS_NOT_EXIST.getMsg());
        }
        // 判断任务问题id是否为空
        if (StringUtils.isEmpty(request.getInspectionFileId())) {
            return JsonResult.error(InspectionFileProcessingCodeEnum.INSPECTION_FILE_ID_IS_NULL.getCode(), InspectionFileProcessingCodeEnum.INSPECTION_FILE_ID_IS_NULL.getMsg());
        }
        // 判断任务问题是否存在
        InspectionFile inspectionFile = inspectionFileMapper.selectOne(new LambdaQueryWrapper<InspectionFile>()
                .eq(InspectionFile::getId, request.getInspectionFileId())
                .eq(InspectionFile::getMark, MarkEnum.VALID.getCode()));
        if (ObjectUtil.isEmpty(inspectionFile)) {
            log.info("任务问题不存在，inspectionFileId:{}", request.getInspectionFileId());
            return JsonResult.error(InspectionFileProcessingCodeEnum.INSPECTION_FILE_IS_NOT_EXIST.getCode(), InspectionFileProcessingCodeEnum.INSPECTION_FILE_IS_NOT_EXIST.getMsg());
        }
        InspectionFileHandle inspectionFileHandle = inspectionFileHandleMapper.selectOne(new LambdaQueryWrapper<InspectionFileHandle>()
                .eq(InspectionFileHandle::getInspectionFileId, request.getInspectionFileId())
                .eq(InspectionFileHandle::getMark, MarkEnum.VALID.getCode()));
        if (ObjectUtil.isNotEmpty(inspectionFileHandle)) {
            log.info("该问题已处理，不能重复提交，inspectionFileHandleId:{}", inspectionFileHandle.getId());
            return JsonResult.error(InspectionFileProcessingCodeEnum.INSPECTION_FILE_Handle_IS_EXIST.getCode(), InspectionFileProcessingCodeEnum.INSPECTION_FILE_Handle_IS_EXIST.getMsg());
        }
        return JsonResult.success(inspectionFile);
    }

    /**
     * 更新任务问题处理结果
     */
    private JsonResult addInspectionFileHandle(String userId, String tenantId, InspectionFileProcessingRresultRequest request) {
        InspectionFileHandle inspectionFileHandle = new InspectionFileHandle();
        inspectionFileHandle.setTenantId(tenantId);
        inspectionFileHandle.setInspectionFileId(request.getInspectionFileId());
        inspectionFileHandle.setHandlerUser(userId);
        inspectionFileHandle.setHandlerImage(request.getHandlerImage());
        inspectionFileHandle.setHandlerResult(request.getHandlerResult());
        inspectionFileHandle.setHandlerTime(DateUtils.now());
        inspectionFileHandle.setCreateUser(userId);
        inspectionFileHandle.setCreateTime(DateUtils.now());
        Integer rowCount = inspectionFileHandleMapper.insert(inspectionFileHandle);
        if (rowCount <= 0) {
            log.info("任务问题处理失败，inspectionFileId：{}", request.getInspectionFileId());
            return JsonResult.error(InspectionFileProcessingCodeEnum.PROCESSING_IS_FAILED.getCode(), InspectionFileProcessingCodeEnum.PROCESSING_IS_FAILED.getMsg());
        }
        return JsonResult.success();
    }

    /**
     * 更新任务问题状态
     */
    private JsonResult updateInspectionFileStatus(String userId, InspectionFileProcessingRresultRequest request) {
        InspectionFile inspectionFile = new InspectionFile();
        inspectionFile.setId(request.getInspectionFileId());
        inspectionFile.setStatus(InspectionFileStatusEnum.PROCESSED.getCode());
        inspectionFile.setUpdateUser(userId);
        inspectionFile.setUpdateTime(DateUtils.now());
        Integer rowCount = inspectionFileMapper.updateById(inspectionFile);
        if (rowCount <= 0) {
            log.info("更新任务问题状态失败，inspectionFileId：{}", request.getInspectionFileId());
            return JsonResult.error(InspectionFileProcessingCodeEnum.PROCESSING_IS_FAILED.getCode(), InspectionFileProcessingCodeEnum.PROCESSING_IS_FAILED.getMsg());
        }
        return JsonResult.success();
    }

    /**
     * 更新工单状态
     * 当工单关联的任务问题都被处理完时，将工单状态改为完成
     */
    private JsonResult updateWorkOrderStatus(String userId, InspectionFileProcessingRresultRequest request) {
        List<WorkOrderFile> workOrderFileList = workOrderFileMapper.selectList(new LambdaQueryWrapper<WorkOrderFile>()
                .eq(WorkOrderFile::getWorkOrderId, request.getWorkOrderId()));
        List<String> inspectionFileIdList = workOrderFileList.stream().map(o -> o.getInspectionFileId()).collect(Collectors.toList());
        Integer count = inspectionFileHandleMapper.selectCount(new LambdaQueryWrapper<InspectionFileHandle>()
                .in(InspectionFileHandle::getInspectionFileId, inspectionFileIdList));
        if (workOrderFileList.size() > count) {
            return JsonResult.success();
        }
        WorkOrder workOrder = new WorkOrder();
        workOrder.setId(request.getWorkOrderId());
        workOrder.setStatus(WorkOrderStatusEnum.COMPLETED.getCode());
        workOrder.setUpdateUser(userId);
        workOrder.setUpdateTime(DateUtils.now());
        Integer rowCount = workOrderMapper.update(workOrder);
        if (rowCount <= 0) {
            log.info("更新工单状态失败，workOrderId：{}", request.getWorkOrderId());
            return JsonResult.error(InspectionFileProcessingCodeEnum.PROCESSING_IS_FAILED.getCode(), InspectionFileProcessingCodeEnum.PROCESSING_IS_FAILED.getMsg());
        }
        return JsonResult.success();
    }

}
