package com.ruoyi.ai.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.ai.domain.AiManager;
import com.ruoyi.ai.domain.AiOrder;
import com.ruoyi.ai.domain.AiStatistics;
import com.ruoyi.ai.mapper.AiOrderMapper;
import com.ruoyi.ai.service.IAiManagerService;
import com.ruoyi.ai.service.IAiOrderService;
import com.ruoyi.ai.service.IAiStatisticsService;
import com.ruoyi.ai.service.IAiUserService;
import com.ruoyi.common.constant.BalanceChangerConstants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.AiUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 订单管理Service业务层处理
 *
 * @author shi
 * @date 2025-11-13
 */
@Service
public class AiOrderServiceImpl implements IAiOrderService {

    @Autowired
    private AiOrderMapper aiOrderMapper;

    @Autowired
    private IAiManagerService aiManagerService;

    @Autowired
    private IAiUserService aiUserService;

    @Autowired
    private IAiStatisticsService aiStatisticsService;


    /**
     * 查询订单管理
     *
     * @param id 订单管理主键
     * @return 订单管理
     */
    @Override
    public AiOrder selectAiOrderById(Long id) {
        return aiOrderMapper.selectById(id);
    }

    /**
     * 查询订单管理列表
     *
     * @param aiOrder 订单管理
     * @return 订单管理
     */
    @Override
    public List<AiOrder> selectAiOrderList(AiOrder aiOrder) {
        return aiOrderMapper.selectAiOrderList(aiOrder);
    }

    /**
     * 分页查询订单管理列表
     *
     * @param aiOrder 订单管理
     * @return 订单管理
     */
    @Override
    public IPage<AiOrder> selectAiOrderPage(Page page, AiOrder aiOrder) {
        LambdaQueryWrapper<AiOrder> query = Wrappers.lambdaQuery(aiOrder);
        query.eq(AiOrder::getDelFlag, "0");
        return aiOrderMapper.selectPage(page, query);
    }

    /**
     * 新增订单管理
     *
     * @param aiOrder 订单管理
     * @return 结果
     */
    @Override
    public int insertAiOrder(AiOrder aiOrder) {
        aiOrder.setDelFlag("0");
        aiOrder.setCreateBy(SecurityUtils.getUsername());
        aiOrder.setCreateTime(DateUtils.getNowDate());
        return aiOrderMapper.insert(aiOrder);
    }

    /**
     * 修改订单管理
     *
     * @param aiOrder 订单管理
     * @return 结果
     */
    @Override
    public int updateAiOrder(AiOrder aiOrder) {
//        aiOrder.setUpdateBy(SecurityUtils.getUsername());
        aiOrder.setUpdateTime(DateUtils.getNowDate());
        return aiOrderMapper.updateById(aiOrder);
    }

    /**
     * 批量删除订单管理
     *
     * @param ids 需要删除的订单管理主键
     * @return 结果
     */
    @Override
    public int deleteAiOrderByIds(Long[] ids) {
        return aiOrderMapper.deleteAiOrderByIds(ids);
    }

    /**
     * 删除订单管理信息
     *
     * @param id 订单管理主键
     * @return 结果
     */
    @Override
    public int deleteAiOrderById(Long id) {
        return aiOrderMapper.deleteAiOrderById(id);
    }

    /**
     * 生成订单
     *
     * @param aiType 对应的AI类型
     * @return
     */
    @Override
    @Transactional
    public AiOrder getAiOrder(String aiType) {
        AiManager aiManager = aiManagerService.selectAiManagerByType(aiType);
        if (aiManager == null) {
            throw new ServiceException("Corresponding functionType does not exist", HttpStatus.BAD_REQUEST);
        }
        // 判断用户余额是否足够
        AiUser aiUser = aiUserService.selectAiUserById(SecurityUtils.getAiUserId());
        if (aiUser.getBalance().compareTo(aiManager.getPrice()) < 0) {
            return null;
        }
        AiOrder aiOrder = new AiOrder();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        String dateTime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String orderno = dateTime + uuid;
        aiOrder.setOrderNum(orderno);
        aiOrder.setUserId(SecurityUtils.getAiUserId());
        aiOrder.setType(aiType);
        aiOrder.setResult(null);
        aiOrder.setAmount(aiManager.getPrice());
        aiOrder.setStatus(0);
        aiOrder.setSource(aiUser.getSource());
        aiOrderMapper.insert(aiOrder);
        // 执行余额变更
        aiUserService.addUserBalance(orderno, SecurityUtils.getAiUserId(), NumberUtil.mul(-1, aiManager.getPrice()), getChangerType(aiType));
        return aiOrder;
    }

    @Override
    @Transactional
    public void orderFailure(AiOrder aiOrder) {
        aiOrder.setStatus(2);
        String remark = MessageUtils.message("order.number.generation.failed", aiOrder.getOrderNum());
        aiOrder.setRemark(remark);
        aiOrderMapper.updateById(aiOrder);
        aiUserService.addUserBalance(aiOrder.getOrderNum(), SecurityUtils.getAiUserId(), aiOrder.getAmount(), BalanceChangerConstants.REFUND, remark);
    }

    @Override
    @Transactional
    public void orderSuccess(AiOrder aiOrder) {
        aiOrder.setStatus(1);
        aiOrderMapper.updateById(aiOrder);
        AiStatistics aiStatistics = new AiStatistics();
        aiStatistics.setSource(aiOrder.getSource());
        aiStatistics.setGenerateCount(1L);
        // 新增生成数量
        aiStatisticsService.saveOrUpdateData(aiStatistics);
    }

    @Override
    public AiOrder getAiOrderByResult(String result) {
        LambdaQueryWrapper<AiOrder> query = Wrappers.lambdaQuery();
        query.eq(AiOrder::getDelFlag, "0");
        query.eq(AiOrder::getResult, result);
        return aiOrderMapper.selectOne(query);
    }

    public int getChangerType(String aiType) {
        switch (aiType) {
            case "11":
                return BalanceChangerConstants.IMAGE_TO_IMAGE_1;
            case "12":
                return BalanceChangerConstants.IMAGE_TO_IMAGE_2;
            case "13":
                return BalanceChangerConstants.ONE_CLICK_FACE_SWAP;
            case "1":
                return BalanceChangerConstants.QUICK_IMAGE_GENERATION;
            case "21":
                return BalanceChangerConstants.QUICK_VIDEO_GENERATION;
            default:
                return -1;
        }
    }

    @Override
    public BigDecimal getSumAmountByUserId(String userId) {
        return aiOrderMapper.getSumAmountByUserId(userId);
    }
}
