package com.ycwl.basic.service.aio.impl;

import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import com.ycwl.basic.enums.OrderStateEnum;
import com.ycwl.basic.exception.BaseException;
import com.ycwl.basic.mapper.AioDeviceMapper;
import com.ycwl.basic.mapper.OrderMapper;
import com.ycwl.basic.model.aio.entity.AioDeviceEntity;
import com.ycwl.basic.model.aio.entity.AioDevicePriceConfigEntity;
import com.ycwl.basic.model.aio.req.AioDeviceCreateOrderReq;
import com.ycwl.basic.model.aio.resp.AioDeviceCreateOrderResp;
import com.ycwl.basic.model.pc.face.entity.FaceEntity;
import com.ycwl.basic.model.pc.order.entity.OrderEntity;
import com.ycwl.basic.model.pc.order.entity.OrderItemEntity;
import com.ycwl.basic.pay.adapter.IPayAdapter;
import com.ycwl.basic.pay.adapter.WxMpPayAdapter;
import com.ycwl.basic.repository.FaceRepository;
import com.ycwl.basic.service.aio.AioDeviceService;
import com.ycwl.basic.service.pc.ScenicService;
import com.ycwl.basic.utils.SnowFlakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class AioDeviceServiceImpl implements AioDeviceService {
    @Autowired
    private AioDeviceMapper aioDeviceMapper;
    @Autowired
    private ScenicService scenicService;
    @Autowired
    private FaceRepository faceRepository;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public AioDeviceCreateOrderResp createOrder(AioDeviceEntity aioDevice, AioDeviceCreateOrderReq req) {
        // 询价
        AioDevicePriceConfigEntity config = aioDeviceMapper.getPriceConfigByDeviceId(aioDevice.getId());
        if (config == null) {
            throw new BaseException("询价失败");
        }
        if (req.getItems() == null || req.getItems().isEmpty()) {
            throw new BaseException("请选择商品");
        }
        FaceEntity face = faceRepository.getFace(req.getFaceId());
        if (face == null) {
            throw new BaseException("请选择人脸");
        }
        AioDeviceCreateOrderResp resp = new AioDeviceCreateOrderResp();
        int sum = req.getItems().stream().mapToInt(AioDeviceCreateOrderReq.AioDeviceOrderItem::getCount).sum();
        BigDecimal totalPrice = config.getEachPrice().multiply(new BigDecimal(sum));
        if (totalPrice.compareTo(BigDecimal.ZERO) <= 0) {
            resp.setSkipPay(true);
            return resp;
        }
        OrderEntity order = new OrderEntity();
        Long orderId = SnowFlakeUtil.getLongId();
        resp.setOrderId(orderId);
        order.setId(orderId);
        order.setMemberId(face.getMemberId());
        order.setFaceId(face.getId());
        order.setScenicId(face.getScenicId());
        order.setType(0);
        List<OrderItemEntity> orderItems = req.getItems().stream().map(item -> {
            OrderItemEntity orderItem = new OrderItemEntity();
            orderItem.setOrderId(orderId);
            orderItem.setGoodsId(item.getGoodsId());
            orderItem.setGoodsType(4);
            if (item.getCount() == null) {
                item.setCount(1);
            }
            orderItem.setCount(item.getCount());
            return orderItem;
        }).toList();
        order.setSlashPrice(totalPrice);
        order.setPrice(totalPrice);
        order.setPayPrice(totalPrice);
        order.setStatus(OrderStateEnum.UNPAID.getState());
        orderMapper.add(order);
        int addOrderItems = orderMapper.addOrderItems(orderItems);
        // 支付
        IPayAdapter scenicPayAdapter = scenicService.getScenicPayAdapter(aioDevice.getScenicId());
        if (scenicPayAdapter instanceof WxMpPayAdapter adapter) {
            NativePayService service = new NativePayService.Builder().config(adapter.getConfig()).build();
            PrepayRequest request = new PrepayRequest();
            request.setAppid(adapter._config().getAppId());
            request.setMchid(adapter._config().getMerchantId());
            request.setDescription("打印订单");
            request.setOutTradeNo(String.valueOf(orderId));
            request.setNotifyUrl("https://zhentuai.com/api/mobile/wx/pay/v1/"+aioDevice.getScenicId()+"/payNotify");
            Amount amount = new Amount();
            amount.setTotal(totalPrice.multiply(new BigDecimal(100)).intValue());
            request.setAmount(amount);
            PrepayResponse response = service.prepay(request);
            resp.setPayCode(response.getCodeUrl());
        }
        return resp;
    }
}
