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.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bonus.canteen.core.allocation.api.AllocCanteenApi;
import com.bonus.canteen.core.allocation.canteen.dto.MarketCanteenSaveDTO;
import com.bonus.canteen.core.allocation.constants.QRTypeEnum;
import com.bonus.canteen.core.allocation.util.PayQRCodeUtil;
import com.bonus.canteen.core.common.constant.LeMqConstant;
import com.bonus.canteen.core.common.redis.RedisUtil;
import com.bonus.canteen.core.common.utils.TenantContextHolder;
import com.bonus.canteen.core.customer.utils.DelFlagEnum;
import com.bonus.canteen.core.order.mq.MqUtil;
import com.bonus.canteen.core.supermarket.api.SupermarketAuthApi;
import com.bonus.canteen.core.supermarket.dto.*;
import com.bonus.canteen.core.supermarket.mapper.SupermarketConfigMapper;
import com.bonus.canteen.core.supermarket.mapper.SupermarketInfoMapper;
import com.bonus.canteen.core.supermarket.mapper.SupermarketMemberMapper;
import com.bonus.canteen.core.supermarket.model.SupermarketConfig;
import com.bonus.canteen.core.supermarket.model.SupermarketInfo;
import com.bonus.canteen.core.supermarket.model.SupermarketMember;
import com.bonus.canteen.core.supermarket.vo.*;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.houqin.constant.LeConstants;
import com.bonus.common.houqin.i18n.I18n;
import com.bonus.common.houqin.utils.LeBeanUtil;
import com.bonus.common.houqin.utils.id.Id;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

@Service
public class SupermarketInfoService {
   @Autowired
   @Lazy
   private AllocCanteenApi allocCanteenApi;
   @Autowired
   @Lazy
   private SupermarketConfigMapper supermarketConfigMapper;
   @Autowired
   @Lazy
   private SupermarketInfoMapper supermarketInfoMapper;
   @Autowired
   @Lazy
   private SupermarketMemberMapper supermarketMemberMapper;
   @Autowired
   @Lazy
   private SupermarketAuthApi supermarketAuthApi;
   @Autowired
   @Lazy
   private PayQRCodeUtil payQRCodeUtil;

   public Page<SupermarketInfoPageVO> pageSupermarket(SupermarketInfoPageDTO content) {
      List<Long> areaAuth = this.supermarketAuthApi.listAreaAuth();
      Page<SupermarketInfoPageVO> resultPage = new Page(content.getCurrent(), content.getSize());
      if (CharSequenceUtil.isNotBlank(content.getSupermarketName())) {
         content.setSupermarketName(LeBeanUtil.fieldLikeHandle(content.getSupermarketName()));
      }

      resultPage = this.supermarketInfoMapper.pageSupermarket(resultPage, content, DelFlagEnum.DEL_FALSE.key(), areaAuth);
      List<SupermarketInfoPageVO> records = resultPage.getRecords();
      Iterator<SupermarketInfoPageVO> var5 = records.iterator();

      while(var5.hasNext()) {
         SupermarketInfoPageVO item = (SupermarketInfoPageVO)var5.next();
         item.setDeliveryWayList(Arrays.asList(item.getDeliveryWay().split(",")));
         List<SupermarketConfigPageVO> configList = this.supermarketConfigMapper.listConfig(item.getSupermarketId());
         item.setConfigList(configList);
         List<Integer> psnTypeList = this.supermarketMemberMapper.listPsnType(item.getSupermarketId());
         if (!CollUtil.isEmpty(psnTypeList)) {
            item.setPsnTypeList(psnTypeList);
         }
      }

      return resultPage;
   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public void insertSupermarket(SupermarketInfoAddDTO content) {
      Long checkName = this.supermarketInfoMapper.selectCount(Wrappers.lambdaQuery(SupermarketInfo.class)
              .eq(SupermarketInfo::getSupermarketName, content.getSupermarketName())
              .eq(SupermarketInfo::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
      if (checkName > 0L) {
         throw new ServiceException(I18n.getMessage("supermarket.supermarket-name-is-exit", new Object[0]));
      } else {
         if (ObjectUtil.isNotEmpty(content.getWarehouseId())) {
            Long checkWarehouseId = this.supermarketInfoMapper.selectCount(Wrappers.lambdaQuery(SupermarketInfo.class)
                    .isNotNull(SupermarketInfo::getWarehouseId)
                    .eq(SupermarketInfo::getWarehouseId, content.getWarehouseId())
                    .eq(SupermarketInfo::getDelFlag, DelFlagEnum.DEL_FALSE.key()));
            if (checkWarehouseId > 0L) {
               throw new ServiceException(I18n.getMessage("supermarket.warehouse-is-bind", new Object[0]));
            }
         }

         MarketCanteenSaveDTO marketSaveDTO = new MarketCanteenSaveDTO();
         marketSaveDTO.setCanteenName(content.getSupermarketName());
         marketSaveDTO.setDirector(content.getUserId());
         marketSaveDTO.setContactTel(content.getMobile());
         marketSaveDTO.setAreaId(content.getAreaId());
         Long supermarketId = this.allocCanteenApi.saveMarketCanteen(marketSaveDTO);
         SupermarketInfo supermarketInfo = new SupermarketInfo();
         BeanUtil.copyProperties(content, supermarketInfo, new String[0]);
         supermarketInfo.setSupermarketId(supermarketId);
         supermarketInfo.setDeliveryWay(CollUtil.join(content.getDeliveryWayList(), ","));
         if (LeConstants.COMMON_YES.equals(content.getIfEnablePayCode())) {
            String payCodeUrl = this.payQRCodeUtil.generateQRCode(supermarketInfo.getSupermarketId(), supermarketInfo.getSupermarketName(), QRTypeEnum.SUPERMARKET_COLLECTION);
            supermarketInfo.setPayCodeUrl(payCodeUrl);
         }

         this.supermarketInfoMapper.insert(supermarketInfo);
         List<MqSupermarketConfigDetailVO> configDetailList = new ArrayList();
         List<SupermarketConfigAddDTO> configList = content.getConfigList();
         Iterator var8 = configList.iterator();

         while(var8.hasNext()) {
            SupermarketConfigAddDTO config = (SupermarketConfigAddDTO)var8.next();
            SupermarketConfig supermarketConfig = new SupermarketConfig();
            BeanUtil.copyProperties(config, supermarketConfig, new String[0]);
            supermarketConfig.setSupermarketId(supermarketId);
            supermarketConfig.setWeekId(Id.next());
            this.supermarketConfigMapper.insert(supermarketConfig);
            MqSupermarketConfigDetailVO mqSupermarketConfigDetailVO = (MqSupermarketConfigDetailVO)LeBeanUtil.copyCreateProperties(supermarketConfig, MqSupermarketConfigDetailVO.class);
            configDetailList.add(mqSupermarketConfigDetailVO);
         }

         if (CollUtil.isNotEmpty(content.getPsnTypeList())) {
            var8 = content.getPsnTypeList().iterator();

            while(var8.hasNext()) {
               Integer psnType = (Integer)var8.next();
               SupermarketMember supermarketMember = new SupermarketMember(supermarketId, psnType);
               this.supermarketMemberMapper.insert(supermarketMember);
            }
         }

         MqSupermarketInfoVO mqSupermarketInfoVO = (MqSupermarketInfoVO)LeBeanUtil.copyCreateProperties(supermarketInfo, MqSupermarketInfoVO.class);
         MqUtil.sendDataChange(mqSupermarketInfoVO, LeMqConstant.DataChangeType.ADD, LeMqConstant.Topic.DATA_CHANGE_SUPERMARKET);
         MqSupermarketConfigVO mqSupermarketConfigVO = (MqSupermarketConfigVO)LeBeanUtil.copyCreateProperties(supermarketInfo, MqSupermarketConfigVO.class);
         mqSupermarketConfigVO.setConfigDetailList(configDetailList);
         MqUtil.sendDataChange(mqSupermarketConfigVO, LeMqConstant.DataChangeType.ADD, LeMqConstant.Topic.DATA_CHANGE_SUPERMARKET_RULE);
      }
   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public void editSupermarket(SupermarketInfoEditDTO content) {
      Long checkName = this.supermarketInfoMapper.selectCount(Wrappers.lambdaQuery(SupermarketInfo.class)
              .eq(SupermarketInfo::getSupermarketName, content.getSupermarketName())
              .eq(SupermarketInfo::getDelFlag, DelFlagEnum.DEL_FALSE.key())
              .ne(SupermarketInfo::getSupermarketId, content.getSupermarketId()));
      if (checkName > 0L) {
         throw new ServiceException(I18n.getMessage("supermarket.supermarket-name-is-exit", new Object[0]));
      } else {
         if (ObjectUtil.isNotEmpty(content.getWarehouseId())) {
            Long checkWarehouseId = this.supermarketInfoMapper.selectCount(Wrappers.lambdaQuery(SupermarketInfo.class)
                    .isNotNull(SupermarketInfo::getWarehouseId)
                    .eq(SupermarketInfo::getWarehouseId, content.getWarehouseId())
                    .eq(SupermarketInfo::getDelFlag, DelFlagEnum.DEL_FALSE.key())
                    .ne(SupermarketInfo::getSupermarketId, content.getSupermarketId()));
            if (checkWarehouseId > 0L) {
               throw new ServiceException(I18n.getMessage("supermarket.warehouse-is-bind", new Object[0]));
            }
         }

         MarketCanteenSaveDTO marketSaveDTO = new MarketCanteenSaveDTO();
         marketSaveDTO.setCanteenId(content.getSupermarketId());
         marketSaveDTO.setCanteenName(content.getSupermarketName());
         marketSaveDTO.setDirector(content.getUserId());
         marketSaveDTO.setContactTel(content.getMobile());
         marketSaveDTO.setAreaId(content.getAreaId());
         this.allocCanteenApi.saveMarketCanteen(marketSaveDTO);
         SupermarketInfo supermarketInfo = new SupermarketInfo();
         BeanUtil.copyProperties(content, supermarketInfo, new String[0]);
         supermarketInfo.setDeliveryWay(CollUtil.join(content.getDeliveryWayList(), ","));
         if (LeConstants.COMMON_YES.equals(supermarketInfo.getIfEnablePayCode())) {
            SupermarketInfo checkSupermarket = (SupermarketInfo)this.supermarketInfoMapper.selectOne(Wrappers.lambdaQuery(SupermarketInfo.class)
                    .eq(SupermarketInfo::getSupermarketId, supermarketInfo.getSupermarketId()));
            if (CharSequenceUtil.isBlank(supermarketInfo.getPayCodeUrl()) || !content.getSupermarketName().equals(checkSupermarket.getSupermarketName())) {
               String payCodeUrl = this.payQRCodeUtil.generateQRCode(supermarketInfo.getSupermarketId(), content.getSupermarketName(), QRTypeEnum.SUPERMARKET_COLLECTION);
               supermarketInfo.setPayCodeUrl(payCodeUrl);
            }
         }

         this.supermarketInfoMapper.update(supermarketInfo, Wrappers.lambdaQuery(SupermarketInfo.class)
                 .eq(SupermarketInfo::getSupermarketId, content.getSupermarketId()));
         List<MqSupermarketConfigDetailVO> configDetailList = new ArrayList<>();
         List<SupermarketConfigEditDTO> configList = content.getConfigList();
         Iterator var7 = configList.iterator();

         while(var7.hasNext()) {
            SupermarketConfigEditDTO config = (SupermarketConfigEditDTO)var7.next();
            SupermarketConfig supermarketConfig = new SupermarketConfig();
            BeanUtil.copyProperties(config, supermarketConfig, new String[0]);
            this.supermarketConfigMapper.update(supermarketConfig, Wrappers.lambdaUpdate(SupermarketConfig.class).eq(SupermarketConfig::getWeekId, config.getWeekId()));
            MqSupermarketConfigDetailVO mqSupermarketConfigDetailVO = (MqSupermarketConfigDetailVO)LeBeanUtil.copyCreateProperties(supermarketConfig, MqSupermarketConfigDetailVO.class);
            configDetailList.add(mqSupermarketConfigDetailVO);
         }

         if (CollUtil.isEmpty(content.getPsnTypeList())) {
            this.supermarketMemberMapper.update(null, Wrappers.lambdaUpdate(SupermarketMember.class)
                    .eq(SupermarketMember::getSupermarketId, content.getSupermarketId())
                    .set(SupermarketMember::getPsnType, (Object)null));
         } else {
            this.supermarketMemberMapper.delete(Wrappers.lambdaQuery(SupermarketMember.class).eq(SupermarketMember::getSupermarketId, content.getSupermarketId()));
            var7 = content.getPsnTypeList().iterator();

            while(var7.hasNext()) {
               Integer psnType = (Integer)var7.next();
               SupermarketMember supermarketMember = new SupermarketMember(content.getSupermarketId(), psnType);
               this.supermarketMemberMapper.insert(supermarketMember);
            }
         }

         String supermarketRedis = "yst:merchant-id:supermarket:info:supermarket-id".replace("merchant-id", TenantContextHolder.getTenantId().toString()).replace("supermarket-id", content.getSupermarketId().toString());
         RedisUtil.delete(supermarketRedis);
         MqSupermarketInfoVO mqSupermarketInfoVO = (MqSupermarketInfoVO)LeBeanUtil.copyCreateProperties(supermarketInfo, MqSupermarketInfoVO.class);
         MqUtil.sendDataChange(mqSupermarketInfoVO, LeMqConstant.DataChangeType.UPDATE, LeMqConstant.Topic.DATA_CHANGE_SUPERMARKET);
         MqSupermarketConfigVO mqSupermarketConfigVO = (MqSupermarketConfigVO)LeBeanUtil.copyCreateProperties(supermarketInfo, MqSupermarketConfigVO.class);
         mqSupermarketConfigVO.setConfigDetailList(configDetailList);
         MqUtil.sendDataChange(mqSupermarketConfigVO, LeMqConstant.DataChangeType.UPDATE, LeMqConstant.Topic.DATA_CHANGE_SUPERMARKET_RULE);
      }
   }

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public void deleteSupermarketById(Long content) {
      if (ObjectUtil.isEmpty(content)) {
         throw new ServiceException(I18n.getMessage("supermarket.id-not-empty", new Object[0]));
      } else {
         MarketCanteenSaveDTO marketSaveDTO = new MarketCanteenSaveDTO();
         marketSaveDTO.setCanteenId(content);
         marketSaveDTO.setIfDel(LeConstants.COMMON_YES);
         this.allocCanteenApi.saveMarketCanteen(marketSaveDTO);
         this.supermarketInfoMapper.update(null, Wrappers.lambdaUpdate(SupermarketInfo.class)
                 .eq(SupermarketInfo::getSupermarketId, content).set(SupermarketInfo::getDelFlag, DelFlagEnum.DEL_TRUE.key()));
         this.supermarketMemberMapper.delete(Wrappers.lambdaQuery(SupermarketMember.class).eq(SupermarketMember::getSupermarketId, content));
         String supermarketRedis = "yst:merchant-id:supermarket:info:supermarket-id".replace("merchant-id", TenantContextHolder.getTenantId().toString()).replace("supermarket-id", content.toString());
         RedisUtil.delete(supermarketRedis);
         MqUtil.sendDataChange(content, LeMqConstant.DataChangeType.REMOVE, LeMqConstant.Topic.DATA_CHANGE_SUPERMARKET);
      }
   }

   public List<SupermarketTreeVO> querySupermarketTree() {
      List<Long> areaAuth = this.supermarketAuthApi.listAreaAuth();
      return this.supermarketInfoMapper.querySupermarketTree(areaAuth);
   }

   public Long getWarehouseId(Long supermarketId) {
      if (ObjectUtil.isEmpty(supermarketId)) {
         throw new ServiceException(I18n.getMessage("supermarket.id-not-empty", new Object[0]));
      } else {
         SupermarketInfo supermarketInfo = (SupermarketInfo)this.supermarketInfoMapper.selectOne(Wrappers.lambdaQuery(SupermarketInfo.class)
                 .eq(SupermarketInfo::getSupermarketId, supermarketId)
                 .eq(SupermarketInfo::getDelFlag, DelFlagEnum.DEL_FALSE.key())
                 .select(SupermarketInfo::getWarehouseId));
         if (ObjectUtil.isEmpty(supermarketInfo)) {
            throw new ServiceException(I18n.getMessage("supermarket.not-exist", new Object[0]));
         } else {
            return supermarketInfo.getWarehouseId();
         }
      }
   }
}
