package jd

import (
	"encoding/json"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/globals/api"
	"net/url"
	"strings"

	"git.rosy.net.cn/jx-callback/business/model/dao"

	"git.rosy.net.cn/baseapi/platformapi/jdapi"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/globals"
)

type PurchaseHandler struct {
	partner.BasePurchasePlatform
}

var (
	CurPurchaseHandler *PurchaseHandler
)

func init() {
	CurPurchaseHandler = new(PurchaseHandler)
	partner.RegisterPurchasePlatform(CurPurchaseHandler)
}

func getAPI(appOrgCode string) (apiObj *jdapi.API) {
	if appOrgCode == "" {
		globals.SugarLogger.Warnf("getAPI appOrgCode is empty")
	}
	return partner.CurAPIManager.GetAPI(model.VendorIDJD, appOrgCode).(*jdapi.API)
}

func GetAPI(appOrgCode string) (apiObj *jdapi.API) {
	return getAPI(appOrgCode)
}

func GetAPIbyKey(appKey string) (apiObj *jdapi.API) {
	if code, err := dao.GetVendorOrgCodeByKey(dao.GetDB(), model.VendorIDJD, appKey); err == nil && code != nil {
		return jdapi.New(code.Token, code.AppKey, code.AppSecret)
	}
	return nil
}

func AppKey2OrgCode(appKey string) (vendorOrgCode string) {
	// apiList := partner.CurAPIManager.GetAppOrgCodeList(model.VendorIDJD)
	// for _, v := range apiList {
	// 	jdAPI := partner.CurAPIManager.GetAPI(model.VendorIDJD, v).(*jdapi.API)
	// 	if jdAPI.GetAppKey() == appKey {
	// 		vendorOrgCode = v
	// 		break
	// 	}
	// }
	if code, err := dao.GetVendorOrgCodeByKey(dao.GetDB(), model.VendorIDJD, appKey); err == nil && code != nil {
		vendorOrgCode = code.VendorOrgCode
	}
	if vendorOrgCode == "" {
		globals.SugarLogger.Warnf("AppKey2OrgCode appKey:%s get empty vendorOrgCode", appKey)
	}
	return vendorOrgCode
}

func (c *PurchaseHandler) GetVendorID() int {
	return model.VendorIDJD
}

func JdOperationTime2JxOperationTime(value1 int) int16 {
	value := int16(value1)
	return (value/2)*100 + (value%2)*30
}

func JxOperationTime2JdOperationTime(value int16) int16 {
	return (value/100)*2 + (value%100)/30
}

func JdStoreStatus2JxStatus(yn, closeStatus int) int {
	if yn == 1 {
		return model.StoreStatusDisabled
	} else if closeStatus == 1 {
		return model.StoreStatusClosed
	}
	return model.StoreStatusOpened
}

func JxStoreStatus2JdStatus(status int) (yn, closeStatus int) {
	switch status {
	case model.StoreStatusDisabled:
		return 1, 1
	case model.StoreStatusHaveRest, model.StoreStatusClosed:
		return 0, 1
	default:
		return 0, 0
	}
}

func (p *PurchaseHandler) UploadImg(ctx *jxcontext.Context, vendorOrgCode, imgURL string, imgData []byte, imgName string, imgType int) (imgHint string, err error) {
	return imgHint, err
}

type JdCode struct {
	Code     string `json:"code"`
	VenderID string `json:"venderId"`
}

type JdToken struct {
	Token    string `json:"token"`
	VenderID string `json:"venderId"`
}

func OnTokenChange(values url.Values) {
	db := dao.GetDB()
	codeInfo := &JdCode{}
	if dataStr := values.Get("code"); dataStr != "" {
		json.Unmarshal([]byte(dataStr), &codeInfo)
	}
	if codeInfo.Code != "" {
		voc := &model.VendorOrgCode{}
		//sql := `
		//	SELECT * FROM tmp_jd WHERE vendor_org_code = ?
		//`
		//sqlParams := []interface{}{codeInfo.VenderID}
		//if err := dao.GetRow(db, &voc, sql, sqlParams); err == nil && voc != nil {
		if result, _ := dao.GetVendorOrgCode(db, model.VendorIDJD, codeInfo.VenderID, model.VendorOrgTypePlatform); len(result) == 0 {
			voc2 := &model.VendorOrgCode{
				Comment:       voc.Comment,
				VendorOrgCode: codeInfo.VenderID,
				VendorType:    model.VendorOrgTypePlatform,
				IsJxCat:       1,
			}
			dao.WrapAddIDCULDEntity(voc2, "jxadmin")
			if err := dao.CreateEntity(db, voc2); err == nil {
				//添加成功后去开发者后台填验证码
				if configs, err := dao.QueryConfigs(dao.GetDB(), "jdConfigCookie", model.ConfigTypeCookie, ""); err == nil {
					api.JdAPI.SetCookieWithStr(configs[0].Value)
					if appID, err := api.JdAPI.GetJdNoAuthAppID(codeInfo.VenderID); err == nil {
						api.JdAPI.SetCode(codeInfo.Code, appID)
					}
				}
			}
		} else {
			globals.SugarLogger.Debugf("OnTokenChange， 发验证码，但是库里有这个账号了")
		}
		//}
	} else {
		tokenInfo := &JdToken{}
		if dataStr := values.Get("token"); dataStr != "" {
			json.Unmarshal([]byte(dataStr), &tokenInfo)
		}
		if tokenInfo == nil {
			return
		}
		//sql := `
		//	SELECT * FROM tmp_jd WHERE vendor_org_code = ?
		//`
		//sqlParams := []interface{}{tokenInfo.VenderID}
		//if err := dao.GetRow(db, &voc, sql, sqlParams); err == nil && voc != nil {
		if result, _ := dao.GetVendorOrgCode(db, model.VendorIDJD, tokenInfo.VenderID, model.VendorOrgTypePlatform); len(result) > 0 {
			result[0].Token = tokenInfo.Token
			if _, err := dao.UpdateEntity(db, result[0], "Token"); err == nil {
				//添加成功后去开发者后台填验证码
				// if configs, err := dao.QueryConfigs(dao.GetDB(), "jdConfigCookie", model.ConfigTypeCookie, ""); err == nil {
				// 	api.JdAPI.SetCookieWithStr(configs[0].Value)
				// 	result2, _ := api.JdAPI.GetJdAppInfo()
				// 	result[0].AppKey = result2.AppKey
				// 	result[0].AppSecret = result2.AppSecret
				// 	dao.UpdateEntity(db, result[0], "AppKey", "AppSecret")
				// }
			}
		} else {
			globals.SugarLogger.Debugf("OnTokenChange， 发token，但是库里没这个账号")
		}
		//}
	}

}

func (p *PurchaseHandler) GetOrderRider(vendorOrgCode, vendorStoreID string, param map[string]interface{}) (err error) {
	logisticInfo := jdapi.ReceiveLogisticInfo{
		OrderId:          param["order_id"].(string),
		DeliveryInfoList: nil,
	}
	deliveryInfoList := make([]jdapi.DeliveryInfo, 0, 0)
	deliverInfo := jdapi.DeliveryInfo{
		DeliveryManName:  "暂无",
		DeliveryManPhone: "",

		DeliveryCarrierNo:      "9966", // 暂时未获取到写死
		DeliveryCarrierName:    "达达配送", // 暂时未获取到写死
		DeliveryCarrierOrderNo: param["order_id"].(string),

		FailReason:  "",
		OperateTime: utils.GetCurTimeStr(),
		Operator:    jxcontext.AdminCtx.GetUserName(),
	}
	switch param["logistics_status"].(int) {
	case 0:
		deliverInfo.DeliveryStatus = jdapi.JdDeliveryStatusNew
	case 10:
		// 接单、更换骑手、骑手到店、骑手取货 都需要填加：骑手姓名和电话
		deliverInfo.DeliveryStatus = jdapi.JdDeliveryStatusRiderTaking
		deliverInfo.DeliveryManName = param["courier_name"].(string)
		deliverInfo.DeliveryManPhone = param["courier_phone"].(string)
	case 15:
		deliverInfo.DeliveryStatus = jdapi.JdDeliveryStatusToStore
		deliverInfo.DeliveryManName = param["courier_name"].(string)
		deliverInfo.DeliveryManPhone = param["courier_phone"].(string)
	case 20:
		deliverInfo.DeliveryStatus = jdapi.JdDeliveryStatusDelivering
		deliverInfo.DeliveryManName = param["courier_name"].(string)
		deliverInfo.DeliveryManPhone = param["courier_phone"].(string)
	case 40:
		// 完成和取消状态不通过此接口发送通知消息
		getAPI(vendorOrgCode).DeliveryEndOrder(param["order_id"].(string), param["courier_name"].(string))
		return nil
	case 100:
		// 完成和取消状态不通过此接口发送通知消息
		return nil
	case 22:
		deliverInfo.DeliveryStatus = jdapi.JdDeliveryStatusFail
	}

	deliveryInfoList = append(deliveryInfoList, deliverInfo)
	logisticInfo.DeliveryInfoList = deliveryInfoList

	return getAPI(vendorOrgCode).ReceiveLogisticInfoForOpenApiPlatform(logisticInfo)
}

func OrderDeliveryCoordinate(vendorOrgCode string, param map[string]interface{}) error {
	operateUser := param["courier_name"].(string)
	if operateUser == "" {
		operateUser = "system_user"
	}

	return getAPI(vendorOrgCode).SelfDeliveryUploadCoordinate(utils.Str2Int64(param["order_id"].(string)), strings.ReplaceAll(param["latitude"].(string), ".", ""), strings.ReplaceAll(param["longitude"].(string), ".", ""), operateUser)
}
