package com.fs.hisStore.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.controller.pay.bean.AliPayBean;
import com.fs.company.service.ICompanyService;
import com.fs.framework.security.LoginUser;
import com.fs.framework.service.TokenService;
import com.fs.his.domain.FsHfpayConfig;
import com.fs.his.mapper.FsHfpayConfigMapper;
import com.fs.hisStore.domain.FsPayConfigScrm;
import com.fs.hisStore.domain.FsStorePaymentScrm;
import com.fs.hisStore.param.FsStorePaymentParam;
import com.fs.hisStore.service.IFsStorePaymentScrmService;
import com.fs.hisStore.vo.FsStorePaymentVO;
import com.fs.huifuPay.domain.HuiFuRefundResult;
import com.fs.huifuPay.sdk.opps.core.request.V2TradePaymentScanpayRefundRequest;
import com.fs.huifuPay.service.HuiFuService;
import com.ijpay.alipay.AliPayApi;
import com.ijpay.alipay.AliPayApiConfig;
import com.ijpay.alipay.AliPayApiConfigKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付明细Controller
 *
 * @author fs
 * @date 2022-06-20
 */
@RestController
@RequestMapping("/store/store/storePayment")
public class FsStorePaymentScrmController extends BaseController
{
    @Autowired
    private IFsStorePaymentScrmService fsStorePaymentService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private AliPayBean aliPayBean;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    HuiFuService huiFuService;
    
    @Autowired
    private FsHfpayConfigMapper fsHfpayConfigMapper;
    /**
     * 查询支付明细列表
     */
    @PreAuthorize("@ss.hasPermi('store:storePayment:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsStorePaymentParam fsStorePayment)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsStorePayment.setBusinessType(1);
        fsStorePayment.setCompanyId(loginUser.getCompany().getCompanyId());
        startPage();
        List<FsStorePaymentVO> list = fsStorePaymentService.selectFsStorePaymentListQueryVO(fsStorePayment);
        
        // 计算总支付金额和总退款金额
        BigDecimal totalPaymentAmount = BigDecimal.ZERO;
        BigDecimal totalRefundAmount = BigDecimal.ZERO;
        
        for (FsStorePaymentVO vo : list){
            vo.setUserPhone(ParseUtils.parsePhone(vo.getUserPhone()));
            
            // 状态为1（已支付）或-1（已退款）时，累加到总支付金额
            if (vo.getStatus() != null && (vo.getStatus() == 1 || vo.getStatus() == -1)) {
                if (vo.getPayMoney() != null) {
                    totalPaymentAmount = totalPaymentAmount.add(vo.getPayMoney());
                }
            }
            
            // 状态为-1（已退款）时，累加到总退款金额
            if (vo.getStatus() != null && vo.getStatus() == -1) {
                    if (vo.getRefundMoney() != null) {
                        totalRefundAmount = totalRefundAmount.add(vo.getRefundMoney());
                    }
            }
        }
        
        // 记录查询条件，包括新增的退款审核状态
        logger.info("支付明细列表查询，公司ID：{}，退款审核状态：{}，退款审核人：{}，查询结果数量：{}，总支付金额：{}，总退款金额：{}",
            loginUser.getCompany().getCompanyId(), fsStorePayment.getRefundAuditStatus(), 
            fsStorePayment.getRefundAuditBy(), list.size(), totalPaymentAmount, totalRefundAmount);
        
        TableDataInfo dataTable = getDataTable(list);

        dataTable.put("totalPaymentAmount", totalPaymentAmount);
        dataTable.put("totalRefundAmount", totalRefundAmount);
        
        return dataTable;
    }

    /**
     * 导出支付明细列表
     */
    @PreAuthorize("@ss.hasPermi('store:storePayment:export')")
    @Log(title = "支付明细", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsStorePaymentParam fsStorePayment)
    {
        fsStorePayment.setBusinessType(1);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsStorePayment.setCompanyId(loginUser.getCompany().getCompanyId());
        List<FsStorePaymentVO> list = fsStorePaymentService.selectFsStorePaymentListQueryVO(fsStorePayment);
        for (FsStorePaymentVO vo : list){
            vo.setUserPhone(ParseUtils.parsePhone(vo.getUserPhone()));
        }
        ExcelUtil<FsStorePaymentVO> util = new ExcelUtil<FsStorePaymentVO>(FsStorePaymentVO.class);
        return util.exportExcel(list, "storePayment");
    }

    /**
     * 获取支付明细详细信息
     */
    @PreAuthorize("@ss.hasPermi('store:storePayment:query')")
    @GetMapping(value = "/{paymentId}")
    public AjaxResult getInfo(@PathVariable("paymentId") Long paymentId)
    {
        return AjaxResult.success(fsStorePaymentService.selectFsStorePaymentById(paymentId));
    }

    /**
     * 新增支付明细
     */
    @PreAuthorize("@ss.hasPermi('store:storePayment:add')")
    @Log(title = "支付明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsStorePaymentScrm fsStorePayment)
    {
        return toAjax(fsStorePaymentService.insertFsStorePayment(fsStorePayment));
    }

    /**
     * 修改支付明细
     */
    @PreAuthorize("@ss.hasPermi('store:storePayment:edit')")
    @Log(title = "支付明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsStorePaymentScrm fsStorePayment)
    {
        return toAjax(fsStorePaymentService.updateFsStorePayment(fsStorePayment));
    }

    /**
     * 删除支付明细
     */
    @PreAuthorize("@ss.hasPermi('store:storePayment:remove')")
    @Log(title = "支付明细", businessType = BusinessType.DELETE)
	@DeleteMapping("/{paymentIds}")
    public AjaxResult remove(@PathVariable Long[] paymentIds)
    {
        return toAjax(fsStorePaymentService.deleteFsStorePaymentByIds(paymentIds));
    }
    @GetMapping("/getStorePaymentList")
    public R getStorePaymentList(FsStorePaymentParam fsStorePayment)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsStorePayment.setCompanyId(loginUser.getCompany().getCompanyId());
        List<FsStorePaymentVO> list = fsStorePaymentService.selectFsStorePaymentListQueryVO(fsStorePayment);
        return R.ok().put("data",list);
    }

    @GetMapping("/getMyPaymentList")
    public TableDataInfo getMyPaymentList(FsStorePaymentParam fsStorePayment)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsStorePayment.setCompanyId(loginUser.getCompany().getCompanyId());
        fsStorePayment.setCompanyUserId(loginUser.getUser().getUserId());
        startPage();
        fsStorePayment.setStatus(1);
        List<FsStorePaymentVO> list = fsStorePaymentService.selectFsMyStorePaymentListQueryVO(fsStorePayment);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('store:storePayment:refund')")
    @PostMapping("refundStorePayment")
    @Transactional
    public R refundStorePayment(@RequestBody FsStorePaymentScrm fsStorePayment)
    {
        FsStorePaymentScrm payment=fsStorePaymentService.selectFsStorePaymentById(fsStorePayment.getPaymentId());
        if(payment.getStatus()!=1){
            return R.error("非法操作");
        }
        if(fsStorePayment.getRefundMoney().compareTo(new BigDecimal(0))<1){
            return R.error("退款金额必须大于0");
        }
        if(payment.getPayMoney().compareTo(fsStorePayment.getRefundMoney())==-1){
            return R.error("退款金额必须小于等于付款金额");
        }
        if(payment.getPayTypeCode().equals("weixin")){

            if (payment.getPayMode()!=null&&payment.getPayMode().equals("hf")){
                // 根据 appId 获取对应的汇付商户号
                String huifuId = "";
                logger.info("开始退款，支付记录ID：{}，appId：{}", payment.getPaymentId(), payment.getAppId());
                
                if (payment.getAppId() != null && !payment.getAppId().isEmpty()) {
                    FsHfpayConfig fsHfpayConfig = fsHfpayConfigMapper.selectByAppId(payment.getAppId());
                    logger.info("根据appId查询汇付配置，appId：{}，查询结果：{}", payment.getAppId(), fsHfpayConfig);
                    if (fsHfpayConfig != null) {
                        huifuId = fsHfpayConfig.getHuifuId();
                        logger.info("获取到huifuId：{}", huifuId);
                    } else {
                        logger.error("未找到appId对应的汇付配置，appId：{}", payment.getAppId());
                    }
                } else {
                    logger.error("支付记录的appId为空，支付记录ID：{}", payment.getPaymentId());
                }
                
                // 如果没有获取到 huifuId，返回错误
                if (huifuId == null || huifuId.isEmpty()) {
                    return R.error("未找到对应的汇付配置信息，请检查支付记录的appId：" + payment.getAppId());
                }
                
                V2TradePaymentScanpayRefundRequest request = new V2TradePaymentScanpayRefundRequest();
                request.setHuifuId(huifuId);
                request.setOrdAmt(payment.getPayMoney().toString());
                request.setOrgReqDate(new SimpleDateFormat("yyyyMMdd").format(payment.getCreateTime()));
                request.setReqSeqId("refund-"+payment.getPayCode());
                Map<String, Object> extendInfoMap = new HashMap<>();
                extendInfoMap.put("org_req_seq_id", "payment-"+payment.getPayCode());
                request.setExtendInfo(extendInfoMap);
                HuiFuRefundResult refund = huiFuService.refund(request);
                logger.info("退款："+refund);
                if((refund.getResp_code().equals("00000000")||refund.getResp_code().equals("00000100"))&&(refund.getTrans_stat().equals("S")||refund.getTrans_stat().equals("P"))){
                    payment.setRefundMoney(fsStorePayment.getRefundMoney());
                    payment.setStatus(-1);
                    payment.setRefundTime(new Date());
                    payment.setRefundAuditStatus(1); // 1-审核完成
                    fsStorePaymentService.updateFsStorePayment(payment);
                    //收款 减去所有
                    if(payment.getCompanyId()!=null&&payment.getCompanyId()>0){
                        companyService.subCompanyPaymentMoney(payment);
                    }
                    return R.ok();
                }else {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error(refund.getResp_desc());
                }

            }else if (payment.getPayMode()!=null&&payment.getPayMode().equals("wx")){

            }

            //小雨点退款
//            payment.setRefundMoney(fsStorePayment.getRefundMoney());
//            fsStorePaymentService.updateFsStorePayment(payment);
//
//            RefundDTO refundDTO=new RefundDTO();
//            refundDTO.setMerchOrderNo(Ids.oid());
//            refundDTO.setAmount(fsStorePayment.getRefundMoney().toString());
//            refundDTO.setOrigMerchOrderNo("payment-"+payment.getPayCode());
//            return payService.refundOrder(refundDTO);
        }
        else if(payment.getPayTypeCode().equals("alipay")){
            try {
                AliPayApiConfig aliPayApiConfig;
                try {
                    aliPayApiConfig = AliPayApiConfigKit.getApiConfig(aliPayBean.getAppId());
                } catch (Exception e) {
                    aliPayApiConfig = AliPayApiConfig.builder()
                            .setAppId(aliPayBean.getAppId())
                            .setAliPayPublicKey(aliPayBean.getPublicKey())
                            .setAppCertPath(aliPayBean.getAppCertPath())
                            .setAliPayCertPath(aliPayBean.getAliPayCertPath())
                            .setAliPayRootCertPath(aliPayBean.getAliPayRootCertPath())
                            .setCharset("UTF-8")
                            .setPrivateKey(aliPayBean.getPrivateKey())
                            .setServiceUrl(aliPayBean.getServerUrl())
                            .setSignType("RSA2")
                            // 普通公钥方式
                            .build();
                    // 证书模式
//					.buildByCert();
                }
                AliPayApiConfigKit.putApiConfig(aliPayApiConfig);
                AlipayTradeRefundModel model = new AlipayTradeRefundModel();
                model.setOutTradeNo("payment-"+payment.getPayCode());
                model.setTradeNo(payment.getTradeNo());
                model.setRefundAmount(fsStorePayment.getRefundMoney().toString());
                model.setRefundReason("退款");
                String result= AliPayApi.tradeRefundToResponse(model).getBody();
                cn.hutool.json.JSONObject json= JSONUtil.parseObj(result);
                cn.hutool.json.JSONObject jsonInfo= (cn.hutool.json.JSONObject) json.get("alipay_trade_refund_response");
                String code=(String)jsonInfo.get("code");
                String msg=(String)jsonInfo.get("sub_msg");
                //{"alipay_trade_refund_response":{"code":"10000","msg":"Success","buyer_logon_id":"270***@qq.com","buyer_user_id":"2088402776950529","fund_change":"Y","gmt_refund_pay":"2022-04-27 18:27:28","out_trade_no":"goods-202204271826530001","refund_fee":"0.10","send_back_fee":"0.00","trade_no":"2022042722001450521456255417"},"sign":"hU+dy17/juMYQEQpO7Yy7jxkx9h5ebSbN3xdZr58msfOfJEUknqra6w4L37pgoZSx1Vj00jK3Ds06vrph6mSEliq3PQ37PwbZiRK3ZHaaKlz+9ndjoBTFYAxP60zLASfTq+W+dczDq4KOrvwhprFGt7YwKXGU42PgfOPb5EOgWyYUP6ivP0r06OzTo0f2lB28w6AQ4m4IQjdIL/tWbDaKl+ld8MPMLIgw5k9BmMcP8LV8ENC6+Gl1u5GwgAMjwHfk0RfB/kTFTHUTa7fgaO22w3pT8YKFMnOdKA0cVuJ2LE4SdxepqlprWJdCtLOeoQUX6PkEtoJGywPWAyjgdJ6Pg=="}
                if(code.equals("10000")){
                    payment.setRefundMoney(fsStorePayment.getRefundMoney());
                    fsStorePaymentService.updateFsStorePayment(payment);
                    fsStorePaymentService.refund(payment.getPayCode());
                    return R.ok("退款成功");

                }
                else{
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("退款失败:"+msg);

                }
                //退款成功
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        }
        return R.error("非法操作");
    }


    /**
     * 退款审核
     */
    @PreAuthorize("@ss.hasPermi('store:storePayment:refundAudit')")
    @Log(title = "退款审核", businessType = BusinessType.UPDATE)
    @PutMapping("/refund/audit")
    public R auditRefund(@RequestBody Map<String, Object> auditData)
    {
        Long paymentId = Long.valueOf(auditData.get("paymentId").toString());
        Integer auditStatus = Integer.valueOf(auditData.get("refundAuditStatus").toString());
        String auditRemark = auditData.get("auditRemark") != null ? auditData.get("auditRemark").toString() : "";
        String auditor = auditData.get("auditor") != null ? auditData.get("auditor").toString() : "";

        return fsStorePaymentService.auditRefund(paymentId, auditStatus, auditRemark , auditor);
    }

}
