package gomei

import (
	"encoding/base64"
	"fmt"
	gomei "git.rosy.net.cn/baseapi/platformapi/gome_live_show"
	"git.rosy.net.cn/baseapi/platformapi/jdshopapi"
	"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/jxutils/tasksch"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/business/partner/putils"
	"git.rosy.net.cn/jx-callback/globals"
	"regexp"
	"strings"
	"time"
)

// 删除不在使用商品(下架之后在删除) ok
func (p *PurchaseHandler) DeleteStoreSkus(ctx *jxcontext.Context, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (failedList []*partner.StoreSkuInfoWithErr, err error) {
	if globals.EnableJdShopWrite && vendorStoreID == model.GoMeiShopMainVendorStoreID {
		for _, v := range storeSkuList {
			if v.IsDeletedBySku && storeID != 0 { // 如果门店id存在,则将该门店商品下架,所有门店该商品处于下架才可以删除!
				_, err = getAPI(v.VendorOrgCode).OnOffLineGoodsOnStore(&gomei.ShelfGoodsForStoreReq{
					StoreCode:    vendorStoreID,
					SkuCode:      []string{v.VendorSkuID},
					ShelveStatus: gomei.DownOnTheShelf,
				})
			}
			if err == nil {
				_, err = getAPI(v.VendorOrgCode).DeleteGoodsOnStore(v.VendorSkuID)
			}
			if err != nil {
				failedList = append(failedList, putils.GetErrMsg2FailedSingleList(storeSkuList, err, storeID, model.VendorChineseNames[model.VendorGoMei], "删除商品")...)
			}
		}
	}
	return failedList, err
}



// 获取门店商品列表
func (p *PurchaseHandler) GetStoreSkusFullInfo(ctx *jxcontext.Context, parentTask tasksch.ITask, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (skuNameList []*partner.SkuNameInfo, err error) {
	var (
		pageNo   = 1
		pageSize = 50
	)
	result, err := getAPI(string(model.VendorGoMei)).QueryGoodsListById(&gomei.QueryGoodsListForStoreReq{
		Page: gomei.Page{
			PageNumber: pageNo,
			PageSize:   pageSize,
		},
	})
	if err != nil {
		return nil, err
	}

	for ; pageNo <= result.Data.Total/pageSize+1; pageNo++ {
		result2, err := getAPI(string(model.VendorGoMei)).QueryGoodsListById(&gomei.QueryGoodsListForStoreReq{
			Page: gomei.Page{
				PageNumber: pageNo,
				PageSize:   pageSize,
			},
		})
		if err != nil {
			return nil, err
		}

		for _, v := range result2.Data.Records {
			if skuName := vendorSku2Jx2(v); skuName != nil {
				skuNameList = append(skuNameList, skuName)
			}
		}
	}

	return skuNameList, err
}

// 修改门店商品状态
func (p *PurchaseHandler) UpdateStoreSkusStatus(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo, status int) (failedList []*partner.StoreSkuInfoWithErr, err error) {
	if globals.EnableJdShopWrite {
		for _, v := range storeSkuList {
			if vendorSkuID, err := getMainStoreVendorSkuID(model.GoMeiShopMainStoreID, v.SkuID); err == nil && vendorSkuID != "" {
				storeSku := &gomei.ShelfGoodsForStoreReq{
					StoreCode: vendorStoreID,
					SkuCode:   []string{vendorSkuID},
				}
				if status == 0 {
					storeSku.ShelveStatus = gomei.PutOnTheShelf
				} else {
					storeSku.ShelveStatus = gomei.DownOnTheShelf
				}
				_, err = getAPI(v.VendorOrgCode).OnOffLineGoodsOnStore(storeSku)
			}
		}
		if err != nil {
			failedList = putils.GetErrMsg2FailedSingleList(storeSkuList, err, storeID, model.VendorChineseNames[model.VendorGoMei], "修改商品库存")
		}
	}
	return failedList, err
}

// 修改门店商品价格维护
func (p *PurchaseHandler) UpdateStoreSkusPrice(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (failedList []*partner.StoreSkuInfoWithErr, err error) {
	if globals.EnableJdShopWrite {
		for _, v := range storeSkuList {
			if vendorSkuID, err := getMainStoreVendorSkuID(model.GoMeiShopMainStoreID, v.SkuID); err == nil && vendorSkuID != "" {
				_, err = getAPI(v.VendorOrgCode).UpdateOnGoodsPriceForStore(&gomei.StoreGoodsPriceUpdateReq{
					StoreCode: vendorStoreID,
					SkuCode:   vendorSkuID,
					SalePrice: utils.Int64ToFloat64(v.VendorPrice),
				})
			}
			if err != nil {
				failedList = append(failedList, putils.GetErrMsg2FailedSingleList(storeSkuList, err, storeID, model.VendorChineseNames[model.VendorIDJDShop], "修改商品价格")...)
			}
		}
	}
	return failedList, err
}

// 门店商品库存维护
func (p *PurchaseHandler) UpdateStoreSkusStock(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, storeSkuList []*partner.StoreSkuInfo) (failedList []*partner.StoreSkuInfoWithErr, err error) {
	if globals.EnableJdShopWrite {
		for _, v := range storeSkuList {
			if vendorSkuID, err := getMainStoreVendorSkuID(model.GoMeiShopMainStoreID, v.SkuID); err == nil && vendorSkuID != "" {
				_, err = getAPI(v.VendorOrgCode).UpdateStockForStore(&gomei.StoreGoodsStockUpdateReq{
					StoreCode: vendorStoreID,
					ItemStocks: []*gomei.StoreSkuNum{
						{SkuCode: vendorSkuID, StockNum: int64(v.Stock)},
					},
				})
			}
		}
		if err != nil {
			failedList = append(failedList, putils.GetErrMsg2FailedSingleList(storeSkuList, err, storeID, model.VendorChineseNames[model.VendorIDJDShop], "修改商品库存")...)
		}
	}
	return failedList, err
}

//  获取门店所有的分类
func (p *PurchaseHandler) GetStoreAllCategories(ctx *jxcontext.Context, storeID int, vendorStoreID string) (cats []*partner.BareCategoryInfo, err error) {
	var (
		pageNo   = 1
		pageSize = 50
	)
	result, err := getAPI(string(model.VendorGoMei)).QueryStoreCategoryList(&gomei.QueryStoreGoodsCategoryListReq{
		Page: gomei.Page{
			PageNumber: pageNo,
			PageSize:   pageSize,
		},
		StoreCode: vendorStoreID,
	})
	for ; pageNo <= result.Data.Total/pageSize+1; pageNo++ {
		result2, err := getAPI(string(model.VendorGoMei)).QueryStoreCategoryList(&gomei.QueryStoreGoodsCategoryListReq{
			Page: gomei.Page{
				PageNumber: pageNo,
				PageSize:   pageSize,
			},
			StoreCode: vendorStoreID,
		})
		if err != nil {
			return nil, err
		}

		for _, v := range result2.Data.Records {
			var cat = &partner.BareCategoryInfo{
				VendorCatID: v.CategoryCode,
				Name:        v.CategoryName,
			}
			cat.Level = 1
			cats = append(cats, cat)
		}
	}

	return cats, err
}

// 修改或者更新门店分类信息
func (p *PurchaseHandler) UpdateStoreCategory(ctx *jxcontext.Context, storeID int, vendorStoreID string, storeCat *dao.SkuStoreCatInfo) (err error) {
	if globals.EnableJdShopWrite {
		_, status, err2 := updateOrCreateCategories(storeCat, vendorStoreID, false)
		err = err2
		if status == -1 {
			return fmt.Errorf("京东商城店内分类更新失败！")
		}
	}
	return err
}

func (p *PurchaseHandler) CreateStoreCategory(ctx *jxcontext.Context, storeID int, vendorStoreID string, storeCat *dao.SkuStoreCatInfo) (err error) {
	if globals.EnableJdShopWrite {
		allCategoryList, status, err2 := updateOrCreateCategories(storeCat, vendorStoreID, true)
		err = err2
		if status == -1 {
			return fmt.Errorf("国美商城店内分类创建失败！")
		}
		if err != nil {
			return err
		}
		time.Sleep(time.Second * 2)

		for _, v := range allCategoryList {
			if v.CategoryName == storeCat.Name {
				storeCat.VendorCatID = v.CategoryCode
				break
			}
		}
		if storeCat.VendorCatID == "" {
			return fmt.Errorf("国美商城店内分类创建可能失败了！storeID: %v", storeID)
		}
	}
	return err
}

func (p *PurchaseHandler) DeleteStoreCategory(ctx *jxcontext.Context, storeID int, vendorStoreID, vendorCatID string, level int) (err error) {
	if globals.EnableJdShopWrite {
		_, err = getAPI(string(model.VendorGoMei)).DeleteStoreGoodsCategory(vendorStoreID, vendorCatID)
	}
	return err
}

func (p *PurchaseHandler) IsErrSkuExist(err error) (isExist bool) {
	return false
}

func (p *PurchaseHandler) IsErrCategoryExist(err error) (isExist bool) {
	return false
}

func (p *PurchaseHandler) IsErrCategoryNotExist(err error) (isNotExist bool) {
	return false
}

func (p *PurchaseHandler) GetStoreSkusBatchSize(funcID int) (batchSize int) {
	return 1
}

func (p *PurchaseHandler) GetSensitiveWordRegexp() *regexp.Regexp {
	return sensitiveWordRegexp
}

func (p *PurchaseHandler) IsErrSkuNotExist(err error) (isNotExist bool) {
	if strings.Contains(err.Error(), deleteErr1) || (strings.Contains(err.Error(), deleteErr2) && strings.Contains(err.Error(), deleteErr3)) {
		return true
	}
	return false
}

func GetAllStoreCategories(vendorOrgCode, vendorStoreId string) ([]*gomei.StoreGoodsCategoryListRecord, error) {
	var (
		pageNo   = 1
		pageSize = 50
	)

	result, err := getAPI(vendorOrgCode).QueryStoreCategoryList(&gomei.QueryStoreGoodsCategoryListReq{
		Page: gomei.Page{
			PageSize:   pageSize,
			PageNumber: pageNo,
		},
		StoreCode: vendorStoreId,
	})
	if err != nil {
		return nil, err
	}
	createShopCategoryParams := make([]*gomei.StoreGoodsCategoryListRecord, 0, 0)
	for ; pageNo <= result.Data.Total/pageSize+1; pageNo++ {
		result2, err := getAPI(vendorOrgCode).QueryStoreCategoryList(&gomei.QueryStoreGoodsCategoryListReq{
			Page: gomei.Page{
				PageNumber: pageNo,
				PageSize:   pageSize,
			},
			StoreCode: vendorStoreId,
		})
		if err != nil {
			return nil, err
		}

		for _, v := range result2.Data.Records {
			createShopCategoryParams = append(createShopCategoryParams, &gomei.StoreGoodsCategoryListRecord{
				CategoryCode: v.CategoryCode,
				CategoryName: v.CategoryName,
				Rank:         v.Rank,
			})
		}
	}

	return createShopCategoryParams, nil
}

// 创建或者修改分类
func updateOrCreateCategories(storeCat *dao.SkuStoreCatInfo, vendorStoreId string, isCreate bool) (createShopCategoryParams []*gomei.StoreGoodsCategoryListRecord, status int64, err error) {
	createShopCategoryParams, err = GetAllStoreCategories(storeCat.VendorOrgCode, vendorStoreId)
	if err != nil {
		return nil, -1, err
	}

	if isCreate { // 创建分类
		_, err = getAPI(storeCat.VendorOrgCode).AddStoreCategory(&gomei.StoreAddGoodsCategory{
			StoreCode:    vendorStoreId,
			CategoryName: storeCat.VendorCategoryName, // storeCat.StoreCatName
			Rank:         0,
		})
		if err != nil {
			return nil, -1, err
		}
	} else { // 修改分类,无法新增和修改排序,排序结构需要在国美系统上获取
		// 查询当前分类
		for _, v := range createShopCategoryParams {
			if v.CategoryCode != storeCat.VendorCatID {
				continue
			}
			_, err = getAPI(storeCat.VendorOrgCode).ModifyStoreGoodsCategory(&gomei.StoreModifyGoodsCategory{
				StoreCode:    vendorStoreId,
				CategoryCode: storeCat.VendorCatID,        // storeCat.StoreCatName
				CategoryName: storeCat.VendorCategoryName, // storeCat.StoreCatName
				Rank:         v.Rank,
			})
			if err != nil {
				return nil, -1, err
			}
		}
	}
	return
}

// 将平台商品信息转化为本地商品信息
func vendorSku2Jx2(result *gomei.QueryGoodsListForStoreRecordRes) (skuName *partner.SkuNameInfo) {
	if result == nil {
		globals.SugarLogger.Warnf("vendorSku2Jx, strange result:%s", utils.Format4Output(result, true))
		return nil
	}
	skuName = &partner.SkuNameInfo{
		Name: result.GoodsName,
		SkuList: []*partner.SkuInfo{
			&partner.SkuInfo{
				StoreSkuInfo: partner.StoreSkuInfo{
					VendorSkuID: result.SkuCode,
					Stock:       result.StockNum,
					VendorPrice: jxutils.StandardPrice2Int(result.SalePrice),
				},
			},
		},
	}

	if result.ShelveStatus == gomei.PutOnTheShelf {
		skuName.Status = 1
	} else {
		skuName.Status = 0
	}

	return skuName
}

// 获取当前门店第三方商品id
func getMainStoreVendorSkuID(mainStoreID int, skuID int) (vendorSkuID string, err error) {
	var (
		db = dao.GetDB()
	)
	storeSkus, err := dao.GetStoresSkusInfo(db, []int{mainStoreID}, []int{skuID})
	if len(storeSkus) > 0 {
		//vendorSkuID = storeSkus[0].GmID
	}
	return vendorSkuID, err
}

// 国美上传图片,转bese64字符串在上传,图片要求长宽和大小
func uploadImg(img, name, index, vendorOrgCode string) (imgURL string, err error) {
	data, _, err := jxutils.DownloadFileByURL(img)
	if err != nil {
		return "", err
	}
	// 获取图片地址
	uploadResult, err := getAPI(vendorOrgCode).UploadPicture(base64.StdEncoding.EncodeToString(data), 1, name+string(time.Now().Unix()))
	if err != nil {
		return "", err
	}
	return uploadResult.Data.Url, err
}

func filterSensitiveWord(name string) (result string) {
	for _, v := range jdshopapi.SensitiveWordMap {
		if strings.Contains(name, v) {
			return strings.ReplaceAll(name, v, "")
		}
	}
	return name
}
