package com.inkasso.factoring.system.message.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.inkasso.adapter.exception.ServiceException;
import com.inkasso.adapter.exception.enums.ExceptionEnum;
import com.inkasso.adapter.page.PageFactory;
import com.inkasso.adapter.page.PageResult;
import com.inkasso.adapter.service.KafubaoServiceImpl;
import com.inkasso.adapter.util.BeanUtilsProxy;
import com.inkasso.adapter.web.LoginUserHolder;
import com.inkasso.factoring.system.message.dao.MessageDAO;
import com.inkasso.factoring.system.message.entity.MessageDO;
import com.inkasso.factoring.system.message.model.dto.MessageDTO;
import com.inkasso.factoring.system.message.model.request.AddMessageRequest;
import com.inkasso.factoring.system.message.model.request.QueryMessageRequest;
import com.inkasso.factoring.system.message.service.MessageService;
import com.inkasso.factoring.system.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author 张超
 * @date 2023-08-18
 */
@Service
public class MessageServiceImpl extends
    KafubaoServiceImpl<MessageDAO, MessageDO, MessageDTO> implements MessageService {

  @Autowired
  private UserService userService;

  @Override
  public void addMessage(AddMessageRequest addMessageRequest) {
    MessageDO message = BeanUtilsProxy.copyPropertiesIgnoreNull(addMessageRequest, MessageDO.class);
    this.baseMapper.insert(message);
  }

  @Override
  public void editMessage(Long messageId) {

    LambdaQueryWrapper<MessageDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    Long id = LoginUserHolder.get().getId();
    lambdaQueryWrapper.eq(MessageDO::getId, messageId).eq(MessageDO::getReceiveUserId, id);
    MessageDO message = this.getOne(lambdaQueryWrapper);
    if (message == null) {
      throw new ServiceException(400, ExceptionEnum.SYSTEM_DATE_ERROR);
    }
    /**
     * 更新阅读状态
     */
    message.setReadStatus(true);
    this.updateById(message);
  }


  @Override
  public void batchUpdateMessage() {
    Long userId = LoginUserHolder.get().getId();
    this.baseMapper.batchUpdateStatus(userId);

  }


  @Override
  public MessageDTO getById(Long id) {
    MessageDO message = super.getById(id);
    MessageDTO messageDto = BeanUtilsProxy.copyProperties(message, MessageDTO.class);
    return messageDto;
  }

  @Override
  public void deleteMessage(Long id) {
    //判断该用户是否有该消息
    Long userId = LoginUserHolder.get().getId();
    LambdaQueryWrapper<MessageDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    lambdaQueryWrapper.eq(MessageDO::getReceiveUserId, userId).eq(MessageDO::getId, id);
    MessageDO one = this.getOne(lambdaQueryWrapper);
    if (one == null) {
      throw new ServiceException(ExceptionEnum.SYSTEM_DATE_ERROR);
    }
    this.removeById(id);
  }

  @Override
  public Object queryMessageNum(QueryMessageRequest queryMessageRequest) {
    JSONObject jsonObject = new JSONObject();
    Long userId = LoginUserHolder.get().getId();
    //租户ID
    Long tenantId = LoginUserHolder.get().getTenantId();
    if(tenantId  == null){
      return jsonObject;
    }
    queryMessageRequest.setBusinessType("vehicleLeader_");
    queryMessageRequest.setReceiveUserId(userId);
    queryMessageRequest.setTenantId(tenantId);
    List<MessageDO> messageDOS =  this.baseMapper.findVehicleLeaderMessage(queryMessageRequest);
    if (messageDOS != null && !messageDOS.isEmpty()) {
      Map<String, List<MessageDO>> listMap = messageDOS.stream()
          .collect(Collectors.groupingBy(MessageDO::getBusinessType));
      List<MessageDO> insuranceList = listMap.get("vehicleLeader_insurance");
      List<MessageDO> annualInspectionList = listMap.get("vehicleLeader_annualInspection");
      if (insuranceList != null && !insuranceList.isEmpty()) {
        JSONObject jsonObject1 = new JSONObject();
        int size = insuranceList.size();
        int size1 = insuranceList.stream().filter(m -> m.getDealStatus().compareTo(Boolean.TRUE) == 0)
            .collect(Collectors.toList()).size();
        jsonObject1.put("shallDealNum", size);
        jsonObject1.put("dealMessageNum", size1);
        jsonObject1.put("messageNum", size - size1);
        List<String> batchIds = insuranceList.stream().map(MessageDO::getObjectId)
            .collect(Collectors.toList());
        jsonObject1.put("batchIds", batchIds);
        jsonObject.put("vehicleLeaderAnnualInspection", jsonObject1);
      } else {
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("messageNum", 0);
        jsonObject1.put("dealMessageNum", 0);
        jsonObject1.put("shallDealNum", 0);
        List<String> batchIds = new ArrayList<>();
        jsonObject1.put("batchIds", batchIds);
        jsonObject.put("vehicleLeaderAnnualInspection", jsonObject1);
      }
      if (annualInspectionList != null && !annualInspectionList.isEmpty()) {
        JSONObject jsonObject1 = new JSONObject();
        int size = annualInspectionList.size();
        int size1 = annualInspectionList.stream().filter(m -> m.getDealStatus().compareTo(Boolean.TRUE) == 0)
            .collect(Collectors.toList()).size();
        jsonObject1.put("shallDealNum", size);
        jsonObject1.put("dealMessageNum", size1);
        jsonObject1.put("messageNum", size - size1);
        List<String> batchIds = annualInspectionList.stream().map(MessageDO::getObjectId)
            .collect(Collectors.toList());
        jsonObject1.put("batchIds", batchIds);
        jsonObject.put("vehicleLeaderInsurance", jsonObject1);
      } else {
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("messageNum", 0);
        jsonObject1.put("dealMessageNum", 0);
        jsonObject1.put("shallDealNum", 0);
        List<String> batchIds = new ArrayList<>();
        jsonObject1.put("batchIds", batchIds);
        jsonObject.put("vehicleLeaderInsurance", jsonObject1);
      }
    } else {
      JSONObject jsonObject1 = new JSONObject();
      jsonObject1.put("messageNum", 0);
      jsonObject1.put("dealMessageNum", 0);
      jsonObject1.put("shallDealNum", 0);
      List<String> batchIds = new ArrayList<>();
      jsonObject1.put("batchIds", batchIds);
      jsonObject.put("vehicleLeaderInsurance", jsonObject1);
      jsonObject.put("vehicleLeaderAnnualInspection", jsonObject1);
    }
    return jsonObject;
  }

  @Override
  public PageResult<MessageDTO> pageQueryList(QueryMessageRequest queryMessageRequest) {
    Page<MessageDTO> page = PageFactory.createPage(queryMessageRequest);
    page = this.baseMapper.pageQuery(page,queryMessageRequest);

    return new PageResult(page);
  }
}

