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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.czg.account.dto.shopuser.*;
import com.czg.account.entity.ShopInfo;
import com.czg.account.entity.ShopUser;
import com.czg.account.entity.UserInfo;
import com.czg.account.service.AShopUserService;
import com.czg.account.service.ShopInfoService;
import com.czg.account.service.ShopUserService;
import com.czg.account.service.UserInfoService;
import com.czg.excel.ExcelExportUtil;
import com.czg.exception.CzgException;
import com.czg.market.entity.MemberLevelConfig;
import com.czg.market.entity.MkShopCouponRecord;
import com.czg.market.entity.SmsPushEventUser;
import com.czg.market.service.MemberLevelConfigService;
import com.czg.market.service.MkShopCouponRecordService;
import com.czg.market.service.OrderInfoService;
import com.czg.market.service.TbMemberConfigService;
import com.czg.market.vo.MemberConfigVO;
import com.czg.order.entity.OrderInfo;
import com.czg.sa.StpKit;
import com.czg.service.account.mapper.ShopUserMapper;
import com.czg.utils.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;


/**
 * 商户储值会员 服务层实现。
 *
 * @author Administrator
 * @since 2025-02-08
 */
@Slf4j
@Service
public class AShopUserServiceImpl implements AShopUserService {
    @Resource
    private ShopUserService shopUserService;
    @Resource
    private ShopUserMapper shopUserMapper;
    @Resource
    private ShopInfoService shopInfoService;
    @Resource
    private UserInfoService userInfoService;
    @DubboReference
    private OrderInfoService orderInfoService;
    @DubboReference
    private MkShopCouponRecordService couponRecordService;
    @DubboReference
    private MemberLevelConfigService memberLevelConfigService;
    @DubboReference
    private TbMemberConfigService memberConfigService;

    private ShopUser getUserInfo(Long shopUserId) {
        ShopUser shopUser = shopUserService.queryChain().eq(ShopUser::getId, shopUserId).one();
        if (shopUser == null) {
            throw new CzgException("用户信息不存在");
        }
        return shopUser;
    }

    @Override
    public Page<ShopUser> getPage(String key, Integer isVip) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(ShopUser::getMainShopId, StpKit.USER.getHeadShopIdBySession());
        queryWrapper.eq(ShopUser::getIsVip, isVip);
        queryWrapper.and(q -> {
            q.like(ShopUser::getNickName, key).or(r -> {
                r.like(ShopUser::getNickName, key);
            });
        });
        return shopUserService.page(PageUtil.buildPage(), queryWrapper);
    }

    @Override
    public Page<ShopUserDTO> getPage(String key, Integer isVip, BigDecimal amount) {
        Long mainIdByShopId = shopInfoService.getMainIdByShopId(StpKit.USER.getShopId());
        PageHelper.startPage(PageUtil.buildPageHelp());
        PageInfo<ShopUserDTO> shopUsers = new PageInfo<>(shopUserMapper.selectPageByKeyAndIsVip(mainIdByShopId, isVip, key, amount));
//        shopUsers.getList().forEach(shopUserDTO -> {
//            if (StrUtil.isNotBlank(shopUserDTO.getPhone())) {
//                shopUserDTO.setPhone(DesensitizedUtil.mobilePhone(shopUserDTO.getPhone()));
//            }
//            if (StrUtil.isNotBlank(shopUserDTO.getNickName())) {
//                shopUserDTO.setNickName(DesensitizedUtil.chineseName(shopUserDTO.getNickName()));
//            }
//        });
        return PageUtil.convert(shopUsers);
    }

    @Override
    public Page<ShopUser> getPushEventUser(SmsPushEventUser smsPushEventUser) {
        try {
            Long mainShopId = shopInfoService.getMainIdByShopId(smsPushEventUser.getShopId());
            PageHelper.startPage(smsPushEventUser.getPage(), smsPushEventUser.getSize());
            smsPushEventUser.checkIsAll();
            // 调用Mapper层查询
            List<ShopUser> shopUsers = shopUserMapper.selectPushEventUser(mainShopId,
                    smsPushEventUser.getShopId(), smsPushEventUser);
            return PageUtil.convert(new PageInfo<>(shopUsers));
        } catch (Exception e) {
            log.info("获取营销推送任务用户列表失败{},{}", smsPushEventUser, e.getMessage());
            return PageUtil.convert(new PageInfo<>());
        }
    }

    @Override
    public Page<ShopUser> getAcPushEventUser(SmsPushEventUser smsPushEventUser) {
        try {
            Long mainShopId = shopInfoService.getMainIdByShopId(smsPushEventUser.getShopId());
            PageHelper.startPage(smsPushEventUser.getPage(), smsPushEventUser.getSize());
            smsPushEventUser.checkIsAll();
            // 调用Mapper层查询
            List<ShopUser> shopUsers = shopUserMapper.selectAcPushEventUser(mainShopId,
                    smsPushEventUser.getShopId(), smsPushEventUser);
            return PageUtil.convert(new PageInfo<>(shopUsers));
        } catch (Exception e) {
            log.info("获取公众号推送任务用户列表失败{},{}", smsPushEventUser, e.getMessage());
            return PageUtil.convert(new PageInfo<>());
        }
    }

    @Override
    public void exportUserList(String key, Integer isVip, HttpServletResponse response) {
        Long mainIdByShopId = shopInfoService.getMainIdByShopId(StpKit.USER.getShopId());
        ShopInfo shopInfo = shopInfoService.getById(StpKit.USER.getShopId());
        List<ShopUserDTO> dtoList = shopUserMapper.selectPageByKeyAndIsVip(mainIdByShopId, isVip, key, null);

        // 将 dtoList 转换为 ShopUserExportDTO 列表
        List<ShopUserExportDTO> exportList = BeanUtil.copyToList(dtoList, ShopUserExportDTO.class);
        ExcelExportUtil.exportToResponse(exportList, ShopUserExportDTO.class, shopInfo == null ? "店铺用户列表" : shopInfo.getShopName() + "_用户列表", response);
    }

    @Override
    public Boolean editVip(ShopUserVipEditDTO vipEditDTO) {
        ShopUser shopUser = getUserInfo(vipEditDTO.getId());
        if (vipEditDTO.getIsVip() != null && vipEditDTO.getIsVip() == 1) {
            shopUser.setIsVip(vipEditDTO.getIsVip());
            if (vipEditDTO.getMemberLevelId() != null) {
                shopUser.setMemberLevelId(vipEditDTO.getMemberLevelId());
                if (shopUser.getStartTime() == null) {
                    shopUser.setStartTime(LocalDateTime.now());
                }
                shopUser.setEndTime(vipEditDTO.getEndTime());
            }
        } else if (vipEditDTO.getIsVip() != null && vipEditDTO.getIsVip() == 0) {
            shopUser.setIsVip(0);
            shopUser.setStartTime(null);
            shopUser.setEndTime(null);
            shopUser.setMemberLevelId(null);
        }
        return shopUserService.updateById(shopUser, false);
    }


    @Override
    public Boolean updateInfo(Long shopId, ShopUserEditDTO shopUserEditDTO) {
        if (StrUtil.isNotBlank(shopUserEditDTO.getPhone())) {
            long count = shopUserService.count(new QueryWrapper().eq(ShopUser::getMainShopId, shopId).eq(ShopUser::getPhone, shopUserEditDTO.getPhone()).ne(ShopUser::getId, shopUserEditDTO.getId()));
            if (count > 0) {
                throw new CzgException("手机号已存在");
            }
        }
        ShopUser shopUser = getUserInfo(shopUserEditDTO.getId());
        BeanUtil.copyProperties(shopUserEditDTO, shopUser);
        return shopUserService.updateById(shopUser);
    }

    @Override
    public ShopUserSummaryDTO getSummary(Long shopId, Integer isVip) {
        Long mainId = shopInfoService.getMainIdByShopId(shopId);
        return shopUserMapper.selectUserSummary(mainId, isVip);
    }

    @Override
    @Transactional
    public Boolean add(Long shopId, ShopUserAddDTO shopUserAddDTO) {
        UserInfo userInfo = userInfoService.queryChain().eq(UserInfo::getPhone, shopUserAddDTO.getPhone()).one();
        if (userInfo == null) {
            userInfo = BeanUtil.copyProperties(shopUserAddDTO, UserInfo.class);
            userInfoService.save(userInfo);
        }

        ShopUser shopUser = BeanUtil.copyProperties(shopUserAddDTO, ShopUser.class);
        shopUser.setCode(ShopUser.generateCode());
        shopUser.setSourceShopId(shopId);
        shopUser.setUserId(userInfo.getId());
        shopUser.setMainShopId(shopInfoService.getMainIdByShopId(shopId));
        shopUser.setJoinTime(shopUser.getIsVip() != null && shopUser.getIsVip() == 1 ? DateUtil.date().toLocalDateTime() : null);
        try {
            DateUtil.parse(shopUserAddDTO.getBirthDay(), "yyyy-MM-dd");
        } catch (Exception e) {
            shopUser.setBirthDay(null);
        }
        return shopUserService.save(shopUser);
    }

    @Override
    public ShopUser getDetail(Integer id, Integer userId) {
        Long mainId = shopInfoService.getMainIdByShopId(StpKit.USER.getShopId());
        ShopUser shopUser;
        if (id == null) {
            shopUser = shopUserService.getShopUserInfo(StpKit.USER.getShopId(), userId);
        } else {
            shopUser = shopUserService.getById(id);
            if (shopUser == null) {
                throw new CzgException("用户不存在");
            }
        }
        long count = couponRecordService.count(new QueryWrapper()
                .eq(MkShopCouponRecord::getShopUserId, shopUser.getId())
                .eq(MkShopCouponRecord::getStatus, 0)
                .eq(MkShopCouponRecord::getIsDel, 0)
        );
        ShopUserDTO shopUserDTO = BeanUtil.copyProperties(shopUser, ShopUserDTO.class);
        shopUserDTO.setCouponNum(count);
        shopUserDTO.setOrderNumber(orderInfoService.count(new QueryWrapper().eq(OrderInfo::getUserId, userId).eq(OrderInfo::getShopId, StpKit.USER.getShopId(0L)).eq(OrderInfo::getStatus, "done")));
        MemberLevelConfig memberLevelConfig = null;
        if (shopUser.getMemberLevelId() != null) {
            memberLevelConfig = memberLevelConfigService.getById(shopUser.getMemberLevelId());
            shopUserDTO.setMemberLevelName(memberLevelConfig == null ? null : memberLevelConfig.getName());
            if (memberLevelConfig != null) {
                shopUserDTO.setDiscount(memberLevelConfig.getDiscount());

            }

        }

        MemberConfigVO configVO = memberConfigService.detail(StpKit.USER.getShopId());
        shopUserDTO.setIsMemberPrice(configVO == null ? 0 : configVO.getIsMemberPrice());
        MemberLevelConfig config = memberLevelConfigService.getOne(new QueryWrapper().eq(MemberLevelConfig::getShopId, mainId)
                .ge(MemberLevelConfig::getExperienceValue, memberLevelConfig == null ? null : memberLevelConfig.getExperienceValue())
                .ne(MemberLevelConfig::getId, shopUserDTO.getMemberLevelId())
                .limit(1).orderBy(MemberLevelConfig::getExperienceValue, true));
        if (config != null) {
            shopUserDTO.setNextExperience(config.getExperienceValue() - (shopUser.getExperience() == null ? 0 : shopUser.getExperience()));
            shopUserDTO.setNextExperience(shopUserDTO.getNextExperience() < 0 ? 0 : shopUserDTO.getNextExperience());
            shopUserDTO.setNextMemberLevelName(config.getName());
        }
        return shopUserDTO;
    }

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

}
