package jdshop

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/jx-callback/business/jxstore/event"
	"git.rosy.net.cn/jx-callback/globals"
	"strings"
	"time"

	"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/globals/api"
)

func (p *PurchaseHandler) ReadStore(ctx *jxcontext.Context, vendorOrgCode, vendorStoreID, vendorStoreName string) (storeDetail *dao.StoreDetail, err error) {
	// result, err := api.JdShopAPI.NewInfoList(utils.Str2Int64(vendorStoreID))
	// storeDetail.VendorStoreID = vendorStoreID
	// storeDetail.Status = JdsStatus2jxStatus(result.StoreStatus)
	if vendorStoreID != "" {
		result2, _ := api.JdShopAPI.QueryEntityStore(utils.Str2Int64(vendorStoreID))
		if result2 == nil {
			return storeDetail, fmt.Errorf("未查询到该平台门店，平台门店ID：[%v]", vendorStoreID)
		}
		storeDetail = &dao.StoreDetail{}
		storeDetail.ID = utils.Str2Int(result2.ExStoreID)
		storeDetail.Name = result2.StoreName
		storeDetail.Address = result2.Address
		storeDetail.Tel1 = result2.Phone
		storeDetail.DistrictCode = result2.AddrCode
		zbs := strings.Split(result2.Coordinate, ",")
		storeDetail.Lat = jxutils.StandardCoordinate2Int(utils.Str2Float64(zbs[0]))
		storeDetail.Lng = jxutils.StandardCoordinate2Int(utils.Str2Float64(zbs[1]))
	}
	return storeDetail, err
}

// stoerIDs为nil表示所有
func (p *PurchaseHandler) UpdateStore(db *dao.DaoDB, storeID int, userName string) (err error) {
	store, err := dao.GetStoreDetail(db, storeID, model.VendorIDJDShop, "2")
	if err != nil {
		return err
	}
	data, _, err := jxutils.DownloadFileByURL(jdshopapi.JdsStoreImg)
	//timeMap := map[string]string{
	//	"businessBeginTime": int2TimeStr(int(store.OpenTime1)),
	//	"businessEndTime":   int2TimeStr(int(store.CloseTime1)),
	//}
	timeMap := map[string]string{
		"businessBeginTime": "07:00",
		"businessEndTime":   "19:00",
	}
	timeJSON, _ := json.Marshal(timeMap)
	updateEntityStoreParam := &jdshopapi.UpdateEntityStoreParam{
		StoreID: utils.Str2Int(store.VendorStoreID),
		//Name:        store.Name,
		AddCode:     store.JdsCode,
		AddCodeName: store.DistrictName,
		AddName:     store.ProvinceName + store.CityName + store.DistrictName + "@!" + store.Address,
		Coordinate:  utils.Float64ToStr(jxutils.IntCoordinate2Standard(store.Lat)) + "," + utils.Float64ToStr(jxutils.IntCoordinate2Standard(store.Lng)),
		Phone:       store.Tel1,
		ExtendJSON:  string(timeJSON),
		ImageFile:   base64.StdEncoding.EncodeToString(data),
		CustomerID:  utils.Int2Str(store.ID),
	}
	if store.JdsStreetCode != 0 {
		updateEntityStoreParam.AddCode = store.JdsStreetCode
	}
	if updateEntityStoreParam.AddCode == 0 {
		updateEntityStoreParam.AddCode = store.JdCode
	}
	//url, _ := getAPI("2").UploadImageNew(data, "2659335b16e3880e367759b8fc675933.tem.png")
	ex := store.LicenceExpire
	if ex == "" {
		ex = utils.Time2Str(utils.Str2Time(store.LicenceValid).AddDate(20, 0, 0))
	}
	if !strings.Contains(ex, "00:00:00") {
		ex += " 00:00:00"
	}
	var url2 string
	if store.Licence != "" {
		data2, _, _ := jxutils.DownloadFileByURL(store.Licence)
		fileName := store.Licence[strings.LastIndex(store.Licence, "/")+1 : len(store.Licence)]
		url2, _ = getAPI("2").UploadImageNew(data2, fileName)
	}
	storeName := store.Name
	if strings.Contains(storeName, "（") {
		storeName = storeName[0:strings.Index(storeName, "（")] + storeName[strings.Index(storeName, "）")+3:len(storeName)]
	}
	if strings.Contains(storeName, "(") {
		storeName = storeName[0:strings.Index(storeName, "(")] + storeName[strings.Index(storeName, ")")+3:len(storeName)]
	}
	if strings.Contains(storeName, ".") {
		storeName = strings.ReplaceAll(storeName, ".", "")
	}
	if strings.Contains(storeName, "-") {
		storeName = strings.ReplaceAll(storeName, "-", "")
	}
	if strings.Contains(storeName, " ") {
		storeName = strings.ReplaceAll(storeName, " ", "")
	}
	storeName = globals.StoreName + strings.ReplaceAll(storeName, "店", "") + "生鲜店"
	if len(storeName) > 30 {
		storeName = utils.LimitUTF8StringLen2(storeName, 30)
	}
	if storeName != store.Name {
		updateEntityStoreParam.Name = storeName
	}
	err = api.JdShopAPI.UpdateEntityStore(updateEntityStoreParam)
	detail, _ := api.JdShopAPI.ShopDetail(utils.Str2Int(store.VendorStoreID))
	if err == nil && detail != nil {
		param := &jdshopapi.UpdateBasicParam{
			StoreID:            detail.StoreID,
			StoreName:          detail.StoreName,
			CategoryID2:        detail.CategoryID2,
			Coordinate:         detail.Coordinate,
			BussinessBeginTime: detail.BussinessBeginTime,
			BussinessEndTime:   detail.BussinessEndTime,
			ImgURL:             detail.ImgURL,
			StorePhone:         detail.StorePhone,
			AddName:            detail.AddName,
			AddCode3:           detail.AddCode3,
			AddCode1:           detail.AddCode1,
			AddCode2:           detail.AddCode2,
			CategoryID1:        detail.CategoryID1,
			ExStoreID:          store.ID,
		}
		var (
			url3      string
			idCode    string
			startTime string
		)
		if store.IDCardFront != "" {
			data2, _, _ := jxutils.DownloadFileByURL(store.IDCardFront)
			fileName := store.IDCardFront[strings.LastIndex(store.IDCardFront, "/")+1 : len(store.IDCardFront)]
			url3, _ = api.JdShopAPI.UploadImageNew(data2, fileName)
		} else {
			data2, _, _ := jxutils.DownloadFileByURL("http://image.jxc4.com/image/a9bfc170a950ab9a4c76bd10b48b222b.tem.jpg")
			fileName := "a9bfc170a950ab9a4c76bd10b48b222b.tem.jpg"
			url3, _ = api.JdShopAPI.UploadImageNew(data2, fileName)
		}
		if store.IDCode == "" {
			idCode = "610126198012230014"
		} else {
			idCode = store.IDCode
		}
		if store.IDValid == "" {
			startTime = "2013-01-25 00:00:00"
		} else {
			startTime = utils.Time2Str(utils.Str2Time(store.IDValid))
		}
		ex2 := store.IDExpire
		if ex2 == "" {
			ex2 = utils.Time2Str(utils.Str2Time(store.IDValid).AddDate(20, 0, 0))
		}
		if !strings.Contains(ex2, "00:00:00") {
			ex2 += " 00:00:00"
		}
		if url2 != "" {
			param.CategoryID1 = 34
			param.CategoryID2 = 62
			param.QualificationRequests = []*jdshopapi.QualificationRequests{
				&jdshopapi.QualificationRequests{
					QualificationID:   41,
					QualificationName: "营业执照",
					QualificationNo:   store.LicenceCode,
					QualificationURL:  url2,
					StartTime:         utils.Time2Str(utils.Str2Time(store.LicenceValid)),
					EndingTime:        ex,
					Time:              []string{utils.Time2Str(utils.Str2Time(store.LicenceValid)), ex},
				},
				&jdshopapi.QualificationRequests{
					QualificationID:   42,
					QualificationName: "身份证件",
					QualificationNo:   idCode,
					QualificationURL:  url3,
					StartTime:         startTime,
					EndingTime:        ex2,
					Time:              []string{startTime, ex2},
				},
			}
		}
		store1 := fmt.Sprintf("门店id:%d,门店名称:%s,第三方门店状态:%d,本地修改前门店状态%d,本地门店修改后状态:%d,第三方平台Id(京东):%s", storeID, store.Name, 0, store.Status, jxutils.MergeStoreStatus(store.Status, store.VendorStatus), store.VendorOrgCode)
		event.AddOperateEvent(jxcontext.AdminCtx, jxcontext.AdminCtx.GetTrackInfo(), store1, "", "", 10, "UpdateStore")
		err = getAPI("2").UpdateBasic(param)
	}
	if store.SyncStatus&model.SyncFlagStoreStatus != 0 {
		mergedStoreStatus := jxutils.MergeStoreStatus(store.Status, store.VendorStatus)
		p.UpdateStoreStatus(jxcontext.AdminCtx, store.VendorOrgCode, storeID, store.VendorStoreID, mergedStoreStatus)
		store1 := fmt.Sprintf("门店id:%d,门店名称:%s,第三方门店状态:%d,本地修改前门店状态%d,本地门店修改后状态:%d,第三方平台Id(京东):%s", storeID, store.Name, 100, store.Status, mergedStoreStatus, store.VendorOrgCode)
		event.AddOperateEvent(jxcontext.AdminCtx, jxcontext.AdminCtx.GetTrackInfo(), store1, "", "", 10, "UpdateStore")

	}
	if err == nil {
		err = getAPI("2").UpdateExpand(utils.Str2Int(store.VendorStoreID))
	}
	return err
}

func (p *PurchaseHandler) CreateStore2(db *dao.DaoDB, storeID int, userName string, params map[string]interface{}, storeDetail *dao.StoreDetail) (vendorStoreID string, err error) {
	store, err := dao.GetStoreDetail(db, storeID, model.VendorIDJDShop, "")
	if err != nil {
		return vendorStoreID, err
	}
	data, _, err := jxutils.DownloadFileByURL(jdshopapi.JdsStoreImg)
	timeMap := map[string]string{
		"businessBeginTime": int2TimeStr(int(store.OpenTime1)),
		"businessEndTime":   int2TimeStr(int(store.CloseTime1)),
	}
	timeJSON, _ := json.Marshal(timeMap)
	createEntityStoreParam := &jdshopapi.CreateEntityStoreParam{
		Name:         store.Name,
		AddCode:      store.JdsCode,
		AddCodeName:  store.DistrictName,
		AddName:      store.ProvinceName + store.CityName + store.DistrictName + "@!" + store.Address,
		Coordinate:   utils.Float64ToStr(jxutils.IntCoordinate2Standard(store.Lat)) + "," + utils.Float64ToStr(jxutils.IntCoordinate2Standard(store.Lng)),
		Phone:        store.Tel1,
		ExtendJSON:   string(timeJSON),
		ImageFile:    base64.StdEncoding.EncodeToString(data),
		CategoryName: jdshopapi.JdsStoreCategoryName,
		CustomerID:   utils.Int2Str(store.ID),
	}
	url, _ := getAPI("2").UploadImageNew(data, "2659335b16e3880e367759b8fc675933.tem.png")
	ex := store.LicenceExpire
	if ex == "" {
		ex = utils.Time2Str(utils.Str2Time(store.LicenceValid).AddDate(20, 0, 0))
	}
	if !strings.Contains(ex, "00:00:00") {
		ex += " 00:00:00"
	}
	var url2 string
	if store.Licence != "" {
		data2, _, _ := jxutils.DownloadFileByURL(store.Licence)
		fileName := store.Licence[strings.LastIndex(store.Licence, "/")+1 : len(store.Licence)]
		url2, _ = getAPI("2").UploadImageNew(data2, fileName)
	}
	storeName := store.Name
	if strings.Contains(storeName, "（") {
		storeName = storeName[0:strings.Index(storeName, "（")] + storeName[strings.Index(storeName, "）")+3:len(storeName)]
	}
	if strings.Contains(storeName, "(") {
		storeName = storeName[0:strings.Index(storeName, "(")] + storeName[strings.Index(storeName, ")")+3:len(storeName)]
	}
	if strings.Contains(storeName, ".") {
		storeName = strings.ReplaceAll(storeName, ".", "")
	}
	if strings.Contains(storeName, "-") {
		storeName = strings.ReplaceAll(storeName, "-", "")
	}
	if strings.Contains(storeName, " ") {
		storeName = strings.ReplaceAll(storeName, " ", "")
	}
	storeName = globals.StoreName + strings.ReplaceAll(storeName, "店", "") + "生鲜店"
	if len(storeName) > 30 {
		storeName = utils.LimitUTF8StringLen2(storeName, 30)
	}
	if storeName != store.Name {
		createEntityStoreParam.Name = storeName
	}
	param := &jdshopapi.UpdateBasicParam{
		StoreName:          storeName,
		CategoryID2:        4,
		Coordinate:         utils.Float64ToStr(jxutils.IntCoordinate2Standard(store.Lat)) + "," + utils.Float64ToStr(jxutils.IntCoordinate2Standard(store.Lng)),
		BussinessBeginTime: int2TimeStr(int(store.OpenTime1)),
		BussinessEndTime:   int2TimeStr(int(store.CloseTime1)),
		ImgURL:             url,
		StorePhone:         store.Tel1,
		AddName:            store.Address,
		AddCode3:           store.JdsCode,
		CategoryID1:        3,
	}
	var (
		url3      string
		idCode    string
		startTime string
	)
	if storeDetail.IDCardFront != "" {
		data2, _, _ := jxutils.DownloadFileByURL(storeDetail.IDCardFront)
		fileName := storeDetail.IDCardFront[strings.LastIndex(storeDetail.IDCardFront, "/")+1 : len(storeDetail.IDCardFront)]
		url3, _ = api.JdShopAPI.UploadImageNew(data2, fileName)
	} else {
		data2, _, _ := jxutils.DownloadFileByURL("http://image.jxc4.com/image/a9bfc170a950ab9a4c76bd10b48b222b.tem.jpg")
		fileName := "a9bfc170a950ab9a4c76bd10b48b222b.tem.jpg"
		url3, _ = api.JdShopAPI.UploadImageNew(data2, fileName)
	}
	if storeDetail.IDCode == "" {
		idCode = "610126198012230014"
	} else {
		idCode = storeDetail.IDCode
	}
	if storeDetail.IDValid == "" {
		startTime = "2013-01-25 00:00:00"
	} else {
		startTime = utils.Time2Str(utils.Str2Time(storeDetail.IDValid))
	}
	ex2 := storeDetail.IDExpire
	if ex2 == "" {
		ex2 = utils.Time2Str(utils.Str2Time(storeDetail.IDValid).AddDate(20, 0, 0))
	}
	if !strings.Contains(ex2, "00:00:00") {
		ex2 += " 00:00:00"
	}
	if url2 != "" {
		param.CategoryID1 = 34
		param.CategoryID2 = 62
		param.QualificationRequests = []*jdshopapi.QualificationRequests{
			&jdshopapi.QualificationRequests{
				QualificationID:   41,
				QualificationName: "营业执照",
				QualificationNo:   store.LicenceCode,
				QualificationURL:  url2,
				StartTime:         utils.Time2Str(utils.Str2Time(store.LicenceValid)),
				EndingTime:        ex,
				Time:              []string{utils.Time2Str(utils.Str2Time(store.LicenceValid)), ex},
			},
			&jdshopapi.QualificationRequests{
				QualificationID:   42,
				QualificationName: "身份证件",
				QualificationNo:   idCode,
				QualificationURL:  url3,
				StartTime:         startTime,
				EndingTime:        ex2,
				Time:              []string{startTime, ex2},
			},
		}
	}
	if store.JdsStreetCode != 0 {
		createEntityStoreParam.AddCode = store.JdsStreetCode
		param.AddCode3 = store.JdsStreetCode
	}
	if createEntityStoreParam.AddCode == 0 {
		createEntityStoreParam.AddCode = store.JdCode
		param.AddCode3 = store.JdCode
	}
	//证明这个店可能隶属直辖市或者东莞
	if model.ZXCityCodeMap[store.CityCode] != "" {
		//result, _ := api.AutonaviAPI.GetCoordinateAreaInfo(jxutils.IntCoordinate2Standard(store.Lng), jxutils.IntCoordinate2Standard(store.Lat))
		street, _ := api.TencentMapAPI.GetCoordinateTownInfo(jxutils.IntCoordinate2Standard(store.Lng), jxutils.IntCoordinate2Standard(store.Lat))
		//street := result["regeocode"].(map[string]interface{})["addressComponent"].(map[string]interface{})["township"].(string)
		if street != "" {
			result1, _ := api.JdShopAPI.GetProvince()
			for _, v := range result1 {
				if strings.Contains(store.CityName, v.AreaName) {
					result2, _ := api.JdShopAPI.GetCity(v.AreaID)
					for _, vv := range result2 {
						if strings.Contains(store.DistrictName, vv.AreaName) {
							result3, _ := api.JdShopAPI.GetCounty(vv.AreaID)
							for _, vvv := range result3 {
								if street == vvv.AreaName {
									createEntityStoreParam.AddCode = vvv.AreaID
									param.AddCode3 = vvv.AreaID
									break
								}
							}
						}
					}
				}
			}
		}
	}
	//vendorStoreID, err = api.JdShopAPI.CreateEntityStore(createEntityStoreParam)
	if vendorStroeID2, err := getAPI("2").SubmitBasic(param); err == nil {
		time.Sleep(time.Second)
		err = getAPI("2").UpdateExpand(int(vendorStroeID2))
		//var storeMap *model.StoreMap
		//sql := `
		//	SELECT * FROM store_map WHERE deletad_at = ? AND store_id = ? AND vendor_id = ? AND vendor_org_code = ?
		//`
		//sqlParams := []interface{}{
		//	utils.DefaultTimeValue, storeID, model.VendorIDJDShop, "2",
		//}
		//err = dao.GetRow(db, &storeMap, sql, sqlParams)
		//if storeMap != nil {
		//	storeMap.VendorStoreID = utils.Int64ToStr(vendorStroeID2)
		//	_, err = dao.UpdateEntity(db, storeMap, "VendorStoreID")
		//}
		vendorStoreID = utils.Int64ToStr(vendorStroeID2)
	}
	return vendorStoreID, err
}

func (p *PurchaseHandler) DeleteStore(db *dao.DaoDB, storeID int, userName string) (err error) {
	// store, err := dao.GetStoreDetail(db, storeID, model.VendorIDJDShop)
	// if err != nil {
	// 	return err
	// }
	// err = api.JdShopAPI.DeleteStoresByID(utils.Str2Int64(store.VendorStoreID))
	return err
}

func (p *PurchaseHandler) RefreshAllStoresID(ctx *jxcontext.Context, parentTask tasksch.ITask, isAsync bool) (hint string, err error) {
	return hint, err
}

func (p *PurchaseHandler) GetStoreStatus(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string) (storeStatus int, err error) {
	return storeStatus, err
}

func (p *PurchaseHandler) EnableAutoAcceptOrder(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, isSetEnable bool) (err error) {
	return err
}

func (c *PurchaseHandler) UpdateStoreStatus(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, status int) (err error) {
	err = api.JdShopAPI.UpdateStatus(utils.Str2Int(vendorStoreID), jxStatus2JdsStatus(status))
	return err
}

func (c *PurchaseHandler) UpdateStoreOpTime(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, opTimeList []int16) (err error) {
	return err
}

func (c *PurchaseHandler) GetAllStoresVendorID(ctx *jxcontext.Context, vendorOrgCode string) (vendorStoreIDs []string, err error) {
	return vendorStoreIDs, err
}

func (c *PurchaseHandler) UpdateStoreCustomID(ctx *jxcontext.Context, vendorOrgCode, vendorStoreID string, storeID int64) (err error) {
	return err
}

func int2TimeStr(time int) (str string) {
	str += utils.Int2Str(time / 1000)
	str += utils.Int2Str(time % 1000 / 100)
	str += ":"
	str += utils.Int2Str(time % 100 / 10)
	str += utils.Int2Str(time % 10)
	return str
}

func jxStatus2JdsStatus(status int) (result int) {
	if status == model.StoreStatusOpened {
		result = jdshopapi.JdsStoreStatusOnline
	} else if status == model.StoreStatusHaveRest || status == model.StoreStatusClosed {
		result = jdshopapi.JdsStoreStatusRest
	} else {
		result = jdshopapi.JdsStoreStatusDisable
	}
	return result
}

func JdsStatus2jxStatus(status int) (result int) {
	if status == jdshopapi.JdsStoreStatusOnline {
		result = model.StoreStatusOpened
	} else if status == jdshopapi.JdsStoreStatusRest {
		result = model.StoreStatusClosed
	} else {
		result = model.StoreStatusDisabled
	}
	return result
}

func (c *PurchaseHandler) UpdateStoreLineStatus(ctx *jxcontext.Context, vendorOrgCode string, storeID int, vendorStoreID string, lineStatus int) (err error) {
	return err
}
