package io.controller;

import cn.hutool.core.util.IdUtil;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.annotation.Login;
import io.annotation.LoginUser;
import io.common.exception.RenException;
import io.common.utils.DateUtils;
import io.common.utils.Result;
import io.config.AlipayConfig;
import io.entity.UserEntity;
import io.modules.item.dao.OrderDao;
import io.modules.item.dto.DoctorsDTO;
import io.modules.item.dto.OrderDTO;
import io.modules.item.entity.OrderEntity;
import io.modules.item.service.DoctorsService;
import io.modules.item.service.OrderService;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
 * 支付宝接口
 */
@RestController
@RequestMapping("/api/alipay")
@CrossOrigin
public class AliPayController {
    @Autowired
    private DoctorsService doctorsService;
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDao orderDao;
    @Autowired
    AlipayConfig alipayTemplate;

    @GetMapping(value = "/pay", produces = "text/html")
    @Login
    public String pay(OrderDTO dto, @Parameter(hidden = true) @LoginUser UserEntity user) throws AlipayApiException {

        DoctorsDTO doctor = doctorsService.get(dto.getItemId());
        if (doctor == null) {
            throw new RenException("查询不到医生信息");
        }
        long orderId = IdUtil.getSnowflake(1, 1).nextId();
        dto.setUserId(user.getId());
        dto.setOrderId(orderId);
        dto.setPaymentMethod("支付宝");
        dto.setSubject(doctor.getUserName());
        dto.setOrderStatus(4); // 未支付
        orderService.save(dto);
        return alipayTemplate.pay(dto); // 直接返回支付宝的HTML响应
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request){
        System.out.println("消息进来！！！！！！！！！！！！！！！！！");
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            //唯一编号
            String tradeNo = params.get("out_trade_no");
            //支付时间
            String gmtPayment = params.get("gmt_payment");
            //支付编号
            String alipayTradeNo = params.get("trade_no");
            System.out.println("-------------------------");
            System.out.println(tradeNo);
            System.out.println(gmtPayment);
            System.out.println(alipayTradeNo);

            LambdaQueryWrapper<OrderEntity> lwq = new LambdaQueryWrapper<>();
            lwq.eq(OrderEntity::getOrderId,tradeNo);
            OrderEntity order = orderDao.selectOne(lwq);
            //支付时间
            order.setPaymentDate(DateUtils.parse(gmtPayment,DateUtils.DATE_TIME_PATTERN));
            order.setOrderStatus(0);
            orderDao.updateById(order);
        }
        return "success";
    }
}

