package cn.newfeifan.mall.sale.service.merchant;

import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.util.json.JsonUtils;
import cn.newfeifan.mall.module.product.service.sku.ProductSkuService;
import cn.newfeifan.mall.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import cn.newfeifan.mall.module.system.dal.dataobject.user.AdminUserDO;
import cn.newfeifan.mall.module.system.dal.mysql.user.AdminUserMapper;
import cn.newfeifan.mall.module.system.mq.message.login.LoginSendMessage;
import cn.newfeifan.mall.module.system.service.user.AdminUserService;
import cn.newfeifan.mall.module.trade.service.order.TradeOrderQueryService;
import cn.newfeifan.mall.sale.controller.admin.merchant.vo.MerchantPageReqVO;
import cn.newfeifan.mall.sale.controller.admin.merchant.vo.MerchantRespVO;
import cn.newfeifan.mall.sale.controller.admin.merchant.vo.MerchantSaveReqVO;
import cn.newfeifan.mall.sale.controller.admin.shop.vo.ShopRespVO;
import cn.newfeifan.mall.sale.controller.admin.shop.vo.ShopSaveReqVO;
import cn.newfeifan.mall.sale.dal.dataobject.merchant.MerchantDO;
import cn.newfeifan.mall.sale.dal.mysql.merchant.MerchantMapper;
import cn.newfeifan.mall.sale.dal.redis.ShopMessage;
import cn.newfeifan.mall.sale.service.shop.ShopService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import cn.newfeifan.mall.framework.common.util.object.BeanUtils;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.module.enums.ErrorCodeConstants.MERCHANT_NOT_EXISTS;
import static cn.newfeifan.mall.module.system.enums.ErrorCodeConstants.USER_MOBILE_EXISTS;

/**
 * 商户 Service 实现类
 *
 * @author 非繁人
 */
@Service
@Validated
public class MerchantServiceImpl implements MerchantService {

    @Resource
    private MerchantMapper merchantMapper;

    @Resource
    private AdminUserMapper userMapper;
    @Resource
    private AdminUserService adminUserService;

    @Resource
    private ShopService shopService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HashMap<String, Long> createMerchant(MerchantSaveReqVO createReqVO) {
        // 插入
        MerchantDO merchant = BeanUtils.toBean(createReqVO, MerchantDO.class);
        merchantMapper.insert(merchant);

        // 创建一个店铺
        Long shopId = shopService.createShop(merchant);
        // 创建商户的时候, 根据手机号, 创建一个新的账号
        // 如果这个手机号已经存在, 则提示该手机号已经存在
        AdminUserDO adminUserDO = userMapper.selectByMobile(merchant.getContactNumber());
        if (adminUserDO != null) {
            throw exception(USER_MOBILE_EXISTS);
        }
        adminUserService.createUserByMobile(merchant.getId(), shopId, merchant.getContactNumber(), merchant.getContact());
        // todo 设置直推人关联关系
        HashMap<String, Long> stringLongHashMap = new HashMap<>();
        stringLongHashMap.put("shopId", shopId);
        stringLongHashMap.put("merId", merchant.getId());
        return stringLongHashMap;
    }

    @Override
    public void updateMerchant(MerchantSaveReqVO updateReqVO) {
        // 校验存在
        validateMerchantExists(updateReqVO.getId());
        // 更新
        MerchantDO updateObj = BeanUtils.toBean(updateReqVO, MerchantDO.class);
        merchantMapper.updateById(updateObj);
    }

    @Override
    public void deleteMerchant(Long id) {
        // 校验存在
        validateMerchantExists(id);
        // 删除
        merchantMapper.deleteById(id);
    }

    private void validateMerchantExists(Long id) {
        if (merchantMapper.selectById(id) == null) {
            throw exception(MERCHANT_NOT_EXISTS);
        }
    }

    @Override
    public MerchantDO getMerchant(Long id) {
        return merchantMapper.selectById(id);
    }

    @Override
    public PageResult<MerchantDO> getMerchantPage(MerchantPageReqVO pageReqVO) {
        return merchantMapper.selectPage(pageReqVO);
    }

    @Resource
    private TradeOrderQueryService tradeOrderQueryService;

    @Resource
    private ProductSkuService productSkuService;

    @Override
    public List<MerchantRespVO> salesVolume(Map<Long, MerchantRespVO> map) {

        for (Long key : map.keySet()) {
            System.out.println("Key = " + key);
            MerchantRespVO value = map.get(key);
            Integer saleVolume = tradeOrderQueryService.getShopSalesVolume(key);
            Integer skuCount = productSkuService.getSkuCount(key);
            value.setSalesVolume(saleVolume);
            value.setSkuCount(skuCount);
            map.put(key, value);
        }
        return new ArrayList<>(map.values());
    }
    @Override
    public void doSendMail(LoginSendMessage message) {

        // 查询用户的商户信息,并且缓存到redis中
        OAuth2AccessTokenDO oAuth2AccessTokenDO = message.getOAuth2AccessTokenDO();
        ShopMessage shopMessage = JsonUtils.parseObject(stringRedisTemplate.opsForValue().get("shop:" + message.getOAuth2AccessTokenDO().getUserId()), ShopMessage.class);
        if (shopMessage != null) {
            // 刷新时间
            stringRedisTemplate.opsForValue().set("shop:" + oAuth2AccessTokenDO.getUserId(), JsonUtils.toJsonString(shopMessage), 3600 * 24, TimeUnit.SECONDS);
        } else {
            // 查询数据库
            AdminUserDO adminUserDO = userMapper.selectById(message.getOAuth2AccessTokenDO().getUserId());
            if (adminUserDO.getShopId() != null) {
                ShopMessage addRedis = new ShopMessage().setShopId(adminUserDO.getShopId()).setMerId(adminUserDO.getMerchantId());
                stringRedisTemplate.opsForValue().set("shop:" + oAuth2AccessTokenDO.getUserId(), JsonUtils.toJsonString(addRedis), 3600 * 24, TimeUnit.SECONDS);
            } else {
                // 获取随机店铺
                List<ShopRespVO> merchantAllShop = shopService.getMerchantAllShop(adminUserDO.getMerchantId());
                oAuth2AccessTokenDO.setMerchantId(adminUserDO.getMerchantId());
                Long shopId = null;
                if (merchantAllShop.size() > 0) {
                    shopId = merchantAllShop.get(0).getId();
                    oAuth2AccessTokenDO.setShopId(shopId);
                }
                //存储redis
                ShopMessage addRedis = new ShopMessage().setShopId(shopId).setMerId(adminUserDO.getMerchantId());
                stringRedisTemplate.opsForValue().set("shop:" + oAuth2AccessTokenDO.getUserId(), JsonUtils.toJsonString(addRedis), 3600 * 24, TimeUnit.SECONDS);
            }
        }
    }
}