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

import cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil;
import cn.newfeifan.mall.framework.common.util.json.JsonUtils;
import cn.newfeifan.mall.module.system.controller.admin.user.vo.user.UserRespVO;
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.dal.redis.oauth2.OAuth2AccessTokenRedisDAO;
import cn.newfeifan.mall.module.system.service.permission.RoleService;
import cn.newfeifan.mall.module.system.service.user.AdminUserService;
import cn.newfeifan.mall.sale.controller.admin.merchant.vo.MerchantSaveReqVO;
import cn.newfeifan.mall.sale.controller.admin.shop.vo.ShopPageReqVO;
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.shop.ShopMapper;
import cn.newfeifan.mall.sale.dal.redis.ShopMessage;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import cn.newfeifan.mall.sale.dal.dataobject.shop.ShopDO;
import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;

import java.util.List;
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.NO_BANDING;
import static cn.newfeifan.mall.module.enums.ErrorCodeConstants.SHOP_NOT_EXISTS;

/**
 * 店铺 Service 实现类
 *
 * @author 非繁人
 */
@Service
@Validated
public class ShopServiceImpl implements ShopService {

    @Resource
    private ShopMapper shopMapper;
    @Resource
    private AdminUserMapper userMapper;
    @Resource
    private RoleService roleService;
    @Override
    public Long createShop(ShopSaveReqVO createReqVO) {
        // 插入
        ShopDO shop = BeanUtils.toBean(createReqVO, ShopDO.class);
        shopMapper.insert(shop);
        // 返回
        return shop.getId();
    }

    @Override
    public Long createShop(MerchantDO createReqVO, MerchantSaveReqVO reqVO) {
        ShopSaveReqVO build = ShopSaveReqVO.builder()
                .logoUrl("")
                .status(1)
                .website(createReqVO.getWebsite())
                .name(createReqVO.getName())
                .merchantId(createReqVO.getId())
                .accountName(reqVO.getAccountName())
                .accountNumber(reqVO.getAccountNumber())
                .bankName(reqVO.getBankName())
                .build();
        ShopDO shop = BeanUtils.toBean(build, ShopDO.class);
        shopMapper.insert(shop);
        return shop.getId();
    }

    @Override
    public void updateShop(ShopSaveReqVO updateReqVO) {
        // 校验存在
        validateShopExists(updateReqVO.getId());
        // 更新
        ShopDO updateObj = BeanUtils.toBean(updateReqVO, ShopDO.class);
        shopMapper.updateById(updateObj);
    }

    @Override
    public void deleteShop(Long id) {
        // 校验存在
        validateShopExists(id);
        // 删除
        shopMapper.deleteById(id);
    }

    private void validateShopExists(Long id) {
        if (shopMapper.selectById(id) == null) {
            throw exception(SHOP_NOT_EXISTS);
        }
    }

    @Override
    public ShopDO getShop(Long id) {
        return shopMapper.selectById(id);
    }

    @Override
    public PageResult<ShopDO> getShopPage(ShopPageReqVO pageReqVO) {
        return shopMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ShopRespVO> getMerchantAllShop(Long merId) {
        List<ShopDO> shopDOS = shopMapper.selectList();
        // 筛选
        shopDOS = shopDOS.stream().filter(k -> k.getMerchantId() != null && k.getMerchantId().equals(merId)).collect(Collectors.toList());
        return BeanUtils.toBean(shopDOS, ShopRespVO.class);
    }

    @Resource
    private AdminUserService userService;

    @Override
    public List<UserRespVO> getAllUser(Long id) {

        List<AdminUserDO> userRespVO = userService.getUserByShopId(id);

        return BeanUtils.toBean(userRespVO, UserRespVO.class);
    }

    @Override
    public List<UserRespVO> getAllUser(List<Long> shopIds) {

        List<AdminUserDO> userRespVO = userService.getUserByShopIds(shopIds);

        List<UserRespVO> respVOS = BeanUtils.toBean(userRespVO, UserRespVO.class);
        for (UserRespVO respVO : respVOS) {
            respVO.setRoleName(roleService.getRoleNames(respVO.getId()));
        }
        return  respVOS;
    }


    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private OAuth2AccessTokenRedisDAO oauth2AccessTokenRedisDAO;

    @Override
    public void changeShop(Long loginUserId, Long shopId) {

        AdminUserDO adminUserDO = userMapper.selectById(loginUserId);
        ShopMessage shopMessage = new ShopMessage().setShopId(shopId).setMerId(adminUserDO.getMerchantId());
        // 存储到redis中
        stringRedisTemplate.opsForValue().set("shop:" + loginUserId, JsonUtils.toJsonString(shopMessage), 3600 * 24, TimeUnit.SECONDS);
        // 更新到数据库中
        AdminUserDO updateAdminUser = new AdminUserDO().setShopId(shopId).setId(adminUserDO.getId());
        userMapper.updateById(updateAdminUser);
    }

    @Override
    public ShopMessage getCurrentShop(Long loginUserId) {
        return JsonUtils.parseObject(stringRedisTemplate.opsForValue().get("shop:" + loginUserId), ShopMessage.class);

    }

    @Override
    public List<ShopRespVO> getAllShopByUserId(Long loginUserId) {
        AdminUserDO adminUserDO = userMapper.selectById(loginUserId);
        if (adminUserDO.getMerchantId() == null){
            throw ServiceExceptionUtil.exception(NO_BANDING);
        }
        return getMerchantAllShop(adminUserDO.getMerchantId());
    }

    @Override
    public List<Long> getShopByName(String shopName) {
        return shopMapper.selectShopIds(shopName);
    }

    @Override
    public List<UserRespVO> selectAllList() {
        List<ShopDO> shopDOS = shopMapper.selectList();
        return BeanUtils.toBean(shopDOS, UserRespVO.class);
    }

}