package com.bohuikeji.delivery.backstage.controller.api.pay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.StreamUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.TOrderCircu;
import com.bohuikeji.delivery.backstage.entity.TPay;
import com.bohuikeji.delivery.backstage.entity.TSettle;
import com.bohuikeji.delivery.backstage.listener.pay.KuaiShouListener;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.utils.kuaishou.kuaishouSign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;


/**
 * @author zhouliwu
 * 客户抖音小程序相关接口
 */
@Slf4j
@Api(tags = {"客户快手小程序相关接口"})
@RestController
@RequestMapping("/api/v2/kuaishou")
@RequiredArgsConstructor
public class KuaiShouV2Api extends ApiController {

    private static final String byteLoginUrl = "https://developer.toutiao.com/api/apps/v2/jscode2session";//字节跳动小程序登陆请求地址

    @Autowired
    ITOrderService itOrderService;
    @Autowired
    ITPayService payService;
    @Autowired
    ITCustomerService customerService;
    @Autowired
    ITOrderService orderService;
    @Autowired
    ITRefundService refundService;
    @Autowired
    ITCustomerAddressService itCustomerAddressService;
    @Autowired
    ISysConfigService sysConfigService;
    @Autowired
    ITCourierService courierService;
    @Autowired
    ITNewsService newsService;
    @Autowired
    IWxUserService wxUserService;
    @Autowired
    IGmsService gmsService;
    @Autowired
    ITSettleService settleService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    MqTool mqTool;


    /**
     * 快手小程序支付
     * @param
     * @return
     * @throws Exception
     */
    @ApiOperation("快手小程序支付、退款异步回调接口，前端不需要接入")
    @PostMapping("/pay/notify")
    public JSONObject douyinPayNotify(HttpServletRequest request) throws Exception {
        JSONObject jsonObject= new JSONObject();
        String date = StreamUtil.readText(request.getInputStream());
        JSONObject strjson= JSONObject.parseObject(date);
        log.info("快手小程序调起支付回调验签1：{}",request.getHeader("kwaisign"));
        log.info("快手小程序调起支付回调验签2：{}",kuaishouSign.checkSign(date));
        if(!request.getHeader("kwaisign").equals(kuaishouSign.checkSign(date))){
            return null;
        }
        if("PAYMENT".equals(strjson.getString("biz_type"))){
            mqTool.sendMsg(strjson, KuaiShouListener.class);
        }
        if("REFUND".equals(strjson.getString("biz_type"))){
            JSONObject msgjson= strjson.getJSONObject("data");
            TPay tPay = payService.getOne(new QueryWrapper<TPay>().eq("pay_channel_num",msgjson.getString("ks_order_no")).eq("pay_status","已支付"));
            log.info("快手小程序支付记录：[{}]", tPay);
            TOrder tOrder = orderService.getOne(new QueryWrapper<TOrder>().eq("order_num",tPay.getMerchantNum()));
            refundService.wxAltRefund(null,null,null,null,msgjson,tOrder,tPay,null,"业务支付退款");
            TOrderCircu.insertCircu(tOrder);
        }
        jsonObject.put("result",1);
        jsonObject.put("message_id",strjson.getString("message_id"));
        return jsonObject;
    }

    /**
     * 快手订单结算回调
     * @param
     * @return
     * @throws Exception
     */
    @ApiOperation("快手订单结算回调")
    @PostMapping("/get/pay/settle")
    public JSONObject getPaySettle(@RequestBody String date) throws IOException {
        JSONObject jsonObject= new JSONObject();
        JSONObject strjson= JSONObject.parseObject(date);
        log.info("抖音小程序交易分账回调信息：[{}]", strjson);
        JSONObject msgjson= JSONObject.parseObject(strjson.getString("data"));
        TSettle settle = settleService.getOne(new QueryWrapper<TSettle>().eq("settle_status","待分账").eq("pay_channel_num", msgjson.getString("ks_order_no")));
        if(msgjson.getString("status").equals("SUCCESS") && settle != null){
            settle.setSettleStatus("已分账");
            settle.setSettleTime(LocalDateTime.now());
            settleService.updateById(settle);
        }
        jsonObject.put("result",1);
        jsonObject.put("message_id",strjson.getString("message_id"));
        return jsonObject;
    }


    /**
     * 支付订单记录查询
     * @param
     * @return
     * @throws Exception
     */
   /* @ApiOperation("支付订单记录查询")
    @PostMapping("/get/order/pay")
    public APIEntity refundNotify(@RequestAttribute("JwtUserId") Integer id,String startDate, String endDate, String type){
        String jsonObject=null;
        log.info("@@@@@@@@时开始时间：{}，结束时间：{}，查询类型：{}",startDate.replaceAll("-",""),endDate.replaceAll("-",""),type);
        jsonObject = BytePay.getOrderPayRecord(startDate.replaceAll("-",""),endDate.replaceAll("-",""),type);
        log.info("抖音交易数据返回：{}",jsonObject);
        return APIEntity.success(jsonObject);
    }*/



}
