package com.tuoheng.miniprogram.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.SecurityUserUtils;
import com.tuoheng.common.core.utils.StringUtils;
import com.tuoheng.miniprogram.dao.*;
import com.tuoheng.miniprogram.entity.*;
import com.tuoheng.miniprogram.entity.dto.UploadResultDto;
import com.tuoheng.miniprogram.enums.InspectionFileHandleEnum;
import com.tuoheng.miniprogram.enums.MarkEnum;
import com.tuoheng.miniprogram.enums.ServiceExceptionEnum;
import com.tuoheng.miniprogram.service.IInspectionFileHandleService;
import com.tuoheng.miniprogram.utils.CurrentUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @Author ChengWang
 * @Date 2022/11/25
 */
@Service
@Slf4j
public class InspectionFileHandleServiceImpl implements IInspectionFileHandleService {

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private InspectionFileHandleMapper inspectionFileHandleMapper;

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Autowired
    private WorkOrderFileMapper workOrderFileMapper;
    /**
     * 上传结果
     * @param dto
     * @return
     */
    @Override
    public JsonResult uploadResult(UploadResultDto dto) {
        //登录用户信息
        User userInfo = CurrentUserUtil.getUserInfo();
        String username = userInfo.getUsername();
        if(StringUtils.isEmpty(username)){
            return JsonResult.error(InspectionFileHandleEnum.USER_NAME_IS_NULL.getCode(),InspectionFileHandleEnum.USER_NAME_IS_NULL.getMsg());
        }
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getMark, MarkEnum.VALID.getCode())
                .eq(User::getUsername, username));
        if(ObjectUtil.isNull(user)){
            return JsonResult.error(InspectionFileHandleEnum.USER_IS_NOT_EXIST.getCode(),InspectionFileHandleEnum.USER_IS_NOT_EXIST.getMsg());
        }
        if(StringUtils.isEmpty(user.getId())){
            return JsonResult.error(InspectionFileHandleEnum.USER_ID_IS_NULL.getCode(),InspectionFileHandleEnum.USER_ID_IS_NULL.getMsg());
        }
        if(StringUtils.isEmpty(dto.getId())) {
            return JsonResult.error(InspectionFileHandleEnum.INSPECTION_FILE_ID_IS_NULL.getCode(),InspectionFileHandleEnum.INSPECTION_FILE_ID_IS_NULL.getMsg());
        }
        if(StringUtils.isEmpty(user.getTenantId())){
            return JsonResult.error(InspectionFileHandleEnum.TENANT_ID_IS_NULL.getCode(),InspectionFileHandleEnum.TENANT_ID_IS_NULL.getMsg());
        }

        InspectionFileHandle inspectionFileHandleTmp = inspectionFileHandleMapper.selectOne(new LambdaQueryWrapper<InspectionFileHandle>()
                .eq(InspectionFileHandle::getInspectionFileId, dto.getId())
                .eq(InspectionFileHandle::getMark, MarkEnum.VALID.getCode()));
        if (ObjectUtil.isNotEmpty(inspectionFileHandleTmp)) {
            log.info("该问题已处理，不能重复提交，inspectionFileHandleId:{}", inspectionFileHandleTmp.getId());
            return JsonResult.error(InspectionFileHandleEnum.INSPECTION_FILE_HANDLE_IS_EXIST.getCode(), InspectionFileHandleEnum.INSPECTION_FILE_HANDLE_IS_EXIST.getMsg());
        }
        //更新问题处理表
        InspectionFileHandle inspectionFileHandle = new InspectionFileHandle();
        inspectionFileHandle.setInspectionFileId(dto.getId());
        inspectionFileHandle.setTenantId(user.getTenantId());
        inspectionFileHandle.setHandlerImage(dto.getHandlerImage());
        inspectionFileHandle.setHandlerResult(dto.getHandlerResult());
        inspectionFileHandle.setHandlerTime(DateUtils.now());
        inspectionFileHandle.setHandlerUser(user.getId());
        inspectionFileHandle.setCreateUser(user.getId());
        inspectionFileHandle.setCreateTime(DateUtils.now());
        inspectionFileHandle.setMark(1);


        int count = inspectionFileHandleMapper.insert(inspectionFileHandle);
        if(count<=0){
            return JsonResult.error();
        }
        //更新问题表问题状态为已处理
        InspectionFile inspectionFile = inspectionFileMapper.selectById(dto.getId());
        if(ObjectUtil.isNull(inspectionFile)){
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        inspectionFile.setStatus(25);
        inspectionFile.setUpdateTime(DateUtils.now());
        inspectionFile.setUpdateUser(user.getId());
        int result = inspectionFileMapper.updateById(inspectionFile);
        if(result<=0){
            return JsonResult.error();
        }
        //更新工单状态，当前工单关联的任务问题处理完时，将工单状态改为已完成
        if(StringUtils.isEmpty(dto.getWorkOrderId())){
            return JsonResult.error(InspectionFileHandleEnum.WORK_ORDER_ID_NULL.getCode(),InspectionFileHandleEnum.WORK_ORDER_ID_NULL.getMsg());
        }
        List<WorkOrderFile> workOrderFiles = workOrderFileMapper.selectList(Wrappers.<WorkOrderFile>lambdaQuery()
                .eq(WorkOrderFile::getWorkOrderId, dto.getWorkOrderId()));
        if(StringUtils.isEmpty(workOrderFiles)){
            return JsonResult.error(InspectionFileHandleEnum.DATA_IS_NULL.getCode(),InspectionFileHandleEnum.DATA_IS_NULL.getMsg());
        }
        List<String> inspectionFileList = workOrderFiles.stream().map(o -> o.getInspectionFileId()).collect(Collectors.toList());
        Integer inspectionFileHandleCount = inspectionFileHandleMapper.selectCount(new LambdaQueryWrapper<InspectionFileHandle>()
                .in(InspectionFileHandle::getInspectionFileId, inspectionFileList));
        if(workOrderFiles.size()>inspectionFileHandleCount){
            return JsonResult.success();
        }
        WorkOrder workOrder = workOrderMapper.selectById(dto.getWorkOrderId());
        workOrder.setStatus(15);
        workOrder.setUpdateUser(user.getId());
        workOrder.setUpdateTime(DateUtils.now());
        int i = workOrderMapper.updateById(workOrder);
        if(i<=0){
            return JsonResult.error();
        }


        return JsonResult.success();
    }

}
