package shop.alien.storeplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.StoreUserVo;
import shop.alien.mapper.*;
import shop.alien.storeplatform.service.MerchantUserService;
import shop.alien.storeplatform.util.LoginUserUtil;
import shop.alien.util.type.LifeNoticeUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;

/**
 * web端商户用户管理服务实现类
 *
 * @author ssk
 * @since 2025-01-xx
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MerchantUserServiceImpl implements MerchantUserService {

    private final StoreUserMapper storeUserMapper;
    private final StoreInfoMapper storeInfoMapper;
    private final StoreImgMapper storeImgMapper;
    private final TagStoreRelationMapper tagStoreRelationMapper;
    private final LifeNoticeMapper lifeNoticeMapper;
    private final LifeUserOrderMapper lifeUserOrderMapper;
    private final OrderCouponMiddleMapper orderCouponMiddleMapper;
    private final LifeCouponMapper lifeCouponMapper;
    private final LifeDiscountCouponMapper lifeDiscountCouponMapper;
    private final LifeDiscountCouponUserMapper lifeDiscountCouponUserMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    @Override
    public StoreUserVo getMerchantByPhone(String phone) {
        log.info("MerchantUserServiceImpl.getMerchantByPhone - 查询商户用户: phone={}", phone);
        
        // 1. 根据手机号查询商户用户
        LambdaQueryWrapper<StoreUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StoreUser::getPhone, phone);
        StoreUser user = storeUserMapper.selectOne(queryWrapper);
        
        StoreUserVo storeUserVo = new StoreUserVo();
        
        // 2. 如果用户不存在，返回空对象
        if (user == null) {
            log.warn("MerchantUserServiceImpl.getMerchantByPhone - 商户用户不存在: phone={}", phone);
            return storeUserVo;
        }
        
        // 3. 注销冷静期（logout_flag=2，兼容旧数据 status=-1）计算倒计时
        boolean logoutCooling = StoreUser.LOGOUT_FLAG_COOLING == user.getLogoutFlag()
                || (StoreUser.LOGOUT_FLAG_DONE == user.getLogoutFlag() && Integer.valueOf(-1).equals(user.getStatus()));
        if (logoutCooling) {
            try {
                // 将注销时间转换为LocalDateTime
                LocalDateTime logoutDateTime = user.getLogoutTime()
                        .toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime();
                
                // 计算7天后的时间（冷静期）
                LocalDateTime futureDateTime = logoutDateTime.plusDays(7);
                
                // 获取当前时间
                LocalDateTime nowDateTime = LocalDateTime.now();
                
                // 计算时间差
                Duration duration = Duration.between(nowDateTime, futureDateTime);
                
                // 转换为毫秒
                long countdownMillis = duration.toMillis();
                
                storeUserVo.setCountdown(countdownMillis);
                log.info("MerchantUserServiceImpl.getMerchantByPhone - 商户用户注销中，倒计时: {}毫秒", countdownMillis);
            } catch (Exception e) {
                log.error("MerchantUserServiceImpl.getMerchantByPhone - 计算注销倒计时失败: {}", e.getMessage(), e);
                storeUserVo.setCountdown(0L);
            }
        }
        
        // 4. 复制用户基本信息
        BeanUtils.copyProperties(user, storeUserVo);
        
        // 5. 转换金额格式（分转元，保留两位小数）
        if (storeUserVo.getMoney() != null) {
            String moneyStr = new BigDecimal(storeUserVo.getMoney())
                    .divide(new BigDecimal(100), 2, RoundingMode.DOWN)
                    .toString();
            storeUserVo.setMoneyStr(moneyStr);
        }
        
        log.info("MerchantUserServiceImpl.getMerchantByPhone - 查询完成: phone={}, userId={}", 
                phone, user.getId());
        return storeUserVo;
    }

    @Override
    public boolean updateMerchantUserInfo(StoreUser storeUserParam) {
        log.info("MerchantUserServiceImpl.updateMerchantUserInfo - 开始修改商户用户信息: userId={}", 
                storeUserParam.getId());

        if (storeUserParam.getId() == null) {
            log.warn("MerchantUserServiceImpl.updateMerchantUserInfo - 用户ID为空");
            throw new RuntimeException("用户ID不能为空");
        }

        // 构建更新对象（只更新非空字段）
        StoreUser storeUser = new StoreUser();
        storeUser.setId(storeUserParam.getId());

        // 昵称
        if (StringUtils.isNotEmpty(storeUserParam.getNickName())) {
            storeUser.setNickName(storeUserParam.getNickName());
            log.debug("MerchantUserServiceImpl.updateMerchantUserInfo - 更新昵称: {}", storeUserParam.getNickName());
        }

        // 身份证号
        if (StringUtils.isNotEmpty(storeUserParam.getIdCard())) {
            storeUser.setIdCard(storeUserParam.getIdCard());
            log.debug("MerchantUserServiceImpl.updateMerchantUserInfo - 更新身份证号");
        }

        // 姓名
        if (StringUtils.isNotEmpty(storeUserParam.getName())) {
            storeUser.setName(storeUserParam.getName());
            log.debug("MerchantUserServiceImpl.updateMerchantUserInfo - 更新姓名: {}", storeUserParam.getName());
        }

        // 账号简介
        if (StringUtils.isNotEmpty(storeUserParam.getAccountBlurb())) {
            storeUser.setAccountBlurb(storeUserParam.getAccountBlurb());
            log.debug("MerchantUserServiceImpl.updateMerchantUserInfo - 更新账号简介");
        }

        // 头像
        if (StringUtils.isNotEmpty(storeUserParam.getHeadImg())) {
            storeUser.setHeadImg(storeUserParam.getHeadImg());
            log.debug("MerchantUserServiceImpl.updateMerchantUserInfo - 更新头像");
        }

        // 执行更新
        int updateResult = storeUserMapper.updateById(storeUser);
        boolean success = updateResult > 0;

        log.info("MerchantUserServiceImpl.updateMerchantUserInfo - 修改完成: userId={}, success={}", 
                storeUserParam.getId(), success);

        return success;
    }

    @Override
    public Map<String, Object> checkPayPassword(String storeUserId, String password) {
        log.info("MerchantUserServiceImpl.checkPayPassword - 检查支付密码: storeUserId={}, hasPassword={}", 
                storeUserId, password != null);

        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("code", 200);

        // 1. 查询用户信息
        StoreUser storeUser = storeUserMapper.selectById(storeUserId);
        
        // 2. 用户不存在
        if (storeUser == null) {
            log.warn("MerchantUserServiceImpl.checkPayPassword - 用户不存在: storeUserId={}", storeUserId);
            returnMap.put("message", "未查询到用户");
            returnMap.put("data", "false");
            return returnMap;
        }

        // 3. 检查是否设置了支付密码
        if (storeUser.getPayPassword() == null) {
            log.info("MerchantUserServiceImpl.checkPayPassword - 用户未设置支付密码: storeUserId={}", storeUserId);
            returnMap.put("message", "用户未设置支付密码");
            returnMap.put("data", "false");
            return returnMap;
        }

        // 4. 如果提供了密码，验证密码是否正确
        if (password != null) {
            if (!password.equals(storeUser.getPayPassword())) {
                log.warn("MerchantUserServiceImpl.checkPayPassword - 密码错误: storeUserId={}", storeUserId);
                returnMap.put("message", "密码错误");
                returnMap.put("data", "false");
                return returnMap;
            }
            log.info("MerchantUserServiceImpl.checkPayPassword - 密码验证成功: storeUserId={}", storeUserId);
        }

        // 5. 验证通过
        returnMap.put("data", "true");
        returnMap.put("message", "用户已设置支付密码");
        
        log.info("MerchantUserServiceImpl.checkPayPassword - 检查完成: storeUserId={}, result=true", storeUserId);
        return returnMap;
    }

    /**
     * 设置/修改支付密码
     * 
     * @param id          用户ID
     * @param payPassword 支付密码
     * @return 是否设置成功
     */
    @Override
    public boolean setPayPassword(Integer id, String payPassword) {
        log.info("MerchantUserServiceImpl.setPayPassword - 开始设置支付密码: id={}", id);

        // 1. 验证参数
        if (id == null) {
            log.warn("MerchantUserServiceImpl.setPayPassword - 用户ID为空");
            throw new RuntimeException("用户ID不能为空");
        }

        if (StringUtils.isEmpty(payPassword)) {
            log.warn("MerchantUserServiceImpl.setPayPassword - 支付密码为空");
            throw new RuntimeException("支付密码不能为空");
        }

        // 2. 构建更新对象
        StoreUser storeUser = new StoreUser();
        storeUser.setId(id);
        storeUser.setPayPassword(payPassword);

        // 3. 执行更新
        int updateResult = storeUserMapper.updateById(storeUser);
        boolean success = updateResult > 0;

        log.info("MerchantUserServiceImpl.setPayPassword - 设置完成: id={}, success={}", id, success);
        return success;
    }

    /**
     * 添加/修改支付宝账号
     *
     * @param userId        用户ID
     * @param alipayAccount 支付宝账号
     * @return 影响的行数
     */
    @Override
    public Integer addAlipayAccount(Integer userId, String alipayAccount) {
        log.info("MerchantUserServiceImpl.addAlipayAccount - 开始添加支付宝账号: userId={}, alipayAccount={}", 
                userId, alipayAccount);

        // 1. 验证参数
        if (userId == null) {
            log.warn("MerchantUserServiceImpl.addAlipayAccount - 用户ID为空");
            throw new RuntimeException("用户ID不能为空");
        }

        if (StringUtils.isEmpty(alipayAccount)) {
            log.warn("MerchantUserServiceImpl.addAlipayAccount - 支付宝账号为空");
            throw new RuntimeException("支付宝账号不能为空");
        }

        // 2. 构建更新条件
        LambdaQueryWrapper<StoreUser> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(StoreUser::getId, userId);

        // 3. 构建更新对象
        StoreUser storeUser = new StoreUser();
        storeUser.setAlipayAccount(alipayAccount);

        // 4. 执行更新
        int updateResult = storeUserMapper.update(storeUser, updateWrapper);

        log.info("MerchantUserServiceImpl.addAlipayAccount - 添加完成: userId={}, updateResult={}", 
                userId, updateResult);

        return updateResult;
    }

    /**
     * 删除支付宝账号
     * 将 StoreUser 表中的 alipayAccount 字段置空
     *
     * @param userId 用户ID
     * @return 是否删除成功
     */
    @Override
    public boolean deleteAlipayAccount(Integer userId) {
        log.info("MerchantUserServiceImpl.deleteAlipayAccount - 开始删除支付宝账号: userId={}", userId);

        // 1. 参数验证
        if (userId == null) {
            log.warn("MerchantUserServiceImpl.deleteAlipayAccount - 用户ID为空");
            throw new RuntimeException("用户ID不能为空");
        }

        // 2. 查询用户是否存在
        StoreUser storeUser = storeUserMapper.selectById(userId);
        if (storeUser == null) {
            log.warn("MerchantUserServiceImpl.deleteAlipayAccount - 用户不存在: userId={}", userId);
            throw new RuntimeException("用户不存在");
        }

        // 4. 使用 LambdaUpdateWrapper 显式将支付宝账号设置为 null
        LambdaUpdateWrapper<StoreUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(StoreUser::getId, userId)
                .set(StoreUser::getAlipayAccount, null);  // 显式设置为 null

        // 5. 执行更新
        int updateResult = storeUserMapper.update(null, updateWrapper);
        boolean success = updateResult > 0;

        log.info("MerchantUserServiceImpl.deleteAlipayAccount - 删除完成: userId={}, success={}", 
                userId, success);

        return success;
    }

    /**
     * 重置商户到刚注册状态
     * 一键退回：删除店铺申请、解绑店铺、清理相关数据
     *
     * @return 是否重置成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean resetToInitialStatus() {
        try {
            // 1. 获取当前登录用户
            Integer userId = LoginUserUtil.getCurrentUserId();
            StoreUser storeUser = storeUserMapper.selectById(userId);
            
            if (storeUser == null) {
                log.warn("MerchantUserServiceImpl.resetToInitialStatus - 用户不存在: userId={}", userId);
                return false;
            }
            
            Integer storeId = storeUser.getStoreId();
            log.info("MerchantUserServiceImpl.resetToInitialStatus - 开始重置: userId={}, storeId={}", 
                    userId, storeId);
            
            // 2. 如果没有关联店铺，无需重置
            if (storeId == null) {
                log.info("MerchantUserServiceImpl.resetToInitialStatus - 用户未关联店铺，无需重置");
                return true;
            }
            
            // 3. 删除店铺图片（营业执照、合同、经营许可证）
            LambdaQueryWrapper<StoreImg> imgWrapper = new LambdaQueryWrapper<>();
            imgWrapper.eq(StoreImg::getStoreId, storeId)
                    .in(StoreImg::getImgType, 14, 15, 25);  // 14-营业执照, 15-合同, 25-经营许可证
            int deletedImgCount = storeImgMapper.delete(imgWrapper);
            log.info("MerchantUserServiceImpl.resetToInitialStatus - 删除店铺图片: count={}", deletedImgCount);
            
            // 4. 删除店铺标签关系
            LambdaQueryWrapper<TagStoreRelation> tagWrapper = new LambdaQueryWrapper<>();
            tagWrapper.eq(TagStoreRelation::getStoreId, storeId);
            int deletedTagCount = tagStoreRelationMapper.delete(tagWrapper);
            log.info("MerchantUserServiceImpl.resetToInitialStatus - 删除店铺标签: count={}", deletedTagCount);
            
            // 5. 删除店铺信息
            int deletedStoreCount = storeInfoMapper.deleteById(storeId);
            log.info("MerchantUserServiceImpl.resetToInitialStatus - 删除店铺信息: success={}", deletedStoreCount > 0);
            
            // 6. 清理用户关联的通知消息（入驻申请相关）
            if (StringUtils.isNotEmpty(storeUser.getPhone())) {
                String receiverId = "store_" + storeUser.getPhone();
                LambdaQueryWrapper<LifeNotice> noticeWrapper = new LambdaQueryWrapper<>();
                lifeNoticeUtil.applyReceiverQuery(noticeWrapper, receiverId);
                noticeWrapper.eq(LifeNotice::getTitle, "入驻店铺申请");
                int deletedNoticeCount = lifeNoticeMapper.delete(noticeWrapper);
                log.info("MerchantUserServiceImpl.resetToInitialStatus - 删除入驻申请通知: count={}", deletedNoticeCount);
            }
            
            // 7. 查询该店铺的所有订单ID（用于后续删除验券记录）
            LambdaQueryWrapper<LifeUserOrder> orderQueryWrapper = new LambdaQueryWrapper<>();
            orderQueryWrapper.eq(LifeUserOrder::getStoreId, storeId)
                    .select(LifeUserOrder::getId);
            java.util.List<LifeUserOrder> orderList = lifeUserOrderMapper.selectList(orderQueryWrapper);
            java.util.List<String> orderIds = orderList.stream()
                    .map(order -> order.getId().toString())
                    .collect(java.util.stream.Collectors.toList());
            log.info("MerchantUserServiceImpl.resetToInitialStatus - 查询到订单数量: count={}", orderIds.size());
            
            // 8. 删除订单-优惠券中间表数据（验券记录）
            if (!orderIds.isEmpty()) {
                LambdaQueryWrapper<OrderCouponMiddle> orderCouponWrapper = new LambdaQueryWrapper<>();
                orderCouponWrapper.in(OrderCouponMiddle::getOrderId, orderIds);
                int deletedOrderCouponCount = orderCouponMiddleMapper.delete(orderCouponWrapper);
                log.info("MerchantUserServiceImpl.resetToInitialStatus - 删除验券记录: count={}", deletedOrderCouponCount);
            }
            
            // 9. 删除该店铺的所有订单记录
            LambdaQueryWrapper<LifeUserOrder> orderWrapper = new LambdaQueryWrapper<>();
            orderWrapper.eq(LifeUserOrder::getStoreId, storeId);
            int deletedOrderCount = lifeUserOrderMapper.delete(orderWrapper);
            log.info("MerchantUserServiceImpl.resetToInitialStatus - 删除订单记录: count={}", deletedOrderCount);
            
            // 10. 删除该店铺发布的团购券
            LambdaQueryWrapper<LifeCoupon> couponWrapper = new LambdaQueryWrapper<>();
            couponWrapper.eq(LifeCoupon::getStoreId, storeId);
            int deletedCouponCount = lifeCouponMapper.delete(couponWrapper);
            log.info("MerchantUserServiceImpl.resetToInitialStatus - 删除团购券: count={}", deletedCouponCount);
            
            // 10. 删除该店铺发布的代金券
            LambdaQueryWrapper<LifeDiscountCoupon> discountCouponWrapper = new LambdaQueryWrapper<>();
            discountCouponWrapper.eq(LifeDiscountCoupon::getStoreId, storeId);
            int deletedDiscountCouponCount = lifeDiscountCouponMapper.delete(discountCouponWrapper);
            log.info("MerchantUserServiceImpl.resetToInitialStatus - 删除代金券: count={}", deletedDiscountCouponCount);
            
            // 11. 删除用户领取的优惠券（用户是商户本人）
            LambdaQueryWrapper<LifeDiscountCouponUser> couponUserWrapper = new LambdaQueryWrapper<>();
            couponUserWrapper.eq(LifeDiscountCouponUser::getUserId, userId);
            int deletedCouponUserCount = lifeDiscountCouponUserMapper.delete(couponUserWrapper);
            log.info("MerchantUserServiceImpl.resetToInitialStatus - 删除用户优惠券: count={}", deletedCouponUserCount);
            
            // 12. 清理所有通知消息（包括订单、优惠券相关）
            if (StringUtils.isNotEmpty(storeUser.getPhone())) {
                String receiverId = "store_" + storeUser.getPhone();
                LambdaQueryWrapper<LifeNotice> allNoticeWrapper = new LambdaQueryWrapper<>();
                lifeNoticeUtil.applyReceiverQuery(allNoticeWrapper, receiverId);
                int deletedAllNoticeCount = lifeNoticeMapper.delete(allNoticeWrapper);
                log.info("MerchantUserServiceImpl.resetToInitialStatus - 删除所有通知消息: count={}", deletedAllNoticeCount);
            }
            
            // 13. 重置用户的店铺关联和个人信息（使用 LambdaUpdateWrapper 显式设置为 null）
            LambdaUpdateWrapper<StoreUser> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(StoreUser::getId, userId)
                    .set(StoreUser::getStoreId, null)       // 解绑店铺
                    .set(StoreUser::getName, null)          // 清空姓名（入驻时填写的联系人）
                    .set(StoreUser::getIdCard, null)        // 清空身份证（入驻时填写的）
                    .set(StoreUser::getPayPassword, null)   // 清空支付密码
                    .set(StoreUser::getMoney, 0)    // 重置用户余额为0
                    .set(StoreUser::getAlipayAccount, null); // 清空支付宝账号（入驻时填写的）
            
            int updateResult = storeUserMapper.update(null, updateWrapper);
            
            log.info("MerchantUserServiceImpl.resetToInitialStatus - 重置用户信息: success={}", updateResult > 0);
            log.info("MerchantUserServiceImpl.resetToInitialStatus - 重置完成: userId={}, storeId={}", userId, storeId);
            
            return updateResult > 0;
            
        } catch (Exception e) {
            log.error("MerchantUserServiceImpl.resetToInitialStatus - 重置失败: {}", e.getMessage(), e);
            throw new RuntimeException("重置失败：" + e.getMessage(), e);
        }
    }
}


