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.DouYinListener;
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.douyin.byteSign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
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 javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;


/**
 * @author zhouliwu
 * 客户抖音小程序相关接口
 */
@Slf4j
@Api(tags = {"客户抖音小程序相关接口"})
@RestController
@RequestMapping("/api/v2/byte")
@RequiredArgsConstructor
public class ByteV2Api 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
    RabbitTemplate rabbitTemplate;
    @Autowired
    IGmsService gmsService;
    @Autowired
    ITSettleService settleService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    MqTool mqTool;


    /**
     * 抖音小程序登陆获取用户信息sessionKey
     * @param code 登录凭证
     * @param anonymousCode 匿名登录凭证
     * @return
     */
   /* @ApiOperation("抖音小程序登陆获取用户信息")
    @PostMapping("/get/byte/sessionKey/login")
    public APIEntity getSessionKey(String code,String anonymousCode,String customerPhone,String verCode) {
        Object phCode = redisUtil.get("gms:customer:"+customerPhone);
        if(phCode==null){
            return APIEntity.fail("验证码无效，请重新获取！");
        }
        if("15771335697".equals(customerPhone)){
            if(!"000000".equals(verCode)){
                return APIEntity.fail("验证码错误！");
            }
        }
        else {
            if (!phCode.toString().equals(verCode)){
                return APIEntity.fail("验证码错误！");
            }
        }
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@code：[{}]",code);
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@anonymousCode：[{}]",anonymousCode);
        JSONObject reqJson=new JSONObject();
        reqJson.put("appid", ByteConfig.App_ID);
        reqJson.put("secret",ByteConfig.APP_SECRET);
        reqJson.put("code",code);
        reqJson.put("anonymous_code",anonymousCode);
        String resultJson = HttpRequest.post(byteLoginUrl).bodyText(reqJson.toJSONString(),MimeTypes.MIME_APPLICATION_JSON,"UTF-8").send().contentType("application/json","utf-8").bodyText();
        JSONObject res= JSONObject.parseObject(resultJson);
        log.info("登陆返回：[{}]",res);
        // 获取参数返回的
        JSONObject jes = res.getJSONObject("data");
        TCustomer tCustomer = customerService.getOne(new QueryWrapper<TCustomer>().eq("customer_phone",customerPhone));
        if(tCustomer != null){
            wxUserService.saveUser(jes,tCustomer);
        }else {
            tCustomer = customerService.saveCustomerByPhone("抖音小程序",customerPhone);
            wxUserService.saveUser(jes,tCustomer);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("customerId",tCustomer.getCustomerId());
        jsonObject.put("customerPhone",tCustomer.getCustomerPhone());
        jsonObject.put("token",JwtTokenUtil.createToken("客户",tCustomer.getCustomerId()));
        return APIEntity.success(jsonObject);
    }*/

    /**
     * 抖音小程序支付、退款异步回调接口
     * @param
     * @return
     * @throws Exception
     */
    @ApiOperation("抖音小程序支付、退款异步回调接口，前端不需要接入")
    @PostMapping("/pay/notify")
    public JSONObject douyinPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        JSONObject jsonObject= new JSONObject();
        String str = StreamUtil.readText(request.getInputStream());
        JSONObject strjson= JSONObject.parseObject(str);
        boolean check = byteSign.checkSignature(strjson);
        if(!check){
            return null;
        }
        log.info("抖音小程序调起支付回调验签：[{}]", check);
        if("payment".equals(strjson.getString("type"))){
            mqTool.sendMsg(strjson, DouYinListener.class);
        }
        if("refund".equals(strjson.getString("type"))){
            JSONObject msgjson= JSONObject.parseObject(strjson.getString("msg"));
            TPay tPay = payService.getOne(new QueryWrapper<TPay>().eq("pay_channel_num",msgjson.getString("order_id")).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("err_no",0);
        jsonObject.put("err_tips","success");
        return jsonObject;
    }

    /**
     * 订单分账记录回调
     * @param
     * @return
     * @throws Exception
     */
    @ApiOperation("订单分账记录回调")
    @PostMapping("/get/pay/settle")
    public JSONObject getPaySettle(@RequestBody String str) {
        JSONObject jsonObject= new JSONObject();
        JSONObject strjson= JSONObject.parseObject(str);
        log.info("抖音小程序交易分账回调信息：[{}]", strjson);
        JSONObject msgjson= JSONObject.parseObject(strjson.getString("msg"));
        TSettle settle = settleService.getOne(new QueryWrapper<TSettle>().eq("settle_status","待分账").eq("pay_channel_num", msgjson.getString("order_id")));
        if(msgjson.getString("status").equals("SUCCESS") && settle != null){
            settle.setSettleStatus("已分账");
            settle.setSettleTime(LocalDateTime.now());
            settleService.updateById(settle);
        }
        jsonObject.put("err_no",0);
        jsonObject.put("err_tips","success");
        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);
    }*/



}
