package cms

import (
	"git.rosy.net.cn/baseapi/utils"
	"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"
)

// 如果京西门为打开，打开状态为非营业的平台门店
func OpenRemoteStoreByJxStatus(ctx *jxcontext.Context, vendorIDs, storeIDs []int, isForce, isAsync, isContinueWhenError bool) (hint string, err error) {
	db := dao.GetDB()
	status := model.StoreStatusAll
	if !isForce {
		status = model.StoreStatusClosed
	}
	storeMapList, err := dao.GetStoresMapList(db, vendorIDs, storeIDs, nil, status, model.StoreIsSyncYes, "", "", "")
	if err != nil {
		return "", err
	}
	vendorIDMap := make(map[int]int)
	if len(vendorIDs) == 0 {
		for k := range partner.PurchasePlatformHandlers {
			vendorIDMap[k] = 1
		}
	} else {
		for _, v := range vendorIDs {
			vendorIDMap[v] = 1
		}
	}
	task := tasksch.NewParallelTask("OpenRemoteStoreByJxStatus", tasksch.NewParallelConfig().SetIsContinueWhenError(isContinueWhenError), ctx,
		func(task *tasksch.ParallelTask, batchItemList []interface{}, params ...interface{}) (retVal interface{}, err error) {
			storeMap := batchItemList[0].(*model.StoreMap)
			if handler, _ := partner.GetPurchasePlatformFromVendorID(storeMap.VendorID).(partner.IStoreHandler); handler != nil {
				storeDetail, err := dao.GetStoreDetail(db, storeMap.StoreID, storeMap.VendorID, "")
				if err == nil && storeDetail.Status == model.StoreStatusOpened {
					if err = handler.UpdateStoreStatus(ctx, storeMap.VendorOrgCode, storeMap.StoreID, storeMap.VendorStoreID, model.StoreStatusOpened); err == nil {
						storeMap.Status = model.StoreStatusOpened
						dao.UpdateEntity(db, storeMap, model.FieldStatus)
						retVal = []int{1}
					}
				}
			}
			return retVal, err
		}, storeMapList)
	tasksch.HandleTask(task, nil, true).Run()

	if isAsync {
		hint = task.GetID()
	} else {
		resultList, err2 := task.GetResult(0)
		if err = err2; err == nil {
			hint = utils.Int2Str(len(resultList))
		}
	}
	return hint, err
}
