package yinbaoapi

import (
	"crypto/md5"
	"fmt"
	"io/ioutil"
	"net/http"
	"testing"

	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/utils"
)

func TestCreateCategoryUid(t *testing.T) {
	result, err := api.CreateCategoryUid()
	if err != nil {
		t.Fatal(err)
	}
	t.Log(utils.Format4Output(result, false))
}

func TestLoadSubStoresByUserIdDDLJson(t *testing.T) {
	result, err := api.LoadSubStoresByUserIdDDLJson()
	if err != nil {
		t.Fatal(err)
	}
	t.Log(utils.Format4Output(result, false))
}

func TestAddNewCategory(t *testing.T) {
	_, err := api.AddNewCategory(MainStoreVendorOrgCode, "测试2", "测试分类2")
	if err != nil {
		t.Fatal(err)
	}
	// t.Log(utils.Format4Output(result, false))
}

func TestUpdateCategory(t *testing.T) {
	err := api.UpdateCategory(MainStoreVendorOrgCode, "1585030864115972859", "叶菜3", "蔬菜")
	if err != nil {
		t.Fatal(err)
	}
	// t.Log(utils.Format4Output(result, false))
}

func TestDeleteCategory(t *testing.T) {
	err := api.DeleteCategory(MainStoreVendorOrgCode, []string{"1585030864115972859"})
	if err != nil {
		t.Fatal(err)
	}
	// t.Log(utils.Format4Output(result, false))
}

func TestLoadCategorysWithOption(t *testing.T) {
	result, err := api.LoadCategorysWithOption(MainStoreVendorOrgCode)
	if err != nil {
		t.Fatal(err)
	}
	t.Log(utils.Format4Output(result, false))
}

func TestLoadProductsByPage(t *testing.T) {
	result, err := api.LoadProductsByPage("3936087", "0012113")
	if err != nil {
		t.Fatal(err)
	}
	t.Log(utils.Format4Output(result, false))
}

func TestFindProduct(t *testing.T) {
	result, err := api.FindProduct("7818179")
	if err != nil {
		t.Fatal(err)
	}
	t.Log(utils.Format4Output(result, false))
}

func TestSaveProduct(t *testing.T) {
	// err := api.SaveProduct(MainStoreVendorOrgCode, "0000001")
	// if err != nil {
	// 	t.Fatal(err)
	// }
}

func TestTryGetCookie(t *testing.T) {
	result, err := api.TryGetCookie()
	if err != nil {
		t.Fatal(err)
	}
	t.Log(utils.Format4Output(result, false))
}

func TestUploadProductImage(t *testing.T) {
	url := "http://image.jxc4.com/image/243ec2100060c15a1eb009fd2ee99450.jpg"
	data, _, _ := DownloadFileByURL(url)
	err := api.UploadProductImage(MainStoreVendorOrgCode, "8788044", data, "243ec2100060c15a1eb009fd2ee99450.jpg")
	if err != nil {
		t.Fatal(err)
	}
}

func DownloadFileByURL(fileURL string) (bodyData []byte, fileMD5 string, err error) {
	response, err := http.Get(fileURL)
	if err == nil {
		defer response.Body.Close()
		if response.StatusCode == http.StatusOK {
			if bodyData, err = ioutil.ReadAll(response.Body); err == nil {
				fileMD5 = fmt.Sprintf("%X", md5.Sum(bodyData))
			}
		} else {
			err = platformapi.ErrHTTPCodeIsNot200
		}
	}
	return bodyData, fileMD5, err
}

func TestBatchUpdateProductEnable(t *testing.T) {
	err := api.BatchUpdateProductEnable("3936087", "463072974624941184", 1)
	if err != nil {
		t.Fatal(err)
	}
	// t.Log(utils.Format4Output(result, false))
}
