package com.miaxis.app.controller.tt;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.miaxis.common.config.WxpayConfig;
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.UserInfo;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.utils.SecurityUtils;
import com.miaxis.system.service.ISysConfigService;
import com.miaxis.system.service.ISysUserService;
import com.miaxis.tt.domain.TtOrder;
import com.miaxis.tt.service.ITtOrderService;
import com.miaxis.feign.dto.ToutiaoCreatOrderDTO;
import com.miaxis.feign.service.ToutiaoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import static com.miaxis.common.utils.OrderCodeFactory.getOrderCode;
import static com.miaxis.common.utils.ttUtils.getSign;

/**
 * 【小程序-微信支付】Controller
 *
 * @author miaxis
 * @date 2021-03-10
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(Constants.STUDENT_PREFIX+"/tt")
@Api(tags = {"【小程序-头条支付】"})
@Slf4j
public class TtController extends BaseController {

    @Autowired
    private HttpClient httpClient;

    @Autowired
    private WxpayConfig wxpayConfig;

    @Autowired
    private ITtOrderService ttOrderService;

    @Autowired
    private ToutiaoService toutiaoService;
    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService sysUserService;

    @Value("${tt.appid}")
    private String ttappid;
    @Value("${tt.notifyUrl}")
    private  String ttnotifyUrl ;



    /**
     * 微信支付获取预订单id
     */
    @PostMapping(value = "/prepareOrder")
    @ApiOperation("小程序头条支付下单")
    public Response<TtParamEntity> getPrepareOrder() throws Exception{

        //创建本地抖音订单
        TtOrder order = new TtOrder();
        UserInfo student = SecurityUtils.getLoginUser().getStudent();
        String orderCode = getOrderCode(student.getId());
        order.setCpOrderno(orderCode);
        order.setXcxOpenid(student.getXcxOpenid());
        order.setUnionId(student.getUnionId());
        ttOrderService.save(order);
        return Response.success(placeWxOrder(order));


    }




    //下单
    private TtParamEntity placeWxOrder(TtOrder order) throws Exception {
        ToutiaoCreatOrderDTO dto = new ToutiaoCreatOrderDTO();
        dto.setApp_id(ttappid);
        dto.setOut_order_no(order.getCpOrderno());
        dto.setTotal_amount(getTotal());

        dto.setSubject("速达驾考会员");
        dto.setBody("速达驾考会员，可以观看付费内容");
        dto.setValid_time(900);
        dto.setNotify_url(ttnotifyUrl);
        dto.setStore_uid("70963547131799657030");
        dto.setSign(getSign(BeanUtil.beanToMap(dto,false,true)));
        String ttReturnStr = toutiaoService.createOrder(dto);
        System.out.println("tt支付返回"+ttReturnStr);
        return getWxParamJson(ttReturnStr);

    }



    private int getTotal() {
        String price = configService.selectConfigByKey("vip_price");
        Double dprice = Double.valueOf(price);
        Double v =dprice* 100;
        return v.intValue();
    }

    // 生成调用调起微信支付所需参数
    private TtParamEntity getWxParamJson(String bodyAsString) throws Exception {
        JSONObject TtReturn = JSONObject.parseObject(bodyAsString);
        if (TtReturn.getInteger("err_no") != 0){
            throw new CustomException(TtReturn.getString("err_tips"));
        }
        JSONObject data = TtReturn.getJSONObject("data");
        TtParamEntity ttParamEntity = new TtParamEntity();
        ttParamEntity.setOrder_id(data.getString("order_id"));
        ttParamEntity.setOrder_token(data.getString("order_token"));
        return ttParamEntity;
    }

    private HttpPost initHttpPost() {
        HttpPost httpPost = new HttpPost(wxpayConfig.getV3url());
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Content-type","application/json; charset=utf-8");
        return httpPost;
    }

    @Data
    class  TtParamEntity{
        String order_id;
        String order_token;

    }










}
