package svc

import (
	"applet/app/db"
	"applet/app/db/model"
	offical "applet/app/db/official"
	"applet/app/utils"
	"code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/kuaishou"
	"code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/md"
	"encoding/json"
	"fmt"
	"github.com/tidwall/gjson"
	"strings"
	"time"
)

func KuaishouOrder() {
	pvdTimeKey := "kuaishou_time"

	// 获得最后时间
	latest := offical.SysCfgByKey(pvdTimeKey)
	if latest == nil {
		offical.DbsSysCfgInserts(pvdTimeKey, time.Now().String())
		latest = offical.SysCfgByKey(pvdTimeKey)
	}
	// 所有时间都是在操作秒数
	now := time.Now().Unix()
	strs := strings.Split(latest.V, ":")
	timeStr := latest.V
	if len(strs) == 3 {
		timeStr = strs[0] + ":" + strs[1] + ":00"
	}
	fmt.Println(timeStr)
	past := utils.TimeParseStd(timeStr).Unix()
	// 如果上次记录超过30天或者 过去时间大于当前时间戳, 把时间设置为此前20分钟
	if past < now-180*86400 || past > now {
		past = now
	}
	var (
		beginTime         int64  = 0
		endTime           int64  = 0
		pageNo            int    = 1
		pageSize          int    = 50
		nextPositionIndex string = ""
	)

	//怕时间不是走最新的
	leave := now - past
	if leave > 500 {
		leave = 0
	}
	past = past + leave
	beginTime = past - 300
	endTime = past

	if endTime > now {
		endTime = now
	}

	for {
		count := 0
		var positionIndex = ""
		if pageNo == 1 {
			nextPositionIndex = "0"
		}
		if nextPositionIndex != "" {
			count, positionIndex = OrdersKuaishouGet(nextPositionIndex, pageSize, beginTime, endTime, "update", 0)
		}
		if count == 0 {
			nextPositionIndex = ""
			goto ChkArg
		}
		// 判断是否分页已经全部取完了
		if count <= pageSize {
			nextPositionIndex = positionIndex
			pageNo++
			fmt.Println("========下一页========" + utils.IntToStr(pageNo))
			count = 0
			continue
		}
	ChkArg:
		nextPositionIndex = ""

		// 查询完后重置时间, 最后查询时间
		if endTime < now {
			pageNo = 1
			offical.DbsSysCfgUpdate(pvdTimeKey, utils.TimeToStr(endTime))
			beginTime = endTime
			endTime = endTime + 300
			if endTime > now {
				endTime = now
			}
			count = 0
			continue
		}
		count = 0
		break
	}
}

func OrdersKuaishouGet(nextPositionIndex string, pageSize int, sTime, eTime int64, timeType string, pvd int) (int, string) {

	arg := map[string]interface{}{
		"cpsOrderStatus": 0,
		"pageSize":       pageSize,
		"sortType":       2, //排序类型 [1:按指定查询类型降序] [2:按指定查询类型升序]
		"queryType":      2, //查询类型 [1:按分销订单创建时间查询] [2:按分销订单更新时间查询]
		"beginTime":      time.Unix(sTime, 0).Unix() * 1000,
		"endTime":        time.Unix(eTime, 0).Unix() * 1000,
		"pcursor":        nextPositionIndex,
	}
	param, kuaishouData := GetKuaishouKey()
	param["param"] = utils.SerializeStr(arg)
	data, err := kuaishou.GetKuishouCpsOrder(kuaishouData["sign_secret"], param)
	goods := gjson.Get(data, "data.orderList").String()
	newPcursor := gjson.Get(data, "data.pcursor").String()
	if goods == "" || err != nil {
		return 0, ""
	}
	var list = make([]md.KuaishouCpsOrder, 0)
	err = json.Unmarshal([]byte(goods), &list)
	if err != nil {
		return 0, ""
	}
	var kuaishouState = map[int]string{
		30: "订单付款",
		50: "订单完成",
		80: "订单失效",
		60: "订单结算",
	}
	for _, v := range list {
		var res = model.GuideOrder{
			PvdParentOid: utils.IntToStr(v.Oid),
			Pvd:          "kuaishou",
			Status:       kuaishouState[v.CpsOrderStatus],
			CreateTime:   v.OrderCreateTime / 1000,
		}
		if v.SettlementSuccessTime > 0 {
			res.PlatformSettleTime = int(v.SettlementSuccessTime / 1000)
		}
		for _, v1 := range v.CpsKwaimoneyOrderProductView {
			resNew := res
			if v1.CpsType == 3 {
				resNew.Pvd = "kuaishou_live"
			}
			if strings.Contains(v1.Comments, "official_") == false {
				continue
			}
			v1.Comments = strings.ReplaceAll(v1.Comments, "official_", "")
			ex := strings.Split(v1.Comments, "_")
			if len(ex) < 3 {
				continue
			}
			orderType := 0
			if ex[0] == "s" {
				orderType = 1
			}
			// 判断免单
			if ex[0] == "f" {
				orderType = 2
			}
			if ex[0] == "cloud" {
				orderType = 10
			}
			if ex[0] == "sef" {
				orderType = 11
			}
			if ex[0] == "shareSeFree" {
				orderType = 12
			}
			if ex[0] == "moref" {
				orderType = 13
			}
			resNew.Oid = utils.StrToInt64(utils.OrderUUID(utils.StrToInt(ex[1])))
			resNew.PvdOid = utils.IntToStr(v1.Oid)
			resNew.Uid = utils.StrToInt(ex[2])
			resNew.StationUid = utils.StrToInt(ex[1])
			resNew.UpdateTime = int(time.Now().Unix())
			resNew.Commission = utils.Float64ToStr(float64(v1.EstimatedIncome) / 100)
			resNew.RealCommission = utils.Float64ToStr(float64(v1.EstimatedIncome) / 100)
			resNew.Title = v1.ItemTitle
			resNew.Img = v1.ItemPicUrl
			resNew.Gid = utils.IntToStr(v1.ItemId)
			resNew.IsShare = orderType
			resNew.Payment = utils.Float64ToStr(float64(v1.PaymentFee) / 100)
			one := db.GetGuideOrderByOne(resNew.PvdOid, utils.IntToStr(resNew.Uid), resNew.Pvd)
			if one == nil {
				insertOne, err := db.ZhimengDb.InsertOne(&resNew)
				fmt.Println(insertOne)
				fmt.Println(err)
			} else {
				resNew.SettleTime = one.SettleTime
				if one.PlatformSettleTime > 0 {
					resNew.PlatformSettleTime = one.PlatformSettleTime
				}
				db.ZhimengDb.Where("id=?", one.Id).AllCols().Update(&resNew)
			}
		}
	}
	return len(list), newPcursor
}
func GetKuaishouKey() (map[string]string, map[string]string) {
	kuaishouData := CommKuaishou()
	param := map[string]string{
		"appkey":       kuaishouData["appkey"],
		"access_token": kuaishouData["token"],
	}

	return param, kuaishouData
}
func CommKuaishou() map[string]string {
	res := OfficialCommKuaishou()
	return res
}
func OfficialCommKuaishou() map[string]string {
	kuaishouAppkey := offical.MasterListCfgGetOneData("0", "kuaishou_kfx_appkey")
	kuaishouAppSecret := offical.MasterListCfgGetOneData("0", "kuaishou_kfx_app_secret")
	kuaishouSignSecret := offical.MasterListCfgGetOneData("0", "kuaishou_kfx_sign_secret")
	authType := "0"
	kuaishouToken := db.MasterListCfgGetOneData("0", "kuaishou_official_access_token")
	kuaishouPid := offical.MasterListCfgGetOneData("0", "kuaishou_official_pid")
	res := map[string]string{
		"pid":         kuaishouPid,
		"authType":    authType,
		"appkey":      kuaishouAppkey,
		"token":       kuaishouToken,
		"app_secret":  kuaishouAppSecret,
		"sign_secret": kuaishouSignSecret,
	}
	return res
}