package services

import (
	"bytes"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"gin-vue-admin/common"
	"gin-vue-admin/global"
	"gin-vue-admin/models"
	"gin-vue-admin/repository"
	"io/ioutil"
	"net/http"
)

func GetPayMealListService(phone string) (interface{}, error) {

	return repository.GetPayMealListRepository(phone)
}

func QueryState(phone string) (interface{}, error) {

	db, err := common.NewAccountConn()
	if err != nil {
		return nil, err
	}

	chainID, hospitalID, _, err := repository.QueryUserWxInfo(db, phone)
	if err != nil {
		return nil, err
	}

	return repository.QueryDoctorState(db, chainID, hospitalID)
}

func QueryBillState(code string) (interface{}, error) {

	db, err := common.NewAccountConn()
	if err != nil {
		return nil, err
	}

	return repository.QueryBillState(db, code)
}

func PurchaseMeal(phone string, m *models.DoctorPurchase, sourceType string) (interface{}, error) {

	db, err := common.NewAccountConn()
	if err != nil {
		return nil, err
	}

	return SmallProgramPay(db, phone, m, sourceType)
}

func SmallProgramPay(db *sql.DB, phone string, m *models.DoctorPurchase, sourceType string) (interface{}, error) {

	// 查询chain id  和 hospital id
	chainID, hospitalID, openID, err := repository.QueryUserWxInfo(db, phone)
	if err != nil {
		return nil, err
	}
	if openID == "" {
		return nil, errors.New("需要绑定微信后才能支付")
	}

	// 查询套餐价格
	mealInfo, err := repository.QueryMealInfo(db, m.MealID)
	if err != nil {
		return nil, err
	}

	tx, err := db.Begin()
	if err != nil {
		return nil, err
	}

	// 写入 订单中
	billID, err := repository.InsertBDoctorBill(tx, chainID, hospitalID, mealInfo)
	if err != nil {
		return nil, err
	}

	noticeURL := global.GVA_CONFIG.DoctorPay.Url
	var appId string
	des := "谛宝宠医"
	if sourceType == "2" {
		appId = global.GVA_CONFIG.Bkwx.Appid
		des = "必康宠医"
	} else {
		appId = global.GVA_CONFIG.Wx.Appid
	}

	global.GVA_LOG.Info("sourceType 为" + sourceType)
	global.GVA_LOG.Info("appId 为" + appId)

	// mealInfo.Money
	// 吊起支付接口
	purchaseDoctor := &models.PurchaseDoctor{
		AttachInfo:   "",
		GoodsDes:     des + "购买",
		GoodsDetail:  des + "购买",
		GoodsPrice:   mealInfo.Money,
		SourceCode:   2,
		NoticeURL:    noticeURL,
		PayType:      1,
		PlatformType: 3,
		PlatformInfo: des + "购买",
		OpenID:       m.OpenId,
		AppID:        appId,
		IsServe:      1,
		SubMchid:     "1636001492",
	}

	param, err := json.Marshal(purchaseDoctor)
	if err != nil {
		_ = tx.Rollback()
		return nil, err
	}

	reader := bytes.NewReader(param)

	payURL := global.GVA_CONFIG.Pay.UnifiedOrder

	request, err := http.NewRequest("POST", payURL, reader)
	if err != nil {
		_ = tx.Rollback()
		return nil, err
	}
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		_ = tx.Rollback()
		return nil, err
	}
	defer response.Body.Close()
	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		_ = tx.Rollback()
		return nil, err
	}

	temp := &models.PayRes{}
	err = json.Unmarshal(responseBody, &temp)
	if err != nil {
		_ = tx.Rollback()
		return nil, err
	}

	if temp.Code != 0 {
		return nil, errors.New(temp.Message)
	}

	_, err = repository.UpdateBDoctorBill(tx, temp.Data.OutTradeNo, billID)
	if err != nil {
		tx.Rollback()
		return nil, err
	}

	_ = tx.Commit()

	fmt.Println("pay.Data: ", temp.Data)

	return temp.Data, nil
}

func PayNoticeService(p *models.NoticeRequest) error {

	db, err := common.NewAccountConn()
	if err != nil {
		return err
	}

	// 查询订单相关信息
	info, err := repository.QueryBDoctorBillInfo(db, p.OutTradeNo)
	if err != nil {
		return err
	}

	fmt.Println("bill: ", info.ResultCode)

	if info.ResultCode == 1 {
		return nil
	}

	tx, err := db.Begin()
	if err != nil {
		return err
	}

	// 把订单信息置为 支付成功
	err = repository.UpdateBDoctorBillBySuccess(tx, info.ID)
	if err != nil {
		_ = tx.Rollback()
		return err
	}

	// 更新用户 购买相关信息
	err = repository.UpdateBDoctorHospital(tx, info)
	if err != nil {
		return err
	}

	_ = tx.Commit()

	fmt.Println("更新购买信息成功")

	return nil
}

// 试用
func OnTrial(phone string, m *models.DoctorPurchase) (interface{}, error) {

	db, err := common.NewAccountConn()
	if err != nil {
		return nil, err
	}

	// 查询chain id  和 hospital id
	chainID, hospitalID, openID, err := repository.QueryUserWxInfo(db, phone)
	if err != nil {
		return nil, err
	}
	if openID == "" {
		return nil, errors.New("需要绑定微信后才能支付")
	}

	// 查询套餐价格
	mealInfo, err := repository.QueryMealInfo(db, m.MealID)
	if err != nil {
		return nil, err
	}

	return repository.OnTrail(db, chainID, hospitalID, mealInfo)
}
