package com.wzj.soopin.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzj.soopin.order.domain.entity.Order;
import com.wzj.soopin.order.domain.entity.VerificationCodes;
import com.wzj.soopin.order.domain.vo.ManagerOrderDetailVO;
import com.wzj.soopin.order.emum.OrderStatusEnum;
import com.wzj.soopin.order.mapper.OrderMapper;
import com.wzj.soopin.order.mapper.VerificationCodesMapper;
import com.wzj.soopin.order.mapper.VerificationLogsMapper;
import com.wzj.soopin.order.service.OrderService;
import com.wzj.soopin.order.service.VerificationCodeService;
import com.wzj.soopin.order.utils.QrCodeGenerator;
import com.wzj.soopin.order.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.enums.CodePrefix;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author fxh
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class VerificationCodeServiceImpl  extends ServiceImpl<VerificationCodesMapper, VerificationCodes> implements VerificationCodeService{



    private final VerificationCodesMapper codeMapper;
    private final OrderMapper orderMapper;
    private final QrCodeGenerator qrCodeGenerator;
    private final VerificationLogsMapper logMapper;

    private final OrderService orderService;

    /**
     * 生成核销码并关联订单
     *
     * @return
     */
    @Override
    public R generateVerificationCode(Long orderId) {
        //  校验订单状态
        Order order = orderMapper.selectById(orderId);
        if (order == null || !Objects.equals(order.getStatus(), OrderStatusEnum.VERIFY.getValue())) {
           return R.fail("订单状态异常");
        }

        //  生成唯一核销码
        String codeValue = generateUniqueCode();

        order.setCode(codeValue);

        // 核销码过期时间（7天后过期）
        LocalDateTime expireTime = LocalDateTime.now().plusDays(7);

        //  保存核销码到数据库
        VerificationCodes code = new VerificationCodes();
        code.setMemberId(order.getMemberId());
        code.setMemberName(order.getMemberUsername());
        code.setCode(codeValue);
        code.setOrderId(orderId);
        code.setExpireTime(expireTime);
        code.setCreateTime(LocalDateTime.now());
        // 未使用状态
        code.setStatus(0);
        int insertResult = codeMapper.insert(code);

        if (insertResult != 1) {
            return R.fail("核销码生成失败");
        }

//        // 构建保存路径
//        String filePath = "qrcode/" + orderId + ".png";
//        String qrCodeUrl = qrCodeGenerator.generateQrCode(
//            "核销码:" + codeValue + ",订单ID:" + orderId,
//            200,
//            200,
//            filePath
//        );
//        // 打印生成后的二维码URL
//        log.info("生成的二维码URL: {}", qrCodeUrl);
//        if (qrCodeUrl == null) {
//            log.error("二维码生成失败");
//        }

//        // 将二维码URL保存到订单表中
//        order.setCodeUrl(qrCodeUrl);
        orderMapper.updateById(order);
        return R.ok("核销码生成成功",  code);
    }

    /**
     * 核销订单
     * @param code
     */
    @Override
    public Order scan(String code) {
        // 查询核销码
        // 参数校验
        if (StringUtils.isBlank(code)  ) {
            throw new IllegalArgumentException("参数不能为空");
        }

        // 查询核销码
        VerificationCodes verificationCodes = codeMapper.selectOne(
            new LambdaQueryWrapper<VerificationCodes>().eq(VerificationCodes::getCode, code)
        );
        if (verificationCodes == null) {
            throw new IllegalArgumentException("核销码不存在");
        }

        // 检查核销码状态
        if (verificationCodes.getStatus() == 1) {
            throw new IllegalArgumentException("核销码已使用");
        }

        if (verificationCodes.getStatus() == 2) {
            throw new IllegalArgumentException("核销码已过期");
        }
        // 检查核销码是否过期
        if (LocalDateTime.now().isAfter(verificationCodes.getExpireTime())) {
            // 更新状态为已过期
            verificationCodes.setStatus(3);
            codeMapper.updateById(verificationCodes);
            throw new IllegalArgumentException("核销码已过期");
        }
        // 检查订单状态
        Order order = orderMapper.selectById(verificationCodes.getOrderId());
        if (order == null || !Objects.equals(order.getStatus(), OrderStatusEnum.VERIFY.getValue())) {
            throw new IllegalArgumentException("订单状态异常，无法核销");
        }



        if (verificationCodes.getStatus() == 1 || verificationCodes.getVerificationTime() != null) {
            throw new IllegalArgumentException("该订单已被核销，核销时间：" + verificationCodes.getVerificationTime());
        }
        return order;
    }

    @Override
    public void  verifyCode(String  code,String tenantId) {

        // 参数校验
        if (StringUtils.isBlank(code) || tenantId == null) {
            throw new IllegalArgumentException("参数不能为空");
        }

        // 查询核销码
        VerificationCodes verificationCodes = codeMapper.selectOne(
            new LambdaQueryWrapper<VerificationCodes>().eq(VerificationCodes::getCode, code)
        );
        if (verificationCodes == null) {
            throw new IllegalArgumentException("核销码不存在");
        }

        // 检查核销码状态
        if (verificationCodes.getStatus() == 1) {
            throw new IllegalArgumentException("核销码已使用");
        }

        if (verificationCodes.getStatus() == 2) {
            throw new IllegalArgumentException("核销码已过期");
        }

        // 检查订单状态
        Order order = orderMapper.selectById(verificationCodes.getOrderId());
        if (order == null || order.getStatus() != 6) {
            throw new IllegalArgumentException("订单状态异常，无法核销");
        }

        // 检查核销码是否过期
        if (LocalDateTime.now().isAfter(verificationCodes.getExpireTime())) {
            // 更新状态为已过期
            verificationCodes.setStatus(3);
            codeMapper.updateById(verificationCodes);
            throw new IllegalArgumentException("核销码已过期");
        }

        if (verificationCodes.getStatus() == 1 || verificationCodes.getVerificationTime() != null) {
            throw new IllegalArgumentException("该订单已被核销，核销时间：" + verificationCodes.getVerificationTime());
        }

        // 执行核销
        verificationCodes.setStatus(1);
        verificationCodes.setUsedTime(LocalDateTime.now());
        verificationCodes.setUsedMerchantId(tenantId);
        verificationCodes.setVerificationTime(LocalDateTime.now());
        verificationCodes.setResult(1);
        int result = codeMapper.updateById(verificationCodes);

        if (result != 1) {
            throw new IllegalArgumentException("核销失败，请重试");
        }

        // 更新订单状态
        order.setStatus(7);
        order.setUsedTime(LocalDateTime.now());
        orderMapper.updateById(order);

    }


    /**
     * 生成唯一核销码
     */
    private String generateUniqueCode() {
        String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", "");
        return CodePrefix.HXM.name()+"-" + uuid.substring(0, 16).toUpperCase();
    }

    @Override
    public List<VerificationCodes> getByOrderId(Long orderId) {
        LambdaQueryWrapper<VerificationCodes> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VerificationCodes::getOrderId, orderId);
        return codeMapper.selectList(wrapper);
    }
}
