package com.fs.app.controller.live;


import com.alibaba.fastjson.JSON;
import com.fs.app.annotation.Login;
import com.fs.app.controller.AppBaseController;
import com.fs.common.annotation.Log;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.enums.BusinessType;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.course.domain.FsCoursePlaySourceConfig;
import com.fs.course.mapper.FsCoursePlaySourceConfigMapper;
import com.fs.his.domain.FsPayConfig;
import com.fs.his.domain.MerchantAppConfig;
import com.fs.his.mapper.MerchantAppConfigMapper;
import com.fs.live.domain.LiveCart;
import com.fs.live.service.ILiveCartService;
import com.fs.live.vo.LiveCartVo;
import com.fs.hisStore.service.IFsStoreOrderScrmService;
import com.fs.hisStore.mapper.FsStorePaymentScrmMapper;
import com.fs.hisStore.domain.FsStoreOrderScrm;
import com.fs.hisStore.domain.FsStorePaymentScrm;
import com.fs.hisStore.service.IFsStorePaymentScrmService;
import com.fs.huifuPay.domain.HuiFuQueryOrderResult;
import com.fs.huifuPay.domain.HuiFuRefundResult;
import com.fs.huifuPay.sdk.opps.core.request.V2TradePaymentScanpayQueryRequest;
import com.fs.huifuPay.sdk.opps.core.request.V2TradePaymentScanpayRefundRequest;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.his.domain.FsHfpayConfig;
import com.fs.his.mapper.FsHfpayConfigMapper;
import com.fs.config.cloud.CloudHostProper;
import com.fs.common.utils.spring.SpringUtils;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fs.common.utils.StringUtils;

/**
 * 购物车Controller
 *
 * @author fs
 * @date 2025-07-08
 */
@Slf4j
@RestController
@RequestMapping("/live/liveCart")
@Api(tags = "购物车管理")
public class LiveCartController extends AppBaseController
{
    @Autowired
    private ILiveCartService liveCartService;
    
    @Autowired
    private IFsStoreOrderScrmService fsStoreOrderScrmService;
    
    @Autowired
    private FsStorePaymentScrmMapper fsStorePaymentScrmMapper;
    
    @Autowired
    private HuiFuService huiFuService;
    
    @Autowired
    private IFsStorePaymentScrmService fsStorePaymentScrmService;
    
    @Autowired
    private CloudHostProper cloudHostProper;

    /**
     * 查询购物车列表
     */
    @GetMapping("/list")
    @ApiOperation("查询购物车列表")
    @Login
    public R list(LiveCart liveCart)
    {
        PageHelper.startPage(liveCart.getPage(), liveCart.getPageSize());
        try {
            liveCart.setUserId(String.valueOf(getUserId()));
            List<LiveCartVo> list = liveCartService.selectLiveCartListVo(liveCart);
            PageInfo<LiveCartVo>  result = new PageInfo<>(list);
            return R.ok().put("data", result);
        } catch (Exception e) {
            return R.error("操作异常");
        }
    }

    /**
     * 导出购物车列表
     */
    @Log(title = "购物车", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ApiOperation("导出购物车列表")
    @Login
    public AjaxResult export(LiveCart liveCart)
    {
        List<LiveCart> list = liveCartService.selectLiveCartList(liveCart);
        ExcelUtil<LiveCart> util = new ExcelUtil<LiveCart>(LiveCart.class);
        return util.exportExcel(list, "购物车数据");
    }

    /**
     * 获取购物车详细信息
     */
    @GetMapping(value = "/{cardId}")
    @ApiOperation("获取购物车详细信息")
    @ApiImplicitParam(name = "cardId", value = "购物车ID", required = true, dataType = "Long", paramType = "path")
    @Login
    public AjaxResult getInfo(@PathVariable("cardId") Long cardId)
    {
        return AjaxResult.success(liveCartService.selectLiveCartByCartId(cardId));
    }

    /**
     * 新增购物车
     */
    @PostMapping
    @ApiOperation("新增购物车")
    @Login
    @RepeatSubmit
    public R add(@RequestBody @ApiParam("购物车信息") LiveCart liveCart)
    {
        liveCart.setUserId(String.valueOf(getUserId()));
        return R.ok().put("data",liveCartService.insertLiveCart(liveCart));
    }

    /**
     * 修改购物车
     */
    @PostMapping("/update")
    @ApiOperation("修改购物车")
    @Login
    @RepeatSubmit
    public R edit(@RequestBody @ApiParam("购物车信息") LiveCart liveCart)
    {
        liveCart.setUserId(String.valueOf(getUserId()));
        return R.ok().put("data",liveCartService.updateLiveCart(liveCart));
    }

    /**
     * 删除购物车
     */
	@PostMapping("/delete")
    @ApiOperation("删除购物车")
    @ApiImplicitParam(name = "cardIds", value = "购物车ID数组", required = true, dataType = "Long", paramType = "path")
    @Login
    public R remove(@RequestBody Long[] cardIds)
    {
        return R.ok().put("data",liveCartService.deleteByCartIds(cardIds, Long.valueOf(getUserId())));
    }

    @GetMapping("/checked")
    @ApiOperation("查询购物车列表")
    @Login
    public R getChecked(LiveCart liveCart)
    {
        PageHelper.startPage(liveCart.getPage(), liveCart.getPageSize());
        try {
            liveCart.setUserId(String.valueOf(getUserId()));
            List<LiveCartVo> list = liveCartService.getChecked(liveCart);
            PageInfo<LiveCartVo>  result = new PageInfo<>(list);
            return R.ok().put("data", result);
        } catch (Exception e) {
            return R.error("操作异常");
        }
    }
    @Autowired
    FsCoursePlaySourceConfigMapper fsCoursePlaySourceConfigMapper;
    @Autowired
    MerchantAppConfigMapper merchantAppConfigMapper;
    @Autowired
    private WxPayService wxPayService;
    @GetMapping("/test1")
    public void test1() {
        FsCoursePlaySourceConfig fsCoursePlaySourceConfig = fsCoursePlaySourceConfigMapper.selectCoursePlaySourceConfigByAppId("wx9bb2cd1e3afe714e");
        if (fsCoursePlaySourceConfig == null) {
            throw new CustomException("未找到appId对应的小程序配置: " );
        }
        Long merchantConfigId = fsCoursePlaySourceConfig.getMerchantConfigId();
        if (merchantConfigId == null || merchantConfigId <= 0) {
            throw new CustomException("小程序没有配置商户信息");
        }
        MerchantAppConfig merchantAppConfig = merchantAppConfigMapper.selectMerchantAppConfigById(fsCoursePlaySourceConfig.getMerchantConfigId());
        FsPayConfig fsPayConfig = JSON.parseObject(merchantAppConfig.getDataJson(), FsPayConfig.class);
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(fsCoursePlaySourceConfig.getAppid());
        payConfig.setMchId(fsPayConfig.getWxMchId());
        payConfig.setMchKey(fsPayConfig.getWxMchKey());
        payConfig.setKeyPath(fsPayConfig.getKeyPath());
        payConfig.setSubAppId(org.apache.commons.lang3.StringUtils.trimToNull(null));
        payConfig.setSubMchId(org.apache.commons.lang3.StringUtils.trimToNull(null));
        wxPayService.setConfig(payConfig);
        WxPayRefundRequest refundRequest = new WxPayRefundRequest();
        refundRequest.setOutTradeNo("live-live-" + "2017147035307872256");
        refundRequest.setOutRefundNo("live-live-" + "2017147035307872256");
        refundRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen("0.10"));
        refundRequest.setRefundFee(WxPayUnifiedOrderRequest.yuanToFen("0.10"));
        try {
            WxPayRefundResult refundResult = wxPayService.refund(refundRequest);
            WxPayRefundQueryResult refundQueryResult = wxPayService.refundQuery("", refundResult.getOutTradeNo(), refundResult.getOutRefundNo(), refundResult.getRefundId());
            if(refundQueryResult!=null&&refundQueryResult.getResultCode().equals("SUCCESS")){
                FsStorePaymentScrm paymentMap=new FsStorePaymentScrm();
                paymentMap.setPaymentId(41868L);
                paymentMap.setStatus(-1);
                paymentMap.setRefundTime(DateUtils.getNowDate());
                paymentMap.setRefundMoney(BigDecimal.valueOf(0.1));
                fsStorePaymentScrmMapper.updateFsStorePayment(paymentMap);
                log.error("成功");
            }
            else {
                log.error("失败");
            }
        } catch (WxPayException e) {
            log.error("失败");
        }
    }


    /**
     * 确认支付（银行回调补偿）
     */
    @GetMapping("/confirmPay/{orderCode}")
    @ApiOperation("确认支付")
    @ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "String", paramType = "path")
    public R confirmPay(@PathVariable("orderCode") String orderCode)
    {
        try {
            log.info("确认支付请求，订单号: {}", orderCode);

            // 查询商城订单
            FsStoreOrderScrm order = fsStoreOrderScrmService.selectFsStoreOrderByOrderCode(orderCode);
            if (order == null) {
                return R.error("订单不存在");
            }

            // 查询未支付的支付记录
            List<FsStorePaymentScrm> orderPayments = fsStorePaymentScrmMapper.selectNoPayByOrderId(order.getId());
            if (orderPayments == null || orderPayments.isEmpty()) {
                return R.error("未找到待支付的支付记录");
            }

            // 遍历支付记录，查询汇付订单状态
            for (FsStorePaymentScrm payment : orderPayments) {
                V2TradePaymentScanpayQueryRequest request = new V2TradePaymentScanpayQueryRequest();
                request.setOrgReqDate(new java.text.SimpleDateFormat("yyyyMMdd").format(payment.getCreateTime()));
                request.setOrgHfSeqId(payment.getTradeNo());
                request.setAppId(payment.getAppId());

                HuiFuQueryOrderResult queryResult = null;
                try {
                    queryResult = huiFuService.queryOrder(request);
                } catch (Exception e) {
                    log.error("查询汇付订单失败，订单号: {}, 错误: {}", orderCode, e.getMessage());
                    continue;
                }

                log.info("汇付返回结果: {}", queryResult);

                // 如果支付成功，进行回调保存
                if ("00000000".equals(queryResult.getResp_code()) && "S".equals(queryResult.getTrans_stat())) {
                    String[] orderSplit = queryResult.getOrg_req_seq_id().split("-");
                    if (orderSplit.length > 1) {
                        String payCode = orderSplit[1];
                        // 调用支付确认
                        fsStoreOrderScrmService.payConfirm(1, null, payCode, queryResult.getOrg_hf_seq_id(),
                                queryResult.getOut_trans_id(), queryResult.getParty_order_id());
                        return R.ok("支付确认成功");
                    }
                }
            }

            return R.error("未找到已支付的记录");
        } catch (Exception e) {
            log.error("确认支付异常，订单号: {}", orderCode, e);
            return R.error("确认支付失败: " + e.getMessage());
        }
    }



}
