package main

import (
	"flag"
	"fmt"
	"net/http"
	_ "net/http/pprof"
	"os"
	"time"

	"git.rosy.net.cn/jx-callback/business/enterprise"
	"git.rosy.net.cn/jx-callback/business/partner/purchase/jdshop"

	"git.rosy.net.cn/jx-callback/business/partner/purchase/yb"

	"github.com/astaxie/beego/server/web"

	"git.rosy.net.cn/baseapi/platformapi/dingdingapi"
	"git.rosy.net.cn/baseapi/utils"

	_ "git.rosy.net.cn/jx-callback/globals/api/apimanager"

	"git.rosy.net.cn/jx-callback/business/jxcallback/orderman"
	"git.rosy.net.cn/jx-callback/business/jxcallback/scheduler/defsch" // 导入缺省订单调度器
	"git.rosy.net.cn/jx-callback/business/jxstore/cms"
	"git.rosy.net.cn/jx-callback/business/jxstore/misc"
	"git.rosy.net.cn/jx-callback/business/jxutils/tasks"
	"git.rosy.net.cn/jx-callback/business/partner/purchase/ebai"
	"git.rosy.net.cn/jx-callback/business/partner/purchase/mtwm"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
	"git.rosy.net.cn/jx-callback/globals/api2"
	"git.rosy.net.cn/jx-callback/globals/beegodb"

	_ "git.rosy.net.cn/jx-callback/business/partner/printer/feie"
	_ "git.rosy.net.cn/jx-callback/business/partner/printer/jxprint"
	_ "git.rosy.net.cn/jx-callback/business/partner/printer/trendit"
	_ "git.rosy.net.cn/jx-callback/business/partner/printer/xiaowm"
	_ "git.rosy.net.cn/jx-callback/business/partner/printer/xpyun"
	_ "git.rosy.net.cn/jx-callback/business/partner/printer/yilianyun"
	_ "git.rosy.net.cn/jx-callback/business/partner/printer/zhongwu"

	_ "git.rosy.net.cn/jx-callback/business/auth2/authprovider/alipay"
	_ "git.rosy.net.cn/jx-callback/business/auth2/authprovider/dingding"
	_ "git.rosy.net.cn/jx-callback/business/auth2/authprovider/douyin"
	_ "git.rosy.net.cn/jx-callback/business/auth2/authprovider/kuaishou"
	_ "git.rosy.net.cn/jx-callback/business/auth2/authprovider/mobile"
	_ "git.rosy.net.cn/jx-callback/business/auth2/authprovider/password"
	_ "git.rosy.net.cn/jx-callback/business/auth2/authprovider/weixin"
	_ "git.rosy.net.cn/jx-callback/business/enterprise"
	_ "git.rosy.net.cn/jx-callback/business/jxcallback/auto_delivery"
	_ "git.rosy.net.cn/jx-callback/business/jxstore/act"
	_ "git.rosy.net.cn/jx-callback/business/model/dao"
	_ "git.rosy.net.cn/jx-callback/business/partner/purchase/ebai"
	_ "git.rosy.net.cn/jx-callback/business/partner/purchase/jd"
	_ "git.rosy.net.cn/jx-callback/business/partner/purchase/jx"
	_ "git.rosy.net.cn/jx-callback/business/partner/purchase/mtwm"
	_ "git.rosy.net.cn/jx-callback/business/partner/purchase/weimob/wsc"

	_ "git.rosy.net.cn/jx-callback/routers"
)

var (
	GitCommit  string
	GitBranch  string
	GitState   string
	GitSummary string
	BuildDate  string
	Version    string
)

func Init() {
	beegodb.Init()
	if globals.EnableWXAuth2 {
		api2.Init()
	}

	defsch.Init()
	buildTime, err := time.ParseInLocation(time.RFC3339, BuildDate, time.UTC)
	if err == nil {
		buildTime = buildTime.Local()
	}
	cms.InitServiceInfo(Version, buildTime, GitCommit)

	if globals.IsProductEnv() {
		ebai.CurPurchaseHandler.StartRefreshComment()
		mtwm.CurPurchaseHandler.StartRefreshComment()
		yb.CurPurchaseHandler.StartRefreshComment()
		jdshop.CurPurchaseHandler.StartRefreshComment()
	}
	misc.Init()
	enterprise.Init() // 初始化enterprise key
}

// 返回true表示非运行服务
func checkCmdFlags() bool {
	var flagGitCommit bool
	var flagGitBranch bool
	var flagGitState bool
	var flagGitSummary bool
	var flagBuildDate bool
	var flagVersion bool
	var flagFullInfo bool

	flag.BoolVar(&flagGitCommit, "gitcommit", false, "get gitcommit info")
	flag.BoolVar(&flagGitBranch, "gitbranch", false, "get gitbranch info")
	flag.BoolVar(&flagGitState, "gitstate", false, "get gitstate info")
	flag.BoolVar(&flagGitSummary, "gitsummary", false, "get gitsummary info")
	flag.BoolVar(&flagBuildDate, "builddate", false, "get builddate info")
	flag.BoolVar(&flagVersion, "version", false, "get version info")
	flag.BoolVar(&flagFullInfo, "fullinfo", false, "get fullinfo info")
	flag.Parse()

	if flagGitCommit || flagFullInfo {
		fmt.Println(GitCommit)
	}
	if flagGitBranch || flagFullInfo {
		fmt.Println(GitBranch)
	}
	if flagGitState || flagFullInfo {
		fmt.Println(GitState)
	}
	if flagGitSummary || flagFullInfo {
		fmt.Println(GitSummary)
	}
	if flagBuildDate || flagFullInfo {
		fmt.Println(BuildDate)
	}
	if flagVersion || flagFullInfo {
		fmt.Println(Version)
	}

	return len(os.Args) > 1
}

func main() {
	if !checkCmdFlags() {
		Init()
		if err := tasks.RefreshWeixinToken(); err != nil {
			globals.SugarLogger.Errorf("RefreshWeixinToken failed with error:%s", err)
			return
		}
		if err := tasks.RefreshWeixin2Token(); err != nil {
			globals.SugarLogger.Errorf("RefreshWeixin2Token failed with error:%s", err)
			return
		}
		if err := tasks.RefreshWeixin3Token(); err != nil {
			globals.SugarLogger.Errorf("RefreshWeixin3Token failed with error:%s", err)
			return
		}

		if err := tasks.RefreshYilianyunToken(); err != nil {
			globals.SugarLogger.Errorf("RefreshYilianyunToken failed with error:%s", err)
			return
		}

		if err := tasks.RefreshFnToken(); err != nil {
			globals.SugarLogger.Errorf("RefreshFnToken failed with error:%s", err)
			return
		}
		if err := tasks.RefreshQywxToken(); err != nil {
			globals.SugarLogger.Errorf("RefreshQywxToken failed with error:%s", err)
			return
		}

		// if globals.IsProductEnv() {
		// 	orderman.SaveJdsOrders(nil, time.Now().Add(-2*time.Hour), time.Now())
		// }
		orderman.LoadPendingOrders()

		// 延时的原因是等回调准备好
		if globals.IsProductEnv() || web.BConfig.RunMode == "beta" {
			utils.AfterFuncWithRecover(2*time.Second, func() {
				if err := tasks.RefreshDingDingToken(); err != nil {
					globals.SugarLogger.Errorf("RefreshDingDingToken failed with error:%s", err)
					return
				}
				if globals.IsProductEnv() {
					api.DingDingAPI.DeleteCallback()
					if err := api.DingDingAPI.RegisterCallback([]string{dingdingapi.CBTagUserAddOrg, dingdingapi.CBTagUserModifyOrg, dingdingapi.CBTagUserLeaveOrg}, web.AppConfig.DefaultString("dingdingCallbackToken", ""), web.AppConfig.DefaultString("dingdingCallbackAESKey", ""), web.AppConfig.DefaultString("dingdingCallbackURL", "")); err != nil {
						globals.SugarLogger.Warnf("dingding RegisterCallback failed with error:%v", err)
					}
				}
			})
		}

		if web.BConfig.RunMode != "prod" {
			web.BConfig.WebConfig.DirectoryIndex = true
			web.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
		}
		go func() {
			if globals.IsMainProductEnv() {
				http.ListenAndServe("0.0.0.0:6061", nil)
			} else {
				http.ListenAndServe("0.0.0.0:6060", nil)
			}
		}()
		web.Run()
	}
}
