package cn.sikey.hmd.controller.app.index;

import cn.sikey.framework.common.exception.ServiceException;
import cn.sikey.framework.common.pojo.CommonResult;
import cn.sikey.hmd.api.hmd.vo.payments.PaymentsRespVO;
import cn.sikey.hmd.api.hmd.vo.plans.PlansRespVO;
import cn.sikey.hmd.entity.paymentindex.ResultInfo;
import cn.sikey.hmd.entity.paymentindex.ServiceInfo;
import cn.sikey.hmd.enums.ValidityEnum;
import cn.sikey.hmd.service.languagedictionary.LanguageDictionaryService;
import cn.sikey.hmd.service.payments.PaymentService;
import cn.sikey.hmd.service.plans.PlansService;
import cn.sikey.hmd.util.MapUtil;
import cn.sikey.hmd.util.PriceUtil;
import cn.sikey.order.api.order.OrderApi;
import cn.sikey.order.api.order.vo.GenerateOrderReqVO;
import cn.sikey.pay.api.alipay.AlipayApi;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: qin
 * @Date: 2025/3/31
 * @Description: 套餐支付首页
 */
@Controller
@RequestMapping("/h5/hmd/payment")
@Slf4j
public class PaymentIndexController {

    @Resource
    private OrderApi orderApi;

    @Resource
    private AlipayApi alipayApi;

    @Resource
    private PaymentService paymentService;

    @Resource
    private PlansService plansService;

    @Resource
    private LanguageDictionaryService languageDictionaryService;

    @GetMapping("/index")
    public String index(String imei, Model model) {
        PlansRespVO plansRespVO = plansService.queryPlans(ValidityEnum.YEAR.getValue());
        String price = "0.00";
        if (Objects.nonNull(plansRespVO)) {
            price = PriceUtil.convertFenToYuan(plansRespVO.getPrice());
        }
        model.addAttribute("imei", imei);
        model.addAttribute("serviceInfo", new ServiceInfo("思奇智能AI助手", "现已接入Deep Seek大模型"));
        //  model.addAttribute("pricingPlans", getAvailablePlans());

        model.addAttribute("yearPrice", price);
        // 年套餐
        model.addAttribute("validity", 1);
        // model.addAttribute("featureList", getFeatureComparison());
        // model.addAttribute("paymentMethods", Arrays.asList(new PaymentMethod("alipay", "支付宝", true), new PaymentMethod("wechat", "微信支付", false)));

        /*DeviceActivationDTO deviceActivationDTO = deviceActivationService.queryDeviceActivation(imei);

        boolean isExpire = Objects.nonNull(deviceActivationDTO) && Objects.nonNull(deviceActivationDTO.getPlansValidity()) && deviceActivationDTO.getPlansValidity().intValue() == ValidityEnum.YEAR.getValue();
        if (isExpire) {
            log.warn("[手机网站支付-支付宝]您已是会员，未过有效期，勿需再支付");
            return "lifelong";
        }*/

        return "index";
    }

    @GetMapping("/result")
    public String index(HttpServletRequest request, Model model) {
        Map<String, String> paramsMap = MapUtil.convertRequestToMap(request);
        log.info("[手机网站支付-支付宝，回调]return返回值 : {}", paramsMap.entrySet());
        boolean isVerify = true;

        // 验签
        CommonResult<Integer> commonResult = alipayApi.verifySignVerified(paramsMap);
        if (!commonResult.getCode().equals(HttpStatus.SC_OK)) {
            log.warn("[手机网站支付-支付宝，回调]调用支付服务验签失败");
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "调用支付服务验签失败");
        }
        if (Objects.isNull(commonResult.getData()) || commonResult.getData().intValue() == 0) {
            isVerify = false;
            log.warn("[手机网站支付-支付宝，回调]验签失败");
        }

        String outTradeNo = paramsMap.get("out_trade_no");
        CommonResult<GenerateOrderReqVO> queryOrder = orderApi.queryOrder(outTradeNo);
        if (!queryOrder.getCode().equals(HttpStatus.SC_OK)) {
            log.warn("[手机网站支付-支付宝，回调]调用订单服务失败");
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "调用订单服务失败");
        }

        GenerateOrderReqVO generateOrderReqVO = queryOrder.getData();
        if (Objects.isNull(generateOrderReqVO)) {
            log.warn("[手机网站支付-支付宝，回调]调用订单数据是空");
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "调用订单数据是空");
        }
        PaymentsRespVO paymentsRespVO = paymentService.queryPayments(generateOrderReqVO.getId());
        if (Objects.isNull(paymentsRespVO)) {
            log.warn("[手机网站支付-支付宝，回调]获取付款是空");
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "获取付款是空");
        }

        model.addAttribute("serviceInfo", new ServiceInfo("思奇智能AI助手", "现已接入Deep Seek大模型"));

        ResultInfo resultInfo = new ResultInfo();
        resultInfo.setOrderSn(generateOrderReqVO.getOrderSn());
        resultInfo.setTotalAmount(PriceUtil.convertFenToYuan(generateOrderReqVO.getTotalAmount()));
        resultInfo.setPaymentTime(paymentsRespVO.getPaymentTime());

        model.addAttribute("resultInfo", resultInfo);
        model.addAttribute("verify", isVerify);
        return "result";
    }

    @GetMapping("/agreement")
    public String agreement() {
        return "agreement";
    }

    @GetMapping("/userAgreement")
    public String userAgreement() {
        return "userAgreement";
    }

    /*public List<PricingPlan> getAvailablePlans() {
        return Arrays.asList(new PricingPlan("包年服务", new BigDecimal("0.02"), 1), new PricingPlan("终身服务", new BigDecimal("0.01"), 2));
    }*/

    /*public LinkedList<Feature> getFeatureComparison() {
        LinkedList<Feature> featureList = new LinkedList<>();

        // 使用 LinkedHashMap 保证顺序
        featureList.add(new Feature("专属特权", createOrderedMap("voiceArousal", "语音唤起", "intelligentService", "智能服务", "maximumNumberOfTimes", "次数上限"), false));

        featureList.add(new Feature("普通", createOrderedMap("support", "支持", "tryOut", "试用", "day", "100天"), false));

        // featureList.add(new Feature("包年", createOrderedMap("support", "支持", "advanced", "高级", "noLimit", "不限次"), false));

        featureList.add(new Feature("VIP", createOrderedMap("support", "支持", "advanced", "高级", "noLimit", "不限次"), true));

        return featureList;
    }*/

    /**
     * 创建有序 Map 的辅助方法
     *
     * @param kvPairs
     * @return
     */
    private LinkedHashMap<String, String> createOrderedMap(String... kvPairs) {
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        for (int i = 0; i < kvPairs.length; i += 2) {
            map.put(kvPairs[i], kvPairs[i + 1]);
        }
        return map;
    }

    @GetMapping("/razorpayIndex")
    public ResponseEntity<Void> razorpayIndex(String imei, String languageType) {
        String publicDomain = "https://pay.tecanswer.com/h5/hmd/payment"; // 配置为公网域名
        if (StringUtils.isBlank(languageType) || StringUtils.equalsAnyIgnoreCase(languageType, "3")) {
            String redirectUrl = publicDomain + "/razorpayIndiaIndex?imei=" + imei;
            return ResponseEntity.status(HttpStatus.SC_MOVED_TEMPORARILY)
                    .location(URI.create(redirectUrl))
                    .build();
        } else {
            String redirectUrl = publicDomain + "/razorpayEnglishIndex?imei=" + imei;
            return ResponseEntity.status(HttpStatus.SC_MOVED_TEMPORARILY)
                    .location(URI.create(redirectUrl))
                    .build();
        }

    }

    @GetMapping("/razorpayIndiaIndex")
    public String razorpayIndiaIndex(String imei, Model model) {
        PlansRespVO plansRespVO = plansService.queryPlans(ValidityEnum.YEAR.getValue());
        String price = "0.00";
        if (Objects.nonNull(plansRespVO)) {
            price = PriceUtil.convertFenToYuan(plansRespVO.getPrice());
        }
        model.addAttribute("imei", imei);
        //model.addAttribute("serviceInfo", languageDictionaryService.getLanguageDictionary("3"));
        //  model.addAttribute("pricingPlans", getAvailablePlans());

        model.addAttribute("yearPrice", price);
        // 年套餐
        model.addAttribute("validity", 1);
        model.addAttribute("razorPayKey", "rzp_test_bwL1qbvhAdCZqw");

        // model.addAttribute("featureList", getFeatureComparison());
        // model.addAttribute("paymentMethods", Arrays.asList(new PaymentMethod("alipay", "支付宝", true), new PaymentMethod("wechat", "微信支付", false)));

        /*DeviceActivationDTO deviceActivationDTO = deviceActivationService.queryDeviceActivation(imei);

        boolean isExpire = Objects.nonNull(deviceActivationDTO) && Objects.nonNull(deviceActivationDTO.getPlansValidity()) && deviceActivationDTO.getPlansValidity().intValue() == ValidityEnum.YEAR.getValue();
        if (isExpire) {
            log.warn("[手机网站支付-支付宝]您已是会员，未过有效期，勿需再支付");
            return "lifelong";
        }*/

        return "razorpayIndiaIndex";
    }

    @GetMapping("/razorpayEnglishIndex")
    public String razorpayEnglishIndex(String imei, Model model) {
        PlansRespVO plansRespVO = plansService.queryPlans(ValidityEnum.YEAR.getValue());
        String price = "0.00";
        if (Objects.nonNull(plansRespVO)) {
            price = PriceUtil.convertFenToYuan(plansRespVO.getPrice());
        }
        model.addAttribute("imei", imei);
        //model.addAttribute("serviceInfo", languageDictionaryService.getLanguageDictionary("2"));
        //  model.addAttribute("pricingPlans", getAvailablePlans());

        model.addAttribute("yearPrice", price);
        // 年套餐
        model.addAttribute("validity", 1);
        model.addAttribute("razorPayKey", "rzp_test_bwL1qbvhAdCZqw");
        // model.addAttribute("featureList", getFeatureComparison());
        // model.addAttribute("paymentMethods", Arrays.asList(new PaymentMethod("alipay", "支付宝", true), new PaymentMethod("wechat", "微信支付", false)));

        /*DeviceActivationDTO deviceActivationDTO = deviceActivationService.queryDeviceActivation(imei);

        boolean isExpire = Objects.nonNull(deviceActivationDTO) && Objects.nonNull(deviceActivationDTO.getPlansValidity()) && deviceActivationDTO.getPlansValidity().intValue() == ValidityEnum.YEAR.getValue();
        if (isExpire) {
            log.warn("[手机网站支付-支付宝]您已是会员，未过有效期，勿需再支付");
            return "lifelong";
        }*/

        return "razorpayEnglishIndex";
    }

}
