package db

import (
	"applet/app/db/model"
	"applet/app/md"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"

	"xorm.io/xorm"
)

// GetCloudBundleByVersion is 根据版本 获取打包记录
func GetCloudBundleByVersion(Db *xorm.Engine, appverison string, os, ep int) (*model.CloudBundle, error) {
	m := new(model.CloudBundle)
	has, err := Db.Where("version = ? and os = ? and template_during_audit<>'' and ep=?", appverison, os, ep).Get(m)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("not Found")
	}
	return m, nil
}

// GetCloudBundleByVersionPlatform is 根据版本\os 获取打包记录
func GetCloudBundleByVersionPlatform(Db *xorm.Engine, appverison string, platform string, appType string) (*model.CloudBundle, error) {
	m := new(model.CloudBundle)
	var tag int
	var ep = 0
	if platform == "ios" {
		tag = 2
	} else {
		tag = 1
	}
	if appType == "daogou" || appType == "" {
		ep = 0
	} else {
		ep = 1
	}
	has, err := Db.Where("version = ? and os=? and ep=?", appverison, tag, ep).Desc("build_number").Get(m)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("not Found")
	}
	return m, nil
}

// GetCloudBundleByVersionPlatformWithAudit is 根据版本\os 获取打包记录
func GetCloudBundleByVersionPlatformWithAudit(Db *xorm.Engine, appverison string, platform string, appType string) (*model.CloudBundle, error) {
	m := new(model.CloudBundle)
	var tag int
	var ep = 0
	if platform == "ios" {
		tag = 2
	} else {
		tag = 1
	}
	if appType == "daogou" || appType == "" {
		ep = 0
	} else {
		ep = 1
	}
	has, err := Db.Where("version = ? and os=? and ep=? and template_during_audit<>''", appverison, tag, ep).Desc("build_number").Get(m)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("not Found")
	}
	return m, nil
}
func GetCloudBuild(c *gin.Context, platform string) string {
	appVersion := c.GetHeader("app_version_name")
	ep := 0
	if c.GetString("app_type") != "" && c.GetString("app_type") != "daogou" {
		ep = 1
	}
	if platform == "" {
		platform = c.GetHeader("platform")
	}

	version := ""
	os := 0
	switch platform {
	case md.PLATFORM_ANDROID:
		if ep == 1 {
			version = SysCfgGet(c, "biz_android_audit_version")
		} else {
			version = SysCfgGet(c, "android_audit_version")
		}
		os = 1
	case md.PLATFORM_IOS:
		if ep == 1 {
			version = SysCfgGet(c, "biz_ios_audit_version")
		} else {
			version = SysCfgGet(c, "ios_audit_version")
		}
		os = 2
	}
	var data model.CloudBundle
	get, err := DBs[c.GetString("mid")].Where("is_auditing=1 and os=? and ep=? and version=?", os, ep, appVersion).Get(&data)
	fmt.Println(get)
	fmt.Println(err)
	if data.Version != "" {
		version = data.Version
	}
	return version
}
