package com.bonus.canteen.core.supermarket.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bonus.canteen.core.common.constant.LeMqConstant;
import com.bonus.canteen.core.customer.utils.DelFlagEnum;
import com.bonus.canteen.core.menu.api.MenuDishesApi;
import com.bonus.canteen.core.menu.constant.MaterialTypeEnum;
import com.bonus.canteen.core.order.mq.MqUtil;
import com.bonus.canteen.core.supermarket.api.SupermarketApi;
import com.bonus.canteen.core.supermarket.dto.*;
import com.bonus.canteen.core.supermarket.mapper.SupermarketProductMapper;
import com.bonus.canteen.core.supermarket.model.SupermarketProduct;
import com.bonus.canteen.core.supermarket.vo.AmountBaseVO;
import com.bonus.canteen.core.supermarket.vo.MqSupermarketProductVO;
import com.bonus.canteen.core.supermarket.vo.SupermarketProductPageVO;
import com.bonus.canteen.core.supermarket.vo.SupermarketUnAddProductListVO;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.houqin.i18n.I18n;
import com.bonus.common.houqin.utils.LeBeanUtil;
import com.bonus.common.houqin.utils.id.Id;
import com.bonus.common.security.utils.SecurityUtils;
import com.github.pagehelper.page.PageMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class SupermarketProductService {
   @Autowired
   @Lazy
   private SupermarketProductMapper supermarketProductMapper;
   @Autowired
   @Lazy
   private MenuDishesApi menuDishesApi;
   @Autowired
   @Lazy
   private SupermarketApi supermarketApi;

   public AmountBaseVO<SupermarketProductPageVO> pageProduct(SupermarketProductPageDTO content) {
      Page<SupermarketProductPageVO> resultPage = new Page(content.getCurrent(), content.getSize());
      if (CharSequenceUtil.isNotBlank(content.getMaterialName())) {
         content.setMaterialName(LeBeanUtil.fieldLikeHandle(content.getMaterialName()));
      }

      List<Long> categoryIdList = this.menuDishesApi.listCategoryChild(content.getCategoryIdList(), MaterialTypeEnum.GOODS.key());
      content.setCategoryIdList(categoryIdList);
      boolean ifSupermarketRelateDrp = this.supermarketApi.ifRelateDrp(content.getSupermarketId());
      if (ifSupermarketRelateDrp) {
         resultPage = this.supermarketProductMapper.pageProductRelate(resultPage, content, 1);
         if (CollUtil.isNotEmpty(resultPage.getRecords())) {
            resultPage.getRecords().forEach(this::packageData);
         }
      } else {
         resultPage = this.supermarketProductMapper.pageProductNoRelate(resultPage, content);
      }

      SupermarketProductPageVO supermarketProductPageVO = new SupermarketProductPageVO();
      if (ifSupermarketRelateDrp) {
         List<SupermarketProductPageVO> list = this.supermarketProductMapper.pageProductRelate(content, 1);
         if (CollUtil.isNotEmpty(list)) {
            list.forEach(this::packageData);
            supermarketProductPageVO.setDrpPrice(((BigDecimal)list.stream().map(SupermarketProductPageVO::getDrpPrice).reduce(BigDecimal.ZERO, BigDecimal::add)).setScale(2, RoundingMode.HALF_UP));
            supermarketProductPageVO.setSellingPrice(((BigDecimal)list.stream().map(SupermarketProductPageVO::getSellingPrice).reduce(BigDecimal.ZERO, BigDecimal::add)).setScale(2, RoundingMode.HALF_UP));
         }
      }

      return (new AmountBaseVO()).setResultPage(resultPage).setTotalLine(supermarketProductPageVO);
   }

   protected void packageData(SupermarketProductPageVO d) {
      if (d.getBuyingPrice() == null) {
         d.setBuyingPrice(BigDecimal.ZERO);
      }

      if (ObjectUtil.isNotEmpty(d.getInventoryNum())) {
         d.setDrpPrice(d.getBuyingPrice().multiply(d.getInventoryNum()));
         d.setSellingPrice(BigDecimal.valueOf((long)d.getSalePrice()).multiply(d.getInventoryNum()));
      } else {
         d.setInventoryNum(BigDecimal.ZERO);
         d.setDrpPrice(BigDecimal.ZERO);
         d.setSellingPrice(BigDecimal.ZERO);
      }

      BigDecimal differences = BigDecimal.valueOf((long)d.getSalePrice()).subtract(d.getBuyingPrice());
      if (d.getSalePrice() != 0) {
         BigDecimal rateOfMargin = differences.divide(BigDecimal.valueOf((long)d.getSalePrice()), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
         d.setRateOfMargin(rateOfMargin);
      } else {
         d.setRateOfMargin(BigDecimal.ZERO);
      }

   }

   public void saveBatchProduct(List<SupermarketProductSaveDTO> content) {
      if (CollUtil.isEmpty(content)) {
         throw new ServiceException(I18n.getMessage("supermarket.not-choose-add-product", new Object[0]));
      } else {
         List<SupermarketProduct> supermarketProductList = new ArrayList();
         Iterator var3 = content.iterator();

         while(var3.hasNext()) {
            SupermarketProductSaveDTO supermarketProductSaveDTO = (SupermarketProductSaveDTO)var3.next();
            SupermarketProduct supermarketProduct = new SupermarketProduct();
            BeanUtil.copyProperties(supermarketProductSaveDTO, supermarketProduct, new String[0]);
            supermarketProduct.setSupermarketDetailId(Id.next());
            supermarketProductList.add(supermarketProduct);
         }

         String userName = SecurityUtils.getUsername();
         this.supermarketProductMapper.saveBatchProduct(supermarketProductList, userName);
         List<MqSupermarketProductVO> mqSupermarketProductVOList = BeanUtil.copyToList(supermarketProductList, MqSupermarketProductVO.class);
         MqUtil.sendDataChange(mqSupermarketProductVOList, LeMqConstant.DataChangeType.ADD, LeMqConstant.Topic.DATA_CHANGE_SUPERMARKET_GOODS);
      }
   }

   public void editProduct(SupermarketProductEditDTO content) {
      if (content.getPrefPrice() > content.getSalePrice()) {
         throw new ServiceException(I18n.getMessage("supermarket.member-price-not-greater-sale-price", new Object[0]));
      } else {
         SupermarketProduct supermarketProduct = new SupermarketProduct();
         BeanUtil.copyProperties(content, supermarketProduct, new String[0]);
         this.supermarketProductMapper.update(supermarketProduct, (Wrapper)Wrappers.lambdaUpdate(SupermarketProduct.class).eq(SupermarketProduct::getSupermarketDetailId, content.getSupermarketDetailId()));
         MqSupermarketProductVO mqSupermarketProductVO = (MqSupermarketProductVO)LeBeanUtil.copyCreateProperties(supermarketProduct, MqSupermarketProductVO.class);
         MqUtil.sendDataChange(mqSupermarketProductVO, LeMqConstant.DataChangeType.UPDATE, LeMqConstant.Topic.DATA_CHANGE_SUPERMARKET_GOODS);
      }
   }

   public void deleteProduct(List<Long> content) {
      this.supermarketProductMapper.delete((Wrapper)Wrappers.lambdaQuery(SupermarketProduct.class).in(SupermarketProduct::getSupermarketDetailId, content));
      MqUtil.sendDataChange(content, LeMqConstant.DataChangeType.REMOVE, LeMqConstant.Topic.DATA_CHANGE_SUPERMARKET_GOODS);
   }

   public List<SupermarketUnAddProductListVO> listUnAddProduct(SupermarketUnAddProductListDTO content) {
      if (CharSequenceUtil.isNotBlank(content.getMaterialName())) {
         content.setMaterialName(LeBeanUtil.fieldLikeHandle(content.getMaterialName()));
      }

      return this.supermarketProductMapper.listUnAddProduct(content, MaterialTypeEnum.GOODS.key(), DelFlagEnum.DEL_FALSE.key());
   }

   public List<SupermarketProductPageVO> exportMaterial(SupermarketProductPageDTO content) {
      SupermarketProductPageVO supermarketProductPageVO = new SupermarketProductPageVO();
      boolean ifSupermarketRelateDrp = this.supermarketApi.ifRelateDrp(content.getSupermarketId());
      PageMethod.startPage(content);
      List<SupermarketProductPageVO> list;
      if (ifSupermarketRelateDrp) {
         list = this.supermarketProductMapper.pageProductRelate(content, 1);
         if (CollUtil.isNotEmpty(list)) {
            list.forEach(this::packageData);
            supermarketProductPageVO.setDrpPrice(((BigDecimal)list.stream().map(SupermarketProductPageVO::getDrpPrice).reduce(BigDecimal.ZERO, BigDecimal::add)).setScale(2, RoundingMode.HALF_UP));
            supermarketProductPageVO.setSellingPrice(((BigDecimal)list.stream().map(SupermarketProductPageVO::getSellingPrice).reduce(BigDecimal.ZERO, BigDecimal::add)).setScale(2, RoundingMode.HALF_UP));
            supermarketProductPageVO.setMaterialName("合计");
            list.add(supermarketProductPageVO);
         }

         return list;
      } else {
         list = this.supermarketProductMapper.pageProductRelate(content, 2);
         list.add(supermarketProductPageVO);
         return list;
      }
   }

   public List<SupermarketUnAddProductListVO> pageUnAddProduct(SupermarketUnAddProductPageDTO content) {
      if (CharSequenceUtil.isNotBlank(content.getMaterialName())) {
         content.setMaterialName(LeBeanUtil.fieldLikeHandle(content.getMaterialName()));
      }

      if (CharSequenceUtil.isNotBlank(content.getBarCode())) {
         content.setBarCode(LeBeanUtil.fieldLikeHandle(content.getBarCode()));
      }

      PageMethod.startPage(content);
      return this.supermarketProductMapper.pageUnAddProduct(content, MaterialTypeEnum.GOODS.key(), DelFlagEnum.DEL_FALSE.key());
   }

}
