package com.bonus.canteen.core.order.common.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bonus.canteen.core.common.utils.SysUtil;
import com.bonus.canteen.core.common.utils.TenantContextHolder;
import com.bonus.canteen.core.order.android.dto.MacOrderImageSaveDTO;
import com.bonus.canteen.core.order.common.constants.OrderPhotoTypeEnum;
import com.bonus.canteen.core.order.common.mapper.OrderPhotoMapper;
import com.bonus.canteen.core.order.common.model.OrderPhoto;
import com.bonus.canteen.core.order.common.service.OrderPhotoService;
import com.bonus.canteen.core.order.common.vo.OrderWithPhoto;
import com.bonus.canteen.core.order.custom.OrderCustomBusiness;
import com.bonus.canteen.core.order.utils.LeNumUtil;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.houqin.constant.LeConstants;
import com.bonus.common.houqin.oss.OssProperties;
import com.bonus.common.houqin.oss.service.OssTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.lang.invoke.SerializedLambda;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderPhotoServiceImpl implements OrderPhotoService {
   private static final Logger log = LoggerFactory.getLogger(OrderPhotoServiceImpl.class);
   @Autowired
   @Lazy
   private OssProperties ossProperties;
   @Autowired
   @Lazy
   private OssTemplate minioTemplate;
   @Autowired
   @Lazy
   private OrderPhotoMapper orderPhotoMapper;
   @Autowired
   @Lazy
   private OrderCustomBusiness orderCustomBusiness;

   public void macUploadImage(MultipartFile file, String macOrdId) {
      Long merchantId = TenantContextHolder.getTenantId();
      String merchantIdString;
      if (merchantId != null && merchantId != -1L && merchantId != 1L) {
         merchantIdString = String.valueOf(merchantId);
      } else {
         merchantIdString = "unknown";
      }

      String bucketName = this.ossProperties.getBucketName();
      StringBuilder photoPath = new StringBuilder();
      photoPath.append(merchantIdString).append("/").append("payment").append("/").append(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))).append("/").append(file.getOriginalFilename());

      try {
         this.minioTemplate.putObject(bucketName, photoPath.toString(), file.getInputStream());
         OrderPhoto orderPhoto = new OrderPhoto();
         orderPhoto.setMacOrderId(macOrdId);
         orderPhoto.setOrderPhotoUrl("/" + bucketName + "/" + String.valueOf(photoPath));
         orderPhoto.setStatus(LeConstants.COMMON_YES);
         orderPhoto.setOrderPhotoType(OrderPhotoTypeEnum.FACE.getKey());
         this.doInsertOrUpdate(CollUtil.toList(new OrderPhoto[]{orderPhoto}));
      } catch (Exception var8) {
         log.error("上传失败异常:{}", var8.getMessage());
         throw new ServiceException("上传失败 ^_^");
      }
   }
//
//   public void saveOrUpdatePhoto(List<MacOrderImageSaveDTO> saveList) {
//      if (!ObjectUtil.isEmpty(saveList)) {
//         List<OrderPhoto> orderPhotoList = (List)saveList.stream().map((s) -> {
//            OrderPhoto orderPhoto = new OrderPhoto();
//            orderPhoto.setMacOrderId(s.getMacOrderId());
//            orderPhoto.setOrderPhotoUrl(SysUtil.getCutPath(s.getImgUrl()));
//            orderPhoto.setStatus(LeConstants.COMMON_YES);
//            orderPhoto.setOrderPhotoType(s.getImgType());
//            return orderPhoto;
//         }).collect(Collectors.toList());
//         this.doInsertOrUpdate(orderPhotoList);
//      }
//   }
//
//   public void autoClearOrderPaymentPhoto(LocalDateTime datetime, Integer orderPhotoType) {
//      List<OrderPhoto> orderPhotoList = this.orderPhotoMapper.selectList(((LambdaQueryWrapper)((LambdaQueryWrapper)Wrappers.lambdaQuery(OrderPhoto.class).le(OrderPhoto::getCrtime, datetime)).eq(OrderPhoto::getStatus, LeConstants.COMMON_YES)).eq(LeNumUtil.isValidId(orderPhotoType), OrderPhoto::getOrderPhotoType, OrderPhotoTypeEnum.FACE.getKey()));
//      if (!ObjectUtil.isEmpty(orderPhotoList)) {
//         String bucketName = this.ossProperties.getBucketName();
//         Iterator var5 = orderPhotoList.iterator();
//
//         while(var5.hasNext()) {
//            OrderPhoto orderPhoto = (OrderPhoto)var5.next();
//
//            try {
//               String orderPhotoUrl = orderPhoto.getOrderPhotoUrl().replaceFirst("/" + bucketName, "");
//               this.minioTemplate.removeObject(bucketName, orderPhotoUrl);
//            } catch (Exception var8) {
//               log.error("删除异常:{}", var8.getMessage());
//            }
//         }
//
//         List<String> ids = (List)orderPhotoList.stream().map(OrderPhoto::getMacOrderId).collect(Collectors.toList());
//         this.orderPhotoMapper.update((Object)null, (Wrapper)((LambdaUpdateWrapper)((LambdaUpdateWrapper)Wrappers.lambdaUpdate(OrderPhoto.class).set(OrderPhoto::getStatus, LeConstants.COMMON_NO)).in(OrderPhoto::getMacOrderId, ids)).eq(OrderPhoto::getStatus, LeConstants.COMMON_YES));
//      }
//   }

   public List<OrderPhoto> listByMacOrderIds(List<String> macOrderIds) {
      return (ObjectUtil.isEmpty(macOrderIds) ? CollUtil.newArrayList(new OrderPhoto[0])
              : this.orderPhotoMapper.selectList(Wrappers.lambdaQuery(OrderPhoto.class)
              .in(OrderPhoto::getMacOrderId, macOrderIds)));
   }

   public <T extends OrderWithPhoto> void fillOrderPhoto(List<T> orderList) {
      if (!ObjectUtil.isEmpty(orderList)) {
         List<String> macOrderIds = orderList.stream().map(OrderWithPhoto::getMacOrderId).collect(Collectors.toList());
         Map<String, List<OrderPhoto>> orderPhotoGroup = this.listByMacOrderIds(macOrderIds).stream()
                 .collect(Collectors.groupingBy(OrderPhoto::getMacOrderId));
         if (!ObjectUtil.isEmpty(orderPhotoGroup)) {
            Iterator var4 = orderList.iterator();

            while(true) {
               OrderWithPhoto order;
               List orderPhotos;
               do {
                  if (!var4.hasNext()) {
                     return;
                  }

                  order = (OrderWithPhoto)var4.next();
                  orderPhotos = (List)orderPhotoGroup.get(order.getMacOrderId());
               } while(ObjectUtil.isEmpty(orderPhotos));

               Iterator var7 = orderPhotos.iterator();

               while(var7.hasNext()) {
                  OrderPhoto orderPhoto = (OrderPhoto)var7.next();
                  if (OrderPhotoTypeEnum.FACE.getKey().equals(orderPhoto.getOrderPhotoType())) {
                     order.setOrderPhotoUrl(SysUtil.getCutFileUrl(orderPhoto.getOrderPhotoUrl()));
                  } else if (OrderPhotoTypeEnum.DISHES.getKey().equals(orderPhoto.getOrderPhotoType())) {
                     order.setImgUrl(SysUtil.getCutFileUrl(orderPhoto.getOrderPhotoUrl()));
                  }
               }
            }
         }
      }
   }

   protected void doInsertOrUpdate(List<OrderPhoto> orderPhotoList) {
      if (!CollUtil.isEmpty(orderPhotoList)) {
         this.orderPhotoMapper.insertOrUpdate(orderPhotoList);
         this.orderCustomBusiness.android().didSaveOrderPhotoV2(orderPhotoList);
      }
   }
}
