package com.miaxis.app.controller.applePay;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.miaxis.applepay.domain.ApplepayOrder;
import com.miaxis.applepay.dto.ApplePayDTO;
import com.miaxis.applepay.service.IApplepayOrderService;
import com.miaxis.common.constant.Constants;
import com.miaxis.common.core.controller.BaseController;
import com.miaxis.common.core.domain.Response;
import com.miaxis.common.core.domain.entity.SysDictData;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.utils.IosVerifyUtil;
import com.miaxis.order.service.IOrderInfoService;
import com.miaxis.system.service.ISysDictDataService;
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 java.util.ArrayList;
import java.util.List;

/**
 * 【小程序-微信支付】Controller
 *
 * @author miaxis
 * @date 2021-03-10
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(Constants.OPEN_PREFIX+"/applepay")
@Api(tags = {"【APP-苹果支付】"})
@Slf4j
public class ApplePayController extends BaseController {


    @Autowired
    private IosVerifyUtil iosVerifyUtil;

    @Autowired
    private IApplepayOrderService applepayOrderService;

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private ISysDictDataService dictDataService;
    /**
     * TransactionID：苹果配置的产品id
     * String receipt_data:需要客户端传过来的参数2
     * 苹果内购支付
     *
     * @Title: doIosRequest
     * @Description:Ios客户端内购支付
     */
    @ApiOperation("验证订单")
    @PostMapping
    public Response doIosRequest(@RequestBody ApplePayDTO applePayDTO) {
        String receipt_data = applePayDTO.getReceipt_data();
        String transactionID = applePayDTO.getTransaction_id();
        String verifyResult = iosVerifyUtil.buyAppVerify(receipt_data,applePayDTO.getType());
        //苹果服务器没有返回验证结果
        if (verifyResult == null) {
            throw new CustomException("无订单信息");
        } else {
            // 苹果验证有返回结果
            log.info("线上，苹果平台返回JSON:" + verifyResult);
            JSONObject job = JSONObject.parseObject(verifyResult);
            Integer status = job.getInteger("status");
            //如果状态正常
            if (status==0){
                //将订单数据存储到数据库
                JSONObject receipt = job.getJSONObject("receipt");
                JSONArray in_app =  receipt.getJSONArray("in_app");
                List<ApplepayOrder> list  = new ArrayList<ApplepayOrder>();
                for (int i=0; i <in_app.size(); i++){
                    //苹果订单数据持久化
                    JSONObject jo = in_app.getJSONObject(i);
                    ApplepayOrder applepayOrder = JSONObject.toJavaObject(jo,ApplepayOrder.class);

                    ApplepayOrder applepayOrderQuery = new ApplepayOrder();
                    applepayOrderQuery.setTransactionId(applePayDTO.getTransaction_id());
                    int count = applepayOrderService.selectApplepayOrderCount(applepayOrderQuery);
                    if(count>0){
                        throw new CustomException("该订单已支付完成，请勿重新调用。");
                    }
                    //查询套餐
                    int index = applepayOrder.getProductId().lastIndexOf(".");
                    String goodCode = applepayOrder.getProductId().substring(index+1);
                    SysDictData sysDictData = dictDataService.selectDictDataById(Long.parseLong(goodCode));
                    String[] values = sysDictData.getDictValue().split(",");
                    Double price = Double.parseDouble(values[0])*100;
                    int b =  new Double(price).intValue();
                    applepayOrder.setTotal(b);   //设置金额
                    applepayOrder.setGoodsName(sysDictData.getDictLabel());
                    //设置用户
                    applepayOrder.setUserId(applePayDTO.getUserId());
                    applepayOrder.setUserName(applePayDTO.getUserName());



                    orderInfoService.writeVipDataToDb(applepayOrder.getGoodsName(),applepayOrder.getUserId(),applepayOrder.getUserName(),applepayOrder.getTransactionId(),applepayOrder.getTotal(),3);
                    applepayOrderService.save(applepayOrder);
                }
                //todo 业务处理
            }else{
                throw new CustomException("订单支付异常");
            }


        }
        return Response.success();
    }


    public static void main(String[] args) {

        String str = "com.kestrel.JSJPStudent.vip.212";

        int index = str.lastIndexOf(".");
        String goodCode= str.substring(index+1);
        System.out.println(goodCode);

    }








}
