package com.ruoyi.xq.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.xq.domain.ActivityOrder;
import com.ruoyi.xq.domain.ActivityShop;
import com.ruoyi.xq.dto.admin.activity.ActivityOrderAdminVo;
import com.ruoyi.xq.dto.app.activity.CreateOrderReq;
import com.ruoyi.xq.dto.app.pay.ConsumeResp;
import com.ruoyi.xq.dto.common.user.MinUser;
import com.ruoyi.xq.enums.common.OrderTypeEnum;
import com.ruoyi.xq.enums.common.TraceIdEnum;
import com.ruoyi.xq.enums.pay.PayStatusEnum;
import com.ruoyi.xq.enums.pay.PlatformTypeEnum;
import com.ruoyi.xq.enums.userinfo.UserGenderEnum;
import com.ruoyi.xq.manager.OrderNoUtil;
import com.ruoyi.xq.manager.TraceIdManager;
import com.ruoyi.xq.mapper.ActivityOrderMapper;
import com.ruoyi.xq.service.ActivityOrderService;
import com.ruoyi.xq.service.ActivityShopService;
import com.ruoyi.xq.service.ActivityUserService;
import com.ruoyi.xq.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 相亲会订单Service业务层处理
 *
 * @author 77
 * @date 2024-05-09
 */
@Service
public class ActivityOrderServiceImpl extends ServiceImpl<ActivityOrderMapper,ActivityOrder> implements ActivityOrderService {

    @Autowired
    private ActivityShopService activityShopService;
    @Autowired
    private UserService userService;
    @Autowired
    private ActivityUserService activityUserService;
    @Override
    public ActivityOrder createOrder(CreateOrderReq req) {
        ActivityShop activityShop = activityShopService.getById(req.getActivityId());
        if(activityShop == null){
            throw new ServiceException("相亲会不存在");
        }
        if(StringUtils.isNotEmpty(req.getMobile())){
            throw new ServiceException("请填写手机号");
        }
        MinUser minUser = userService.getMinUserById(req.getUserId());
        if(minUser== null){
            throw new ServiceException("用户不存在");
        }
        BigDecimal price = null;
        if(UserGenderEnum.MAN.getCode().equals(minUser.getGender())){
            price = activityShop.getJoinManPrice();
        }else if(UserGenderEnum.WOMEN.getCode().equals(minUser.getGender())){
            price = activityShop.getJoinWomenPrice();
        }else{
            throw new ServiceException("用户异常");
        }
        String orderNo = OrderNoUtil.gen(OrderTypeEnum.ACTIVITY_MATCHMAKING);
        String traceId = TraceIdManager.gen(TraceIdEnum.ACTIVITY_MATCHMAKING);
        ActivityOrder order = new ActivityOrder();
        order.setUserId(minUser.getId());
        order.setUsercode(minUser.getUsercode());
        order.setBody("报名相亲会");
        order.setPrice(price);
        order.setTraceId(traceId);
        order.setActivityId(activityShop.getId());
        order.setActivityTitle(activityShop.getActivityTitle());
        order.setActivityCode(activityShop.getActivityCode());
        order.setActivityMobile(req.getMobile());
        order.setOrderName("报名相亲会");
        order.setOrderNo(orderNo);
        order.setPayStatus(PayStatusEnum.READY_PAY.getCode());
        this.save(order);
        return order;
    }

    @Override
    public ActivityOrder getByOrderNo(String orderNo){
        return this.getOne(Wrappers.lambdaQuery(ActivityOrder.class).eq(ActivityOrder::getOrderNo, orderNo).last("limit 1"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ConsumeResp doSuccess(String orderNo, Map<String, String> params, String appId, PlatformTypeEnum payTypeEnum){
        ActivityOrder order = this.getByOrderNo(orderNo);
        if(order == null){
            ConsumeResp resp = new ConsumeResp();
            resp.setSuccess(false);
            return resp;
        }
        String traceId = TraceIdManager.gen(TraceIdEnum.ACTIVITY_MATCHMAKING);
        boolean success = this.update(Wrappers.lambdaUpdate(ActivityOrder.class)
                .eq(ActivityOrder::getId, order.getId())
                .eq(ActivityOrder::getPayStatus, PayStatusEnum.READY_PAY.getCode())
                .set(ActivityOrder::getPayStatus, PayStatusEnum.PAY.getCode())
                .set(ActivityOrder::getTraceId, traceId)
                .set(ActivityOrder::getReturnContent, JSON.toJSONString(params))
                .set(ActivityOrder::getAppid,appId)
                .set(ActivityOrder::getPlatformType, payTypeEnum.getCode()));
        if(!success){
            ConsumeResp resp = new ConsumeResp();
            resp.setSuccess(false);
            return resp;
        }
        activityUserService.joinActivity(order.getOrderNo());
        ConsumeResp resp = new ConsumeResp();
        resp.setPrice(order.getPrice());
        resp.setUserId(order.getUserId());
        resp.setTraceId(traceId);
        resp.setSuccess(true);
        return resp;
    }

    @Override
    public Page<ActivityOrderAdminVo> pageAdmin(PageQuery pageQuery, ActivityOrderAdminVo bo) {
        return baseMapper.pageAdmin(pageQuery.build(), bo);
    }
}
