package event

import (
	"errors"
	"fmt"
	"regexp"
	"strings"
	"time"

	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
)

var (
	NoUseEventMap = map[string]string{
		"CreateQrOrBarCode":         "CreateQrOrBarCode",
		"StatisticsReportForOrders": "StatisticsReportForOrders",
	}
	regexpToken = regexp.MustCompile(`,"token":".*"`)
)

type CheckCookie struct {
	VendorID      int    `json:"vendorID"`
	VendorOrgCode string `json:"vendorOrgCode"`
	Status        string `json:"status"`
}

func AddOperateEvent(ctx *jxcontext.Context, accessUUID, jsonData string, errCode, errMsg string, useTime int, apiFunctionSpec string) (err error) {
	var (
		apiFunction string
		db          = dao.GetDB()
	)
	// if ctx.GetRequest() == nil {
	// 	return nil
	// }
	if apiFunctionSpec == "" {
		url := ctx.GetRequest().URL.Path
		if url != "" {
			apiFunction = url[strings.LastIndex(url, "/")+1 : len(url)]
		}
	} else {
		apiFunction = apiFunctionSpec
	}
	if apiFunction != "" {
		if apiFunction[0:3] == "Get" || NoUseEventMap[apiFunction] != "" {
			return errors.New("未知错误")
		}
	}
	if accessUUID != "" {
		accessUUID = accessUUID[0:strings.Index(accessUUID, ",")]
	}
	jsonData = strings.ReplaceAll(jsonData, regexpToken.FindString(jsonData), "")
	jsonData = utils.LimitUTF8StringLen(jsonData, 3200)
	errMsg = utils.LimitUTF8StringLen(errMsg, 9999)
	event := &model.OperateEvent{
		CreatedAt:    time.Now(),
		LastOperator: ctx.GetUserName(),
		APIFunction:  apiFunction,
		UserID:       ctx.GetUserID(),
		AccessUUID:   accessUUID,
		JsonData:     jsonData,
		ErrCode:      errCode,
		ErrMsg:       errMsg,
		UseTime:      useTime,
	}
	txDB, err := dao.Begin(db)
	defer func() {
		if r := recover(); r != nil {
			dao.Rollback(db, txDB)
			panic(r)
		}
	}()
	err = dao.CreateEntity(db, event)
	dao.Commit(db, txDB)
	return err
}

func AddOperateEventDetail(db *dao.DaoDB, operateEventDetail *model.OperateEventDetail) (err error) {
	txDB, _ := dao.Begin(db)
	defer func() {
		if r := recover(); r != nil {
			dao.Rollback(db, txDB)
			panic(r)
		}
	}()
	operateEventDetail.BeforeData = utils.LimitUTF8StringLen(operateEventDetail.BeforeData, 3200)
	operateEventDetail.AfterData = utils.LimitUTF8StringLen(operateEventDetail.AfterData, 3200)
	err = dao.CreateEntity(db, operateEventDetail)
	dao.Commit(db, txDB)
	return err
}

func DeleteOperateEventAndDetail(ctx *jxcontext.Context, deleteTime time.Time) (err error) {
	db := dao.GetDB()
	txDB, _ := dao.Begin(db)
	defer func() {
		if r := recover(); r != nil {
			dao.Rollback(db, txDB)
			panic(r)
		}
	}()
	dao.DeleteOperateEventDetail(db, deleteTime)
	dao.DeleteOperateEvent(db, deleteTime)
	dao.Commit(db, txDB)
	return err
}

func GetOperateEvents(ctx *jxcontext.Context, name string, apiFunctions []string, operateTypes, skuIDs, storeIDs []int, fromTime, toTime, keyword string, errType, offset, pageSize int) (pageInfo *model.PagedInfo, err error) {
	var (
		fromTimeP time.Time
		toTimeP   time.Time
	)
	db := dao.GetDB()
	if fromTime != "" {
		fromTimeP = utils.Str2Time(fromTime)
	}
	if toTime != "" {
		toTimeP = utils.Str2Time(toTime)
	}
	pageSize = jxutils.FormalizePageSize(pageSize)
	offset = jxutils.FormalizePageOffset(offset)
	operateEventExt, totalCount, err := dao.GetOperateEvents(db, name, apiFunctions, operateTypes, skuIDs, storeIDs, fromTimeP, toTimeP, keyword, errType, offset, pageSize)
	if err != nil {
		return pageInfo, err
	}
	pageInfo = &model.PagedInfo{
		Data:       operateEventExt,
		TotalCount: totalCount,
	}
	return pageInfo, err
}

func GetCheckVendorCookie(ctx *jxcontext.Context, vendorIDs []int, isAuto bool) (ccList []*CheckCookie, err error) {
	var (
		ebaiOrderID = "1577329467196263592"
		ebaiErr     = "return not json"
		ebaiErr2    = "系统错误"
		mtStoreID   = "7388603"
		mtErr       = "返回结果格式不正常"
		jdUpcCode   = "6952395700895"
		jdErr       = "请输入用户名"
		// mtpsErr     = "用户未登录"
		errMsg = ""
	)
	for _, v := range vendorIDs {
		cc := &CheckCookie{}
		var flag = false
		switch v {
		case model.VendorIDEBAI:
			resultMap, err := api.EbaiAPI.GetStoreOrderInfo(ebaiOrderID)
			if len(resultMap) < 1 && err != nil {
				if strings.Contains(err.Error(), ebaiErr) || strings.Contains(err.Error(), ebaiErr2) {
					errMsg += fmt.Sprintf(" 饿百账号:[%v]的Cookie无效了！", v)
					flag = true
				}
			}
		case model.VendorIDMTWM:
			_, err := api.MtwmAPI.PackagePriceGet(mtStoreID)
			if err != nil {
				if strings.Contains(err.Error(), mtErr) {
					errMsg += fmt.Sprintf(" 美团账号:[%v]的Cookie无效了！", v)
					flag = true
				}
			}
		case model.VendorIDJD:
			result, err := api.JdAPI.GetJdUpcCodeByName("", jdUpcCode, 1, 5)
			if len(result) < 1 && err != nil {
				if strings.Contains(err.Error(), jdErr) {
					errMsg += fmt.Sprintf(" 京东账号:[%v]的Cookie无效了！", v)
					flag = true
				}
			}
		case model.VendorIDJDShop:
			_, err := api.JdShopAPI.OrderDetail("124350112427")
			if err != nil {
				if strings.Contains(err.Error(), "登录") {
					errMsg += fmt.Sprintf("京东商城:[%v]的Cookie无效了！", v)
					flag = true
				}
			}
		}
		cc.VendorID = v
		cc.VendorOrgCode = ""
		if flag {
			cc.Status = "无效"
		} else {
			cc.Status = "有效"
		}
		ccList = append(ccList, cc)
	}
	if isAuto && errMsg != "" {
		globals.SugarLogger.Warnf("GetCheckVendorCookie：[%v]", errMsg)
	}
	return ccList, err
}
