package tao_vegetable

import (
	"bytes"
	"fmt"
	request1475 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability1475/request"
	domain585 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability585/domain"
	request585 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability585/request"
	domain589 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability589/domain"
	request589 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability589/request"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/globals"
	"image/jpeg"
	"io/ioutil"
	"net/http"
	"strings"
	"testing"
	"time"
)

// 上传图片
func TestUploadImg(t *testing.T) {
	uploadImg(apiTao, []string{"http://img20.360buyimg.com/vc/jfs/t2473/147/1629369634/4242813/e73adcd0/566a65f3N8aa04ec1.jpg"})
	//uploadImg(apiTao, []string{"http://image.jxc4.com/image/2c28b6e2a1de59adba0f117b1519b5f7.png"})
}

func TestAddStoreSku(t *testing.T) {
	param1 := &request585.AlibabaWdkSkuAddRequest{}
	param := make([]domain585.AlibabaWdkSkuAddSkuDo, 0, 0)
	sku1 := domain585.AlibabaWdkSkuAddSkuDo{
		Barcodes:  utils.String2Pointer("19930827"),
		BrandName: utils.String2Pointer("京西菜场"),
		//CategoryCode:  utils.String2Pointer("222201"),
		OuCode:        utils.String2Pointer("JX668594"),
		InventoryUnit: utils.String2Pointer("份"),
		//MainPicUrls:   utils.String2Pointer("https://img.alicdn.com/imgextra/i1/2680068332/O1CN01nXtVt92BQ6ryMXDpS_!!2680068332.png"), // 多图逗号
		//DetailPicUrls: utils.String2Pointer("https://img.alicdn.com/imgextra/i1/2680068332/O1CN01nXtVt92BQ6ryMXDpS_!!2680068332.png"), // 多图逗号
		ProducerPlace: utils.String2Pointer("中国"),
		//ShelfLife:      utils.Int64ToPointer(7),
		SkuCode: utils.String2Pointer("19930827"),
		SkuName: utils.String2Pointer("西兰花 500g/份"),
		//SkuType:        utils.Int64ToPointer(13),
		StorageType:       utils.Int64ToPointer(242),
		SuggestedPrice:    utils.String2Pointer("9"),
		Weight:            utils.String2Pointer("500"),
		WeightFlag:        utils.Int64ToPointer(0),
		ShortTitle:        utils.String2Pointer("美味西兰花"),
		TxtDesc:           utils.String2Pointer("美味西兰花"),
		NetContent:        utils.String2Pointer("500"),
		SaleUnit:          utils.String2Pointer("份"),
		LifeStatus:        utils.String2Pointer("A"),
		SaleSpec:          utils.String2Pointer("1*1份"),
		AvgWeight:         utils.String2Pointer("1"), // 每个虾饺重量
		PreMinusWeight:    utils.String2Pointer("1"), // 每个购买单位重量,预扣重量
		StepQuantity:      utils.Int64ToPointer(1),   // 每次购买至少增加一个购买单位
		PurchaseQuantity:  utils.Int64ToPointer(1),   // 起购单位
		SubTitle:          utils.String2Pointer("同城包邮"),
		SubTitle1:         utils.String2Pointer("一小时速达"),
		OnlineSaleFlag:    utils.Int64ToPointer(1), // 门店控制是否可见
		DeliveryUnit:      utils.String2Pointer("份"),
		DeliverySpec:      utils.String2Pointer("1"),
		MemberPrice:       utils.String2Pointer("9"),
		Storage:           utils.String2Pointer("冷藏"),
		PickFloatRate:     utils.String2Pointer("0"),   // ? 0
		ForbidReceiveDays: utils.Int64ToPointer(0),     // ? 7
		ForbidSalesDays:   utils.Int64ToPointer(0),     // ? 0
		OverloadRate:      utils.String2Pointer("0"),   // ? 0
		WarnDays:          utils.Int64ToPointer(0),     // ? 0
		FixedFlag:         utils.Int64ToPointer(0),     // ? 0
		PurchaseSpec:      utils.String2Pointer("1"),   // ? 1
		PurchaseUnit:      utils.String2Pointer("份"),   // ? 同上
		LabelStyleType:    utils.String2Pointer("无价签"), // 库存单位
		RichText:          utils.String2Pointer("优先使用这个(txt_desc)"),
		//BackCatCode: , // 优先使用BackCatCode  HmCategoryCode靠后
		//HmCategoryCode: ,
		SkuPrice:        utils.String2Pointer("9"),                                                                                                                                   // 优先使用skuPrice 靠后SalePrice
		Period:          utils.Int64ToPointer(7),                                                                                                                                     // 优先使用period 靠后shelf_life
		ItemTypeNew:     utils.Int64ToPointer(1),                                                                                                                                     // 优先使用 靠后 sku_type
		MerchantCatCode: utils.String2Pointer("222201"),                                                                                                                              // 优先使用 靠后 category_code
		SkuPicUrls:      utils.String2Pointer("https://image.jxc4.com/image/af9501e559555d062f2bba830adcd04a.jpg,https://image.jxc4.com/image/26d4f62c006180050df1237b92a007de.jpg"), // 第一张主图,后面是详情 优先使用本字段 靠后 同字段main_pic_urls和detail_pic_urls
		FragileFlag:     utils.Int64ToPointer(1),
		DeliveryStorage: utils.String2Pointer("常温"),
		TemporaryFlag:   utils.Int64ToPointer(0),
		IsOnline:        utils.Int64ToPointer(1),
	}
	sku1.SkuSuppliers = &[]domain585.AlibabaWdkSkuAddSkuSupplierDo{
		domain585.AlibabaWdkSkuAddSkuSupplierDo{
			ReturnFlag:    utils.Int64ToPointer(0),
			Minimum:       utils.String2Pointer("1"),
			PurchasePrice: utils.String2Pointer(""),
			SupplierNo:    nil,
			SupplierName:  nil,
			MainFlag:      nil,
		},
	}
	sku1.ChannelProps = &[]domain585.AlibabaWdkSkuAddChannelProp{
		domain585.AlibabaWdkSkuAddChannelProp{
			ChannelType: utils.String2Pointer("txd"),
			Props: &[]domain585.AlibabaWdkSkuAddPropField{
				domain585.AlibabaWdkSkuAddPropField{
					Value: utils.String2Pointer("1"),
					Key:   utils.String2Pointer("ONE_HOUR_STATUS"),
				},
			},
		},
	}

	param = append(param, sku1)
	param1.ParamList = &param
	result, err := apiTao.AddStoreSku(param1)
	globals.SugarLogger.Debugf("result = %s", utils.Format4Output(result, false))
	globals.SugarLogger.Debugf("err = %s", utils.Format4Output(err, false))
}

func TestUpdateSku(t *testing.T) {
	StoreIds1 := "JX668428"
	storeCode := strings.Split(StoreIds1, ",")

	for _, v := range storeCode {
		param := &request585.AlibabaWdkSkuUpdateRequest{}
		updateSkuList := make([]domain585.AlibabaWdkSkuUpdateSkuDo, 0, 0)
		updateSku := domain585.AlibabaWdkSkuUpdateSkuDo{
			OuCode:   utils.String2Pointer(v),
			SkuCode:  utils.String2Pointer("25824"),
			SkuPrice: utils.String2Pointer("129.5"), // 优先使用skuPrice 靠后SalePrice
		}
		updateSkuList = append(updateSkuList, updateSku)
		param.ParamList = &updateSkuList
		_, err := apiTao.UpdateStoreSku(param)
		if err != nil {
			fmt.Println(v)
			continue
		}
	}

}

// 商品上下架
func TestStoreSkuUpdateOffShelf(t *testing.T) {
	for _, storeID := range storeList {
		globals.SugarLogger.Debugf("store  %d", storeID)
		err := apiTao.StoreSkuUpdateOffShelfList(storeID, skuList)
		if err != nil {
			globals.SugarLogger.Debugf("err := %s", utils.Format4Output(err, false))
		}
	}

}

//
var storeList = []int64{100930, 100871}

var skuList = []int64{}

// 商品库存修改
func TestStoreSkuStock(t *testing.T) {
	param := request589.AlibabaWdkStockPublishRequest{}
	batchStockPublishDto := &domain589.AlibabaWdkStockPublishBatchStockPublishDto{
		UpdateType:       utils.Int64ToPointer(1),
		BillNo:           utils.String2Pointer(utils.Int64ToStr(time.Now().UnixNano())),
		BillType:         utils.Int64ToPointer(UpdateTypeStokeBillType),
		PublishSource:    utils.String2Pointer("JX668594"),
		ShopCode:         utils.String2Pointer("JX668594"),
		Operator:         utils.String2Pointer("liulei"),
		StockPublishDtos: nil,
	}
	stockPublishDtos := make([]domain589.AlibabaWdkStockPublishStockPublishDto, 0, 0)
	stockPublishDtos = append(stockPublishDtos, domain589.AlibabaWdkStockPublishStockPublishDto{
		SkuCode:   utils.String2Pointer("22640"),
		Quantity:  utils.String2Pointer("99"),
		OrderNo:   utils.String2Pointer(fmt.Sprintf("%s_%d_%d", "JX668594", time.Now().UnixNano(), 84671)),
		OrderType: utils.String2Pointer("10006800"),
	})
	batchStockPublishDto.StockPublishDtos = &stockPublishDtos
	param.BatchStockPublishDto = batchStockPublishDto

	if err := apiTao.StoreSkuStock(&param); err != nil {
		globals.SugarLogger.Debugf("err := %s", err.Error())
	}
}

func TestGetSkuDetaul(t *testing.T) {
	result, err := apiTao.QueryStoreSKu(&request585.AlibabaWdkSkuQueryRequest{Param: &domain585.AlibabaWdkSkuQuerySkuQueryDo{
		OuCode:   utils.String2Pointer("JX666678"),
		SkuCodes: &[]string{"22491", "2"},
	}})
	globals.SugarLogger.Debugf("err  :=  %s ", utils.Format4Output(err, false))
	globals.SugarLogger.Debugf("result  :=  %s ", utils.Format4Output(result, false))
}

func uploadImg(api *API, imgs []string) *string {
	result := make([]string, 0, 0)
	for _, v := range imgs {
		if v == "" {
			continue
		}

		inputTitle := strings.LastIndex(v, "/")
		title := strings.LastIndex(v, ".")
		resp, err := http.Get(v)
		if err != nil {
			continue
		}
		body, _ := ioutil.ReadAll(resp.Body)
		if strings.Contains(string(body), "Document not found") {
			continue
		}
		if float64(len(body))/float64(1024)/float64(1024) > float64(3) {
			jpgimg, err := jpeg.Decode(strings.NewReader(string(body))) // 文件解码成图像对象
			if err != nil {
				return nil
			}
			var buf bytes.Buffer
			err = jpeg.Encode(&buf, jpgimg, &jpeg.Options{Quality: 30})
			if err != nil {
				return nil
			}
			body = buf.Bytes()
		}

		if newImg, _ := api.UploadImg(&request1475.AlibabaWdkPictureUploadRequest{
			PictureCategoryId: utils.Int64ToPointer(0),
			Img:               &body,
			ImgInputTitle:     utils.String2Pointer(v[inputTitle+1:]),
			Title:             utils.String2Pointer(v[inputTitle+1 : title]),
		}); newImg != "" {
			result = append(result, newImg)
		}
	}

	return utils.String2Pointer(strings.Join(result, ","))
}

func TestUpLoadImg(t *testing.T) {
	v := `http://image.jxc4.com/9e8e8471ba959d10166d0cf4f08ccb2d.jpg`
	inputTitle := strings.LastIndex(v, "/")
	title := strings.LastIndex(v, ".")
	resp, err := http.Get(v)
	globals.SugarLogger.Debugf("err :=    get err := %s", utils.Format4Output(err, false))
	body, err := ioutil.ReadAll(resp.Body)
	globals.SugarLogger.Debugf("err :=2    get err := %s", utils.Format4Output(err, false))

	dataa, err3 := apiTao.UploadImg(&request1475.AlibabaWdkPictureUploadRequest{
		PictureCategoryId: utils.Int64ToPointer(0),
		Img:               &body,
		ImgInputTitle:     utils.String2Pointer(v[inputTitle:]),
		Title:             utils.String2Pointer(v[inputTitle:title]),
	})
	globals.SugarLogger.Debugf("errr3 := %s", utils.Format4Output(err3, false))
	globals.SugarLogger.Debugf("data2 := %s", utils.Format4Output(dataa, false))
}
