package com.czg.service.account.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.czg.account.dto.shopuser.ShopUserAddDTO;
import com.czg.account.dto.shopuser.ShopUserDetailDTO;
import com.czg.account.dto.shopuser.ShopUserMoneyEditDTO;
import com.czg.account.dto.shopuser.ShopUserVipCardDTO;
import com.czg.account.entity.*;
import com.czg.account.service.*;
import com.czg.config.RedisCst;
import com.czg.exception.CzgException;
import com.czg.market.entity.MkPointsUser;
import com.czg.market.entity.MkShopCouponRecord;
import com.czg.market.service.MkPointsUserService;
import com.czg.market.service.MkShopCouponRecordService;
import com.czg.resp.CzgResult;
import com.czg.service.RedisService;
import com.czg.service.account.mapper.ShopConfigMapper;
import com.czg.utils.AssertUtil;
import com.czg.utils.JoinQueryWrapper;
import com.czg.utils.PageUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 商户储值会员 服务层实现。
 *
 * @author Administrator
 * @since 2025-02-08
 */
@Service
public class UShopUserServiceImpl implements UShopUserService {
    @Resource
    private ShopUserService shopUserService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private RedisService redisService;
    @Resource
    private ShopInfoService shopInfoService;
    @Resource
    private ShopExtendService shopExtendService;
    @Resource
    private FreeDineConfigService freeDineConfigService;
    @Resource
    private ShopConfigMapper shopConfigMapper;
    @DubboReference
    private MkShopCouponRecordService couponRecordService;
    @DubboReference
    private MkPointsUserService pointsUserService;

    @Override
    public ShopUserService getService() {
        return shopUserService;
    }

    @Override
    public ShopUser getShopUserInfo(Long shopId, long userId) {
        return shopUserService.getShopUserInfo(shopId, userId);
    }

    @Override
    public Page<ShopUserVipCardDTO> vipCard(long userInfoId) {
        return shopUserService.getMapper().xmlPaginate("selectVipCard", PageUtil.buildPage(), new JoinQueryWrapper().eq(ShopUser::getUserId, userInfoId));
    }

    @Override
    public CzgResult<String> getCode(long userInfoId, long shopId) {
        shopId = shopInfoService.getMainIdByShopId(shopId);
        ShopUser shopUser = shopUserService.queryChain().eq(ShopUser::getMainShopId, shopId).eq(ShopUser::getUserId, userInfoId).one();
        AssertUtil.isNull(shopUser, "会员信息不存在");
        if (shopUser.getIsVip().equals(0)) {
            return CzgResult.failure("加入会员后使用");
        }
        String dynamicCode = generatePaymentCode(String.valueOf(shopId), String.valueOf(userInfoId));
        redisService.set(RedisCst.SHOP_USER_DYNAMIC_CODE + shopUser.getMainShopId() + ":" + dynamicCode, shopUser.getId(), 180);
        return CzgResult.success(dynamicCode);
    }

    @Override
    public boolean join(Long shopId, Long userId, ShopUserAddDTO shopUserAddDTO) {
        return shopUserService.join(shopId, userId, shopUserAddDTO);
    }

    public String generatePaymentCode(String shopId, String platformNumber) {
        // 获取当前毫秒时间戳的后四位
        String date = String.format("%04d", System.currentTimeMillis() % 10000);

        // 获取店铺ID的最后2位数字
        String shopIdLastTwoDigits = String.format("%02d", Integer.parseInt(shopId) % 100);

        // 生成一个6位随机数
        String randomPart = RandomUtil.randomNumbers(6);

        // 拼接生成支付码：毫秒后的四位 + 平台号码 + 店铺ID的最后2位 + 随机数

        return date + platformNumber + shopIdLastTwoDigits + randomPart;
    }

    @Override
    public ShopUserDetailDTO getInfo(Long shopId, long userId) {
        Long mainId = shopInfoService.getMainIdByShopId(shopId);
        ShopUser shopUser = shopUserService.getShopUserInfo(mainId, userId);
        UserInfo userInfo = userInfoService.getById(userId);
        if (userInfo == null) {
            throw new CzgException("用户信息不存在");
        }

        long couponNum = 0;
        if (shopUser == null) {
            shopUser = BeanUtil.copyProperties(userInfo, ShopUser.class);
            shopUser.setMainShopId(mainId);
            shopUser.setSourceShopId(shopId);
            shopUser.setId(null);
            shopUser.setUserId(userId);
            shopUserService.save(shopUser);
//            shopUser = getById(shopUser.getId());
        } else {
            couponNum = couponRecordService.count(new QueryWrapper()
                    .eq(MkShopCouponRecord::getUserId, shopUser.getUserId())
                    .eq(MkShopCouponRecord::getStatus, 0)
                    .eq(MkShopCouponRecord::getIsDel, 0)
            );
        }
        ShopUserDetailDTO shopUserDetailDTO = BeanUtil.copyProperties(shopUser, ShopUserDetailDTO.class);
        shopUserDetailDTO.setCouponNum(couponNum);

        ShopInfo shopInfo = shopInfoService.getById(shopId);
        if (shopInfo != null) {
            shopUserDetailDTO.setShopName(shopInfo.getShopName());
            shopUserDetailDTO.setShopId(shopInfo.getId());

            ShopConfig config = shopConfigMapper.selectOneByQuery(new QueryWrapper().eq(ShopConfig::getId, shopId));
            if (config != null) {
                BeanUtil.copyProperties(config, shopInfo, "id");
            }
            shopUserDetailDTO.setShopInfo(shopInfo);
            List<ShopExtend> shopExtends = shopExtendService.list(new QueryWrapper().eq(ShopExtend::getShopId, shopInfo.getId()));
            shopUserDetailDTO.setShopExtendList(shopExtends);
        }

        shopUserDetailDTO.setFreeDineConfig(freeDineConfigService.getConfig(shopInfoService.getMainIdByShopId(shopId)));
        shopUserDetailDTO.setPayPwd(userInfo.getPayPwd());
        shopUserDetailDTO.setUsePayPwd(userInfo.getUsePayPwd());
        MkPointsUser pointsUser = pointsUserService.getPointsUser(shopId, shopUser.getId(), shopUser.getUserId());
        shopUserDetailDTO.setPointsUser(pointsUser);
        return shopUserDetailDTO;
    }

    @Override
    public Long updateMoney(ShopUserMoneyEditDTO shopUserEditDTO) {
        return shopUserService.updateMoney(shopUserEditDTO);
    }
}
