package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"gin-vue-admin/global"
	"gin-vue-admin/model/request"
	"io/ioutil"
	"net/http"
	"time"
)

const (
	payType      = 1 //1: 微信
	platformType = 3 //平台类型 1: saas  3:shop mobile
	sourceCode   = 2 //2：微信小程序
)

/**
 * 收银台
 */
func Pay(data *request.OrderPayReq, payNum int) (interface{}, error) {
	des := "谛医" //描述
	if data.UserType == 2 {
		des = "必康"
	}

	if data.UserCharacter != 0 {
		des = "谛医-远程判读" //描述
		if data.UserType == 2 {
			des = "必康-远程判读"
		}
	}

	//支付信息
	paymentInfo := make(map[string]interface{})
	paymentInfo["app_id"] = &global.GVA_CONFIG.Wx.Appid

	if data.UserType == 2 {
		paymentInfo["app_id"] = &global.GVA_CONFIG.Bkwx.Appid
	}

	paymentInfo["attach_info"] = data.OrderNo
	paymentInfo["goods_des"] = des
	paymentInfo["goods_detail"] = des
	paymentInfo["goods_price"] = data.PayMoney
	paymentInfo["notice_url"] = &global.GVA_CONFIG.Pay.PayCallBack
	paymentInfo["open_id"] = data.Openid
	paymentInfo["pay_type"] = payType
	paymentInfo["platform_info"] = des
	paymentInfo["platform_type"] = platformType
	paymentInfo["source_code"] = sourceCode
	fmt.Println("payConf:", payNum)
	if payNum == 1 {
		paymentInfo["sub_mchid"] = &global.GVA_CONFIG.Wx.Mchid
	} else if payNum == 2 {
		paymentInfo["is_serve"] = 1
		paymentInfo["sub_mchid"] = &global.GVA_CONFIG.Bkwx.Mchid
	} else {
		paymentInfo["is_serve"] = 1
		paymentInfo["sub_mchid"] = &global.GVA_CONFIG.Bkwx.Mchid
	}
	//发起支付
	payUrl := global.GVA_CONFIG.Pay.UnifiedOrder

	result := PayPost(payUrl, paymentInfo, "")

	return result, nil
}

func PayPost(url string, data interface{}, token string) string {
	// 超时时间：10秒
	client := &http.Client{Timeout: 10 * time.Second}
	fmt.Println("请求地址：" + url)

	jsonStr, _ := json.Marshal(data)
	fmt.Println("请求数据：" + string(jsonStr))

	reqest, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))

	if token != "" {
		reqest.Header.Add("Authorization", "Bearer "+token)
		fmt.Println("token：" + token)
	}
	reqest.Header.Add("Content-Type", "application/json")
	reqest.Header.Add("Connection", "keep-alive")
	if err != nil {
		fmt.Println("PayPost Err:", err)
		panic(err)
	}

	resp, _ := client.Do(reqest)
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)

	fmt.Println("返回数据：" + string(result))
	return string(result)
}
