package com.fs.app.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.config.FSSysConfig;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.spring.SpringUtils;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.erp.service.IErpOrderService;
import com.fs.huifuPay.domain.HuiFuResult;
import com.fs.huifuPay.dto.*;
import com.fs.pay.pay.domain.OrderCallback;
import com.fs.pay.pay.domain.OrderResult;
import com.fs.pay.pay.dto.OrderQueryDTO;
import com.fs.pay.pay.service.PayService;
import com.fs.pay.pay.util.PayUtil;
import com.fs.pay.service.dto.PayNotifyDTO;
import com.fs.pay.service.dto.RefundNotifyDTO;
import com.fs.pay.service.dto.TradeOrder;
import com.fs.store.domain.FsStorePayment;
import com.fs.store.domain.TzConfigInfoDTO;
import com.fs.store.service.*;
import com.fs.store.vo.PrescribeVO;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.tzBank.TzBankService;
import com.fs.tzBank.dto.TzOrderInfoDTO;
import com.fs.tzBank.dto.TzPaymentResultDTO;
import com.fs.tzBank.dto.TzRefundOrderDTO;
import com.fs.tzBank.utils.TzConfigUtils;
import com.google.gson.Gson;
import com.tzbank.util.CallBackUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api("第三方支付接口")
@RestController
@RequestMapping("/app/pay")
public class PayController {

    protected final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IFsStoreOrderService orderService;
    @Autowired
    private IFsStoreOrderStatusService orderStatusService;
    @Autowired
    private IFsUserBillService billService;
    @Autowired
    private IFsUserService userService;
    @Autowired
    private ApplicationEventPublisher publisher;

    @Autowired
    private FSSysConfig sysConfig;
    @Autowired
    IErpOrderService erpOrderService;

    @Autowired
    private IFsStoreOrderItemService storeOrderItemService;

    @Autowired
    private IFsStorePaymentService storePaymentService;
    @Autowired
    private IFsExpressService expressService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    PayService ybPayService;

    @Autowired
    TzBankService tzBankService;

    @Autowired
    private ICompanyUserService companyUserService;

    @ApiOperation("台州银行第三方支付回调")
    @PostMapping(value="/tzBkPayNotify")
    public String tzBkPayNotify( @RequestBody String  decryptForm ) throws Exception {

        TzConfigInfoDTO tzConfigInfoDTO = TzConfigUtils.getConfig();

        String decrypt = CallBackUtil.decrypt( tzConfigInfoDTO.getAppSecret(),decryptForm);
        logger.info("台州银行第三方支付回调接口被调用，请求参数: {}", decrypt);

        String filteredString = decrypt.replaceAll("[^\\x20-\\x7E]", "");
        Gson gson = new Gson();
        TzPaymentResultDTO tzPaymentResultDTO = gson.fromJson(filteredString, TzPaymentResultDTO.class);
        //验证
        if(tzPaymentResultDTO.getStatus().equals("90")){
            String orderId = tzPaymentResultDTO.getOrderNo().replace("store","");
            if(StringUtils.isNotBlank(orderId)){
                orderService.payConfirm(1, null, tzPaymentResultDTO.getOrderNo(),
                        tzPaymentResultDTO.getOrderFlowNo(),tzPaymentResultDTO.getChlTrxId(),tzPaymentResultDTO.getOrderFlowNo());
            }
        }
        return "success";

    }
    @ApiOperation("台州银行第三方退款回调")
    @PostMapping(value="/tzRefundNotify")
    public String tzRefundNotify(@RequestBody String  decryptForm) throws Exception {
        TzConfigInfoDTO tzConfigInfoDTO = TzConfigUtils.getConfig();

        String decrypt = CallBackUtil.decrypt( tzConfigInfoDTO.getAppSecret(),decryptForm);
        logger.info("台州银行第三方退款回调，请求参数: {}", JSON.toJSONString(decrypt));

//        if(dto.getRefundOrdStatus().equals("90")){
//            FsStorePayment storePayment=storePaymentService.selectFsStorePaymentByCode(dto.getRefundOrderNo());
//            if(storePayment!=null){
//                storePaymentService.refund(dto.getRefundOrderNo());
//                Long orderId = storePayment.getOrderId();
//                orderService.refundOrder(orderId);
//            }
//            return "success";
//        }
        return "success";
    }

    @ApiOperation("易宝第三方支付回调")
    @PostMapping(value="/ybPayNotify")
    public String ybPayNotify( @RequestBody String jsonBody ) throws Exception {
        //验证
        OrderCallback o= JSONUtil.toBean(jsonBody, OrderCallback.class);
        if(o.getState().equals("0")){
            OrderQueryDTO orderQueryDTO = new OrderQueryDTO();
            orderQueryDTO.setLowOrderId(o.getLowOrderId());
            OrderResult orderResult = ybPayService.getOrder(orderQueryDTO);
            String[] order=o.getLowOrderId().split("-");
            switch (order[0]) {
                case "store":
                    return orderService.payConfirm(1,null,order[1], o.getUpOrderId(),orderResult.getBankTrxId(),orderResult.getBankOrderId());
                case "store_remain":
                    return orderService.payRemainConfirm( order[1], o.getUpOrderId(),orderResult.getBankTrxId(),orderResult.getBankOrderId());
                case "payment":
                    return storePaymentService.payConfirm(order[1],o.getUpOrderId(),orderResult.getBankTrxId(),orderResult.getBankOrderId());
            }
        }
        return "";

    }
    @ApiOperation("汇付第三方支付回调")
    @PostMapping(value="/hfPayNotify")
    public String hfPayNotify(@RequestParam String resp_desc, @RequestParam String resp_code, @RequestParam String sign, @RequestParam String resp_data) throws Exception {
        //验证
        HuiFuResult o = JSON.parseObject(resp_data, HuiFuResult.class);
        logger.info("汇付支付回调:"+o);
        if(o.getResp_code().equals("00000000")){
            String[] order=o.getReq_seq_id().split("-");
            switch (order[0]) {
                case "store":
                    return orderService.payConfirm(1,null,order[1], o.getHf_seq_id(),o.getOut_trans_id(),o.getParty_order_id());
                case "store_remain":
                    return orderService.payRemainConfirm( order[1], o.getHf_seq_id(),o.getOut_trans_id(),o.getParty_order_id());
                case "payment":
                    return storePaymentService.payConfirm(order[1],o.getHf_seq_id(),o.getOut_trans_id(),o.getParty_order_id());
            }

        }
        return "ok";
    }


    @ApiOperation("小雨点第三方支付回调")
    @PostMapping(value="/payNotify")
    public String payNotify(HttpServletRequest request,PayNotifyDTO dto) throws Exception {
            if("SUCCESS".equals(dto.getOrderStatus())) {
                //订单号
                String tradeNo = dto.getMerchOrderNo();
                List<TradeOrder> tradeOrders= JSON.parseArray(dto.getTradeOrders(),TradeOrder.class);
                if(tradeOrders!=null&&tradeOrders.size()>0){
                    for(TradeOrder tradeOrder:tradeOrders){
                        String[] order=tradeOrder.getSubMerchOrderNo().split("-");
                        switch (order[0]) {
                            case "store":
                                orderService.payConfirm(1,null,order[1], tradeNo,dto.getBankTransactionId(),dto.getBankSerialNo());
                                return "success";
                            case "store_remain":
                                orderService.payRemainConfirm( order[1], tradeNo,dto.getBankTransactionId(),dto.getBankSerialNo());
                                return "success";
                            case "payment":
                                return storePaymentService.payConfirm(order[1], tradeNo,dto.getBankTransactionId(),dto.getBankSerialNo());
                        }
                    }
                }
            }
            return "success";
    }

    @ApiOperation("小雨点第三方退款回调")
    @PostMapping(value="/refundNotify")
    public String refundNotify(HttpServletRequest request, RefundNotifyDTO dto) throws Exception {
        if("SUCCESS".equals(dto.getOrderStatus())) {
            String[] orderIds=dto.getOrigMerchOrderNo().split("-");
            FsStorePayment storePayment=null;
            switch (orderIds[0]) {
                case "store":
                    storePayment=storePaymentService.selectFsStorePaymentByCode(orderIds[1]);
                    if(storePayment!=null){
                        storePayment.setRefundMoney(BigDecimal.valueOf(Double.parseDouble(dto.getAmount())));
                        storePayment.setStatus(-1);
                        storePayment.setRefundTime(new Date());
                        storePaymentService.updateFsStorePayment(storePayment);
                    }
                    return "success";
                case "store_remain":
                    storePayment=storePaymentService.selectFsStorePaymentByCode(orderIds[1]);
                    if(storePayment!=null){
                        storePayment.setRefundMoney(BigDecimal.valueOf(Double.parseDouble(dto.getAmount())));
                        storePayment.setStatus(-1);
                        storePayment.setRefundTime(new Date());
                        storePaymentService.updateFsStorePayment(storePayment);
                    }
                    return "success";
                case "doctor":
                   return "success";
                case "payment":
                    storePaymentService.refund(orderIds[1]);
                    return "success";
            }
            return "success";
        }
        return "success";
    }


//    @Transactional
//    public String paymentOp(String payCode,String tradeNo,String bankTransactionId,String bankSerialNo) {
//
//        //更新订单状态
//        FsStorePayment storePayment=storePaymentService.selectFsStorePaymentByCode(payCode);
//        if(!storePayment.getStatus().equals(0)){
//            return "";
//        }
//        storePayment.setStatus(1);
//        storePayment.setPayTime(new Date());
//        storePayment.setTradeNo(tradeNo);
//        storePayment.setBankSerialNo(bankSerialNo);
//        storePayment.setBankTransactionId(bankTransactionId);
//        storePaymentService.updateFsStorePayment(storePayment);
//        //增加佣金
//        if(storePayment.getCompanyId()!=null&&storePayment.getCompanyId()>0){
//            companyService.addCompanyPaymentMoney(storePayment);
//        }
//        return "success";
//
//    }


}
