package dao

import (
	"errors"
	"fmt"
	"git.rosy.net.cn/jx-print/dao"
	"sort"
	"strings"
	"time"

	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/model"
)

func (s *StoreDetail) GetPricePerentage(price int) (pricePercentage int) {
	return pricePercentage
}

func getStoreDetail(db *DaoDB, storeID, vendorID int, vendorStoreID, vendorOrgCode string) (storeDetail *StoreDetail, err error) {
	sql := `
	SELECT t1.*,
	t2.vendor_store_id, t2.status vendor_status, t2.delivery_fee_deduction_sill, t2.delivery_fee_deduction_fee, t2.sync_status, t2.vendor_org_code,
	t2.price_percentage, t2.auto_pickup, t2.delivery_type, t2.delivery_competition, t2.is_sync, t2.vendor_store_name, t2.is_order, t2.yb_app_id, t2.yb_app_key, t2.yb_store_prefix,
	t2.jds_street_code, t2.jds_street_name, t2.is_supply_goods, t2.vendor_pay_percentage, t2.mtwm_token, t2.ebai_supplier_id, t2.create_delivery_type,t2.is_service,t2.delivery_self,
	t3.value price_percentage_pack_str,
	t4.value freight_deduction_pack_str,
	province.name province_name,
	province.code province_code,
	district.name district_name,
	district.jds_code jds_code,
	district.jd_code jd_code,
	city.jd_code jd_city_code,
	city.name city_name,
	IF(mm.name <> '', mm.name, mm.user_id2) market_man_name,
	IF(om.name <> '', om.name, om.user_id2) operator_name,
	IF(om2.name <> '', om2.name, om2.user_id2) operator_name2,
	IF(om3.name <> '', om3.name, om3.user_id2) operator_name3,
	b.name brand_name,
	b.logo brand_logo,
	b.is_open brand_is_open,
	b.is_print brand_is_print
	FROM store t1
	LEFT JOIN store_map t2 ON t1.id = t2.store_id AND t2.vendor_id = ? AND t2.deleted_at = ?
	LEFT JOIN place city ON city.code = t1.city_code
	LEFT JOIN place district ON district.code = t1.district_code
	LEFT JOIN place province ON city.parent_code = province.code
	LEFT JOIN new_config t3 ON t3.key = t2.price_percentage_pack AND t3.type = ? AND t3.deleted_at = ?
	LEFT JOIN new_config t4 ON t4.key = t2.freight_deduction_pack AND t4.type = ? AND t4.deleted_at = ?
	LEFT JOIN user mm ON mm.mobile <> '' AND mm.mobile = t1.market_man_phone 
	LEFT JOIN user om ON om.mobile <> '' AND om.mobile = t1.operator_phone 
	LEFT JOIN user om2 ON om2.mobile <> '' AND om2.mobile = t1.operator_phone2
	LEFT JOIN user om3 ON om3.mobile <> '' AND om3.mobile = t1.operator_phone3
	LEFT JOIN brand b ON b.id = t1.brand_id AND b.deleted_at = ?
	WHERE t1.deleted_at = ?	
	`
	sqlParams := []interface{}{
		vendorID,
		utils.DefaultTimeValue,
		model.ConfigTypePricePack,
		utils.DefaultTimeValue,
		model.ConfigTypeFreightPack,
		utils.DefaultTimeValue,
		utils.DefaultTimeValue,
		utils.DefaultTimeValue,
	}
	// if vendorID != model.VendorIDJX {
	// 	sql += " AND t2.id IS NOT NULL"
	// }
	if storeID > 0 {
		sql += " AND t1.id = ?"
		sqlParams = append(sqlParams, storeID)
	}
	if vendorStoreID != "" {
		sql += " AND t2.vendor_store_id = ?"
		sqlParams = append(sqlParams, vendorStoreID)
	}
	if vendorOrgCode != "" {
		sql += " AND t2.vendor_org_code = ?"
		sqlParams = append(sqlParams, vendorOrgCode)
	}
	//if vendorID == model.VendorIDJDShop && vendorOrgCode == "" {
	//	sql += " AND t2.vendor_org_code = 2"
	//}
	if err = GetRow(db, &storeDetail, sql, sqlParams...); err == nil {
		storeDetail.PricePercentagePackObj = PricePercentagePack2Obj(storeDetail.PricePercentagePackStr)
		storeDetail.FreightDeductionPackObj = FreightDeductionPack2Obj(storeDetail.FreightDeductionPackStr)
		// if storeDetail.VendorStoreID == "" {
		// 	storeDetail.VendorStatus = storeDetail.Status
		// 	storeDetail.PricePercentage = model.DefVendorPricePercentage
		// 	storeDetail.AutoPickup = 1
		// 	storeDetail.DeliveryType = model.StoreDeliveryTypeByStore
		// 	storeDetail.DeliveryCompetition = 1
		// 	if vendorID == model.VendorIDJX {
		// 		storeDetail.IsSync = 1
		// 	}
		// }
		return storeDetail, nil
	}
	return nil, err
}

func GetStoreDetail(db *DaoDB, storeID, vendorID int, vendorOrgCode string) (storeDetail *StoreDetail, err error) {
	return getStoreDetail(db, storeID, vendorID, "", vendorOrgCode)
}

func GetStoreDetailForDD(db *DaoDB, storeID, vendorID int, vendorStoreID, vendorOrgCode string) (storeDetail *StoreDetail, err error) {
	return getStoreDetail(db, storeID, vendorID, vendorStoreID, vendorOrgCode)
}

func GetStoreDetailByVendorStoreID(db *DaoDB, vendorStoreID string, vendorID int, vendorOrgCode string) (storeDetail *StoreDetail, err error) {
	if vendorID != model.VendorIDJX {
		return getStoreDetail(db, 0, vendorID, vendorStoreID, vendorOrgCode)
	}
	if storeDetail, err = getStoreDetail(db, int(utils.Str2Int64WithDefault(vendorStoreID, 0)), vendorID, "", vendorOrgCode); err == nil {
		storeDetail.VendorStoreID = vendorStoreID
	}
	return storeDetail, err
}

// 这个返回的地点信息是城市
func GetStoreDetail2(db *DaoDB, storeID int, vendorStoreID string, vendorID int) (storeDetail *StoreDetail2, err error) {
	sql := `
	SELECT t1.*,
	city.name city_name, district.name district_name,
	t3.vendor_store_id, t3.vendor_id, t3.status courier_status, t3.audit_status
	FROM store t1
	LEFT JOIN place city ON city.code = t1.city_code
	LEFT JOIN place district ON district.code = t1.district_code
	LEFT JOIN store_courier_map t3 ON t3.store_id = t1.id AND t3.vendor_id = ? AND t3.deleted_at = ?
	WHERE t1.deleted_at = ?`
	sqlParams := []interface{}{
		vendorID,
		utils.DefaultTimeValue,
		utils.DefaultTimeValue,
	}
	if storeID != 0 {
		sql += " AND t1.id = ?"
		sqlParams = append(sqlParams, storeID)
	}
	if vendorStoreID != "" {
		sql += " AND t3.vendor_store_id = ?"
		sqlParams = append(sqlParams, vendorStoreID)
	}
	err = GetRow(db, &storeDetail, sql, sqlParams...)
	return storeDetail, err
}

func GetStoreCourierList(db *DaoDB, storeIDs, vendorIDs []int, status, auditStatus int) (courierStoreList []*model.StoreCourierMap, err error) {
	sql := `
	SELECT t1.*
	FROM store_courier_map t1
	WHERE t1.deleted_at = ?
	`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
	}
	if len(storeIDs) > 0 {
		sql += " AND t1.store_id IN (" + GenQuestionMarks(len(storeIDs)) + ")"
		sqlParams = append(sqlParams, storeIDs)
	}
	if len(vendorIDs) > 0 {
		sql += " AND t1.vendor_id IN (" + GenQuestionMarks(len(vendorIDs)) + ")"
		sqlParams = append(sqlParams, vendorIDs)
	}
	if status != model.StoreStatusAll {
		sql += " AND t1.status = ?"
		sqlParams = append(sqlParams, status)
	}
	if auditStatus != model.StoreAuditStatusAll {
		sql += " AND t1.audit_status = ?"
		sqlParams = append(sqlParams, auditStatus)
	}
	if err = GetRows(db, &courierStoreList, sql, sqlParams...); err == nil {
		return courierStoreList, nil
	}
	return nil, err
}

func GetStoreCourierList2(db *DaoDB, storeIDs, vendorIDs []int, status int, auditStatuss []int) (courierStoreList []*model.StoreCourierMap, err error) {
	sql := `
	SELECT t1.*
	FROM store_courier_map t1
	WHERE t1.deleted_at = ?
	`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
	}
	if len(storeIDs) > 0 {
		sql += " AND t1.store_id IN (" + GenQuestionMarks(len(storeIDs)) + ")"
		sqlParams = append(sqlParams, storeIDs)
	}
	if len(vendorIDs) > 0 {
		sql += " AND t1.vendor_id IN (" + GenQuestionMarks(len(vendorIDs)) + ")"
		sqlParams = append(sqlParams, vendorIDs)
	}
	if status != model.StoreStatusAll {
		sql += " AND t1.status = ?"
		sqlParams = append(sqlParams, status)
	}
	if len(auditStatuss) > 0 {
		sql += " AND t1.audit_status IN (" + GenQuestionMarks(len(auditStatuss)) + ")"
		sqlParams = append(sqlParams, auditStatuss)
	}
	if err = GetRows(db, &courierStoreList, sql, sqlParams...); err == nil {
		return courierStoreList, nil
	}
	return nil, err
}

func GetStoresMapList2(db *DaoDB, vendorIDs, storeIDs, storeStatuss []int, status, isSync int, pricePack, name, vendorOrgCode string, mustDirty bool) (storeMapList []*model.StoreMap, err error) {
	sql := `	
	SELECT t1.*
	FROM store_map t1
	JOIN store t2 ON t2.id = t1.store_id AND t2.deleted_at = ?
	WHERE t1.deleted_at = ?
	`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
		utils.DefaultTimeValue,
	}

	if len(vendorIDs) > 0 {
		sql += " AND t1.vendor_id IN (" + GenQuestionMarks(len(vendorIDs)) + ")"
		sqlParams = append(sqlParams, vendorIDs)
	}
	if len(storeIDs) > 0 {
		sql += " AND t1.store_id IN (" + GenQuestionMarks(len(storeIDs)) + ")"
		sqlParams = append(sqlParams, storeIDs)
	}
	if len(storeStatuss) > 0 {
		sql += " AND t2.status IN (" + GenQuestionMarks(len(storeStatuss)) + ")"
		sqlParams = append(sqlParams, storeStatuss)
	}
	if status != model.StoreStatusAll {
		sql += " AND t1.status <> ?"
		sqlParams = append(sqlParams, status)
	}
	if isSync != model.StoreIsSyncAll {
		sql += " AND t1.is_sync = ?"
		sqlParams = append(sqlParams, isSync)
	}
	if pricePack != "" {
		sql += " AND t1.price_percentage_pack = ?"
		sqlParams = append(sqlParams, pricePack)
	}
	if name != "" {
		sql += " AND t2.name LIKE ?"
		sqlParams = append(sqlParams, "%"+name+"%")
	}
	if vendorOrgCode != "" {
		sql += " AND t1.vendor_org_code = ?"
		sqlParams = append(sqlParams, vendorOrgCode)
	}
	if mustDirty {
		sql += " AND t1.sync_status <> 0"
	}
	sql += " ORDER BY t1.store_id , t1.vendor_id"
	if err = GetRows(db, &storeMapList, sql, sqlParams...); err == nil {
		return storeMapList, nil
	}
	return nil, err
}

func SetStoresMapSyncStatus(db *DaoDB, vendorIDs, storeIDs []int, syncStatus int8) (err error) {
	sql := `
	UPDATE store_map t1
	JOIN store t2 ON t2.id = t1.store_id AND t2.deleted_at = ?
	SET t1.sync_status = t1.sync_status | ?
	WHERE t1.deleted_at = ?
	`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
		syncStatus,
		utils.DefaultTimeValue,
	}
	if len(vendorIDs) > 0 {
		sql += " AND t1.vendor_id IN (" + GenQuestionMarks(len(vendorIDs)) + ")"
		sqlParams = append(sqlParams, vendorIDs)
	}
	if len(storeIDs) > 0 {
		sql += " AND t1.store_id IN (" + GenQuestionMarks(len(storeIDs)) + ")"
		sqlParams = append(sqlParams, storeIDs)
	}
	_, err = ExecuteSQL(db, sql, sqlParams...)
	return err
}

func GetStoresMapList(db *DaoDB, vendorIDs, storeIDs, storeStatuss []int, status, isSync int, pricePack, name, vendorOrgCode string) (storeMapList []*model.StoreMap, err error) {
	return GetStoresMapList2(db, vendorIDs, storeIDs, storeStatuss, status, isSync, pricePack, name, vendorOrgCode, false)
}

func StoreMapList2Map(storeMapList []*model.StoreMap) (storeMapMap map[int][]*model.StoreMap) {
	storeMapMap = make(map[int][]*model.StoreMap)
	for _, v := range storeMapList {
		storeMapMap[v.StoreID] = append(storeMapMap[v.StoreID], v)
	}
	return storeMapMap
}

func StoreCourierList2Map(storeCourierList []*model.StoreCourierMap) (storeCourierMap map[int][]*model.StoreCourierMap) {
	storeCourierMap = make(map[int][]*model.StoreCourierMap)
	for _, v := range storeCourierList {
		storeCourierMap[v.StoreID] = append(storeCourierMap[v.StoreID], v)
	}
	return storeCourierMap
}

// 此函数在检测到一个门店的所有平台状态一样，且不为StoreStatusOpened时，
// 将平台门店状态全部改为StoreStatusOpened，则把京西门店状态改为之前那个统一的平台门店状态
func FormalizeStoreStatus(db *DaoDB, storeID, storeStatus int) (err error) {
	sql := `
	SELECT DISTINCT t1.status
	FROM store_map t1
	WHERE t1.deleted_at = ? AND t1.store_id = ?
	`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
		storeID,
	}
	var statusList []int
	if err = GetRows(db, &statusList, sql, sqlParams...); err == nil {
		if len(statusList) == 1 {
			if statusList[0] != model.StoreStatusOpened {
				txDB, _ := Begin(db)
				defer func() {
					if r := recover(); r != nil || err != nil {
						Rollback(db, txDB)
						if r != nil {
							panic(r)
						}
					}
				}()
				if storeStatus != statusList[0] {
					store := &model.Store{}
					store.ID = storeID
					if _, err = UpdateEntityLogically(db, store, map[string]interface{}{
						model.FieldStatus: statusList[0],
					}, model.AdminName, nil); err != nil {
						return err
					}
				}
				if _, err = UpdateEntityLogically(db, &model.StoreMap{}, map[string]interface{}{
					model.FieldStatus: model.StoreStatusOpened,
				}, model.AdminName, map[string]interface{}{
					model.FieldStoreID:   storeID,
					model.FieldDeletedAt: utils.DefaultTimeValue,
				}); err != nil {
					return err
				}
				Commit(db, txDB)
			}
		}
	}
	return err
}

func GetVendorStoreSnapshot(db *DaoDB, snapshotAt time.Time) (snapshotList []*model.VendorStoreSnapshot, err error) {
	sql := `
	SELECT t1.*
	FROM vendor_store_snapshot t1
	LEFT JOIN store t2 ON t2.id = t1.store_id
	WHERE t1.snapshot_at = ?
	ORDER BY t2.city_code, t1.store_id, t1.vendor_id`
	err = GetRows(db, &snapshotList, sql, snapshotAt)
	return snapshotList, err
}

func DeleteVendorStoreSnapshot(db *DaoDB, minSnapshotAt time.Time) (err error) {
	_, err = ExecuteSQL(db, `
	DELETE t1
	FROM vendor_store_snapshot t1
	WHERE t1.snapshot_at < ?
	`, minSnapshotAt)
	return err
}

func GetRebindPrinterStoreList(db *DaoDB) (storeList []*model.Store, err error) {
	err = GetRows(db, &storeList, `
	SELECT *
	FROM store t1
	WHERE t1.deleted_at = ? AND printer_vendor_id >= ? AND printer_bind_info <> ''
	`, utils.DefaultTimeValue, model.VendorIDPrinterBegin)
	return storeList, err
}

func PricePercentagePack2Obj(packStr string) (obj model.PricePercentagePack) {
	if packStr != "" {
		var floatObj []*tPricePercentageItemFloat
		if err := utils.UnmarshalUseNumber([]byte(packStr), &floatObj); err == nil {
			if len(floatObj) > 0 {
				obj = make(model.PricePercentagePack, len(floatObj))
				for k, v := range floatObj {
					if v.PricePercentage >= 500 || v.PricePercentage <= 80 {
						return nil
					}
					obj[k] = &model.PricePercentageItem{
						BeginPrice:      int(v.BeginPrice),
						PricePercentage: int(v.PricePercentage),
						PriceAdd:        int(v.PriceAdd),
					}
				}
				sort.Sort(obj)
			}
		}
	}
	return obj
}

func AddStoreCategoryMap(db *DaoDB, storeID, categoryID int, vendorID int, vendorCategoryID string, status int8, userName string) (err error) {
	storeCat := &model.StoreSkuCategoryMap{
		StoreID:        storeID,
		CategoryID:     categoryID,
		MtwmSyncStatus: model.SyncFlagNewMask,
		TaoSyncStatus:  model.SyncFlagNewMask,
		EbaiSyncStatus: model.SyncFlagNewMask,
		DdSyncStatus:   model.SyncFlagNewMask,
		YbSyncStatus:   model.SyncFlagNewMask,
	}
	storeCat.DeletedAt = utils.DefaultTimeValue
	if err = GetEntity(db, storeCat, model.FieldStoreID, model.FieldCategoryID, model.FieldDeletedAt); err != nil && !IsNoRowsError(err) {
		return err
	}
	if vendorID == model.VendorIDMTWM {
		storeCat.MtwmID = vendorCategoryID
		storeCat.MtwmSyncStatus = status
	} else if vendorID == model.VendorIDEBAI {
		storeCat.EbaiID = utils.Str2Int64WithDefault(vendorCategoryID, 0)
		storeCat.EbaiSyncStatus = status
	} else if vendorID == model.VendorIDYB {
		storeCat.YbID = utils.Str2Int64WithDefault(vendorCategoryID, 0)
		storeCat.YbSyncStatus = status
	} else if vendorID == model.VendorIDJDShop {
		storeCat.JdsID = utils.Str2Int64WithDefault(vendorCategoryID, 0)
		storeCat.JdsSyncStatus = status
	} else if vendorID == model.VendorIDDD {
		storeCat.DdID = vendorCategoryID
		storeCat.DdSyncStatus = status
	} else if vendorID == model.VendorIDTaoVegetable {
		storeCat.TaoID = vendorCategoryID
		storeCat.TaoSyncStatus = status
	} else {
		panic("unsupported vendor")
	}
	if storeCat.ID == 0 {
		WrapAddIDCULDEntity(storeCat, userName)
		if err = CreateEntity(db, storeCat); IsDuplicateError(err) {
			err = nil
		}
	} else {
		WrapUpdateULEntity(storeCat, userName)
		_, err = UpdateEntity(db, storeCat)
	}
	return err
}

func GetOpenedStoreCouriersByStoreID(db *DaoDB, storeID, vendorID int) (storeMaps []*model.StoreCourierMap, err error) {
	if db == nil {
		db = GetDB()
	}
	if err = utils.CallFuncLogError(func() error {
		sql := `
		SELECT *
		FROM store_courier_map
		WHERE store_id = ? AND status = ? AND deleted_at = ?
		`
		sqlParams := []interface{}{
			storeID,
			model.StoreStatusOpened,
			utils.DefaultTimeValue,
		}
		if vendorID != -1 {
			sql += " AND vendor_id = ?"
			sqlParams = append(sqlParams, vendorID)
		}
		return GetRows(db, &storeMaps, sql, sqlParams...)
	}, "GetStoreCouriersByStoreID storeID:%d, vendorID:%d", storeID, vendorID); err != nil {
		return nil, err
	}
	return storeMaps, nil
}

func GetStoreList(db *DaoDB, idList, cityCodes, statuss, brandIDs []int, mobileList []string, shortRoleName string) (storeList []*model.Store, err error) {
	sql := `
	SELECT t1.*
	FROM store t1
	WHERE t1.deleted_at = ?`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
	}
	if len(idList) > 0 {
		sql += "  AND t1.id IN (" + GenQuestionMarks(len(idList)) + ")"
		sqlParams = append(sqlParams, idList)
	}
	if len(cityCodes) > 0 {
		sql += "  AND t1.city_code IN (" + GenQuestionMarks(len(cityCodes)) + ")"
		sqlParams = append(sqlParams, cityCodes)
	}
	if len(statuss) > 0 {
		sql += "  AND t1.status IN (" + GenQuestionMarks(len(statuss)) + ")"
		sqlParams = append(sqlParams, statuss)
	}
	if len(brandIDs) > 0 {
		sql += "  AND t1.brand_id IN (" + GenQuestionMarks(len(brandIDs)) + ")"
		sqlParams = append(sqlParams, brandIDs)
	}
	if len(mobileList) > 0 {
		sql += "  AND (t1.tel1 IN (" + GenQuestionMarks(len(mobileList)) + ") OR t1.tel2 IN (" + GenQuestionMarks(len(mobileList)) + "))"
		sqlParams = append(sqlParams, mobileList, mobileList)
	}
	if shortRoleName != "" {
		sql += "  AND (t1.market_man_role = ? OR t1.operator_role = ? OR t1.operator_role2 = ? OR t1.operator_role3 = ?)"
		sqlParams = append(sqlParams, shortRoleName, shortRoleName, shortRoleName, shortRoleName)
	}

	sql += ` ORDER BY id `
	err = GetRows(db, &storeList, sql, sqlParams...)
	return storeList, err
}

func GetCityBankBranches(db *DaoDB, cityCode int, bankCode string) (list []*CityBrankBranch, err error) {
	sql := `
	SELECT payee_bank_code, city_code, payee_bank_branch_name
	FROM store
	WHERE payee_bank_branch_name <> ''`
	sqlParams := []interface{}{}
	if cityCode > 0 {
		sql += " AND city_code = ?"
		sqlParams = append(sqlParams, cityCode)
	} else {
		sql += " AND city_code <> 0"
	}
	if bankCode != "" {
		sql += " AND payee_bank_code = ?"
		sqlParams = append(sqlParams, bankCode)
	} else {
		sql += " AND payee_bank_code <> ''"
	}
	sql += " GROUP BY 1,2,3;"
	err = GetRows(db, &list, sql, sqlParams...)
	return list, err
}

func FreightDeductionPack2Obj(packStr string) (obj *model.FreightDeductionPack) {
	if packStr != "" {
		if err := utils.UnmarshalUseNumber([]byte(packStr), &obj); err == nil {
			sort.Sort(obj)
		}
	}
	return obj
}

func GetStoreMapsListWithoutDisabled(db *DaoDB, vendorIDs []int, status int) (storeMapList []*model.StoreMap, err error) {
	sql := `
		SELECT *
		FROM store_map
		WHERE 1=1
	`
	sqlParams := []interface{}{}
	if len(vendorIDs) > 0 {
		sql += " AND vendor_id in (" + GenQuestionMarks(len(vendorIDs)) + ")"
		sqlParams = append(sqlParams, vendorIDs)
	}
	if status != model.StoreStatusAll {
		sql += " AND status != ?"
		sqlParams = append(sqlParams, status)
	}
	err = GetRows(db, &storeMapList, sql, sqlParams...)
	return storeMapList, err
}

func GetStorePriceScore(db *DaoDB, storeIDs, vendorIDs []int, fromScore, toScore, sort int, snapDate time.Time, offset, pageSize int) (StorePriceScore []*StorePriceScore, totalCount int, err error) {
	sql := `
		SELECT SQL_CALC_FOUND_ROWS a.store_id, score store_score, e.name city_name, b.name store_name, t2.direct_down_count, t2.sec_kill_count
		FROM store_price_score_snapshot a
		JOIN store b ON b.id = a.store_id
		JOIN place e ON e.code = b.city_code
		LEFT JOIN (SELECT t1.store_id,count(t1.type = ? OR NULL) direct_down_count, count(t1.type = ? OR NULL) sec_kill_count
					FROM(
						SELECT a.store_id, a.sku_id,d.type
						FROM store_sku_bind a
						LEFT JOIN act_store_sku b ON a.store_id = b.store_id AND b.sku_id = a.sku_id
						LEFT JOIN act_map c ON c.act_id = b.act_id
						LEFT JOIN act d ON d.id = c.act_id
						WHERE 1=1
						AND d.status = ?
	`
	sqlParams := []interface{}{
		model.ActSkuDirectDown, model.ActSkuSecKill, model.ActStatusCreated,
	}
	if len(storeIDs) > 0 {
		sql += " AND a.store_id IN(" + GenQuestionMarks(len(storeIDs)) + ")"
		sqlParams = append(sqlParams, storeIDs)
	}
	if len(vendorIDs) > 0 {
		sql += " AND c.vendor_id IN(" + GenQuestionMarks(len(vendorIDs)) + ")"
		sqlParams = append(sqlParams, vendorIDs)
	}
	sql += `
				AND NOW() BETWEEN d.begin_at AND d.end_at
				AND a.status = ?
				AND a.deleted_at = ? AND b.deleted_at = ? AND c.deleted_at = ? AND d.deleted_at = ?
				GROUP BY 1,2,3)t1 
				GROUP BY 1)t2 ON t2.store_id = a.store_id
		WHERE 1=1
	`
	sqlParams = append(sqlParams, model.StoreSkuBindStatusNormal, utils.DefaultTimeValue, utils.DefaultTimeValue, utils.DefaultTimeValue, utils.DefaultTimeValue)
	if fromScore != 0 || toScore != 0 {
		sql += " AND a.score BETWEEN ? AND ?"
		sqlParams = append(sqlParams, fromScore, toScore)
	}
	if len(storeIDs) > 0 {
		sql += " AND a.store_id IN(" + GenQuestionMarks(len(storeIDs)) + ")"
		sqlParams = append(sqlParams, storeIDs)
	}
	if !utils.IsTimeZero(snapDate) {
		sql += " AND a.snapshot_at = ?"
		sqlParams = append(sqlParams, snapDate)
	}
	if sort == 1 {
		sql += " ORDER BY a.score"
	} else if sort == -1 {
		sql += " ORDER BY a.score DESC"
	} else if sort == 2 {
		sql += " ORDER BY t2.direct_down_count"
	} else if sort == -2 {
		sql += " ORDER BY t2.direct_down_count DESC"
	} else if sort == 3 {
		sql += " ORDER BY t2.sec_kill_count"
	} else if sort == -3 {
		sql += " ORDER BY t2.sec_kill_count DESC"
	}
	sql += " LIMIT ? OFFSET ?"
	sqlParams = append(sqlParams, pageSize, offset)
	txDB, _ := Begin(db)
	defer Commit(db, txDB)
	if err = GetRowsTx(txDB, &StorePriceScore, sql, sqlParams...); err == nil {
		totalCount = GetLastTotalRowCount2(db, txDB)
	}
	return StorePriceScore, totalCount, err
}

func GetStorePriceScoreSnapshot(db *DaoDB, snapDate time.Time) (storePriceScoreSnapshot []*model.StorePriceScoreSnapshot, err error) {
	sql := `
		SELECT c.store_id,ROUND(count(c.unit_price * IF(d.pay_percentage < 50 , 70, d.pay_percentage) / 100 <= a.mid_unit_price or NULL)/count(*)*100,2) score
		FROM price_refer_snapshot a
		JOIN store_sku_bind c ON c.sku_id = a.sku_id AND c.deleted_at = ?
		JOIN store d ON c.store_id = d.id AND d.city_code = a.city_code AND d.deleted_at = ? AND d.status != ?
		WHERE 1=1
	`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
		utils.DefaultTimeValue, model.StoreStatusDisabled,
	}
	if !utils.IsTimeZero(snapDate) {
		sql += " AND a.snapshot_at = ?"
		sqlParams = append(sqlParams, snapDate)
	}
	sql += `
		GROUP BY c.store_id
	`
	err = GetRows(db, &storePriceScoreSnapshot, sql, sqlParams...)
	return storePriceScoreSnapshot, err
}

func SetStoreMapSyncStatus(db *DaoDB, vendorIDs, storeIDs []int, syncStatus int) (num int64, err error) {
	sql := `
	UPDATE store_map t1
	SET t1.sync_status = t1.sync_status | ?
	`
	sqlParams := []interface{}{
		syncStatus,
	}
	sql += " WHERE t1.is_sync <> 0 AND t1.deleted_at = ? AND t1.sync_status & ? = 0"
	sqlParams = append(sqlParams, utils.DefaultTimeValue, model.SyncFlagDeletedMask)
	if len(vendorIDs) > 0 {
		sql += " AND t1.vendor_id IN (" + GenQuestionMarks(len(vendorIDs)) + ")"
		sqlParams = append(sqlParams, vendorIDs)
	}
	if len(storeIDs) > 0 {
		sql += " AND t1.store_id IN (" + GenQuestionMarks(len(storeIDs)) + ")"
		sqlParams = append(sqlParams, storeIDs)
	}
	return ExecuteSQL(db, sql, sqlParams...)
}

func GetOrderNotifyPhones(db *DaoDB, storeID int) (phoneList []string) {
	store := &model.Store{}
	store.ID = storeID
	if err := GetEntity(db, store); err == nil {
		if store.SMSNotify != 0 {
			telMap := make(map[string]int)
			for _, v := range []string{store.Tel1, store.Tel2} {
				if v != "" {
					telMap[v] = 1
				}
			}
			phoneList = jxutils.StringMap2List(telMap)
		}
	}
	return phoneList
}

func GetStoreLinkStores(db *DaoDB, storeID int) (storeList []*model.Store, err error) {
	sql := `
	SELECT t1.*
	FROM store t1
	WHERE t1.link_store_id = ? AND t1.deleted_at = ?
	`
	sqlParams := []interface{}{
		storeID,
		utils.DefaultTimeValue,
	}
	err = GetRows(db, &storeList, sql, sqlParams...)
	return storeList, err
}

func GetRealLinkStoreID(db *DaoDB, linkStoreID int) (realLinkStoreID int, err error) {
	realLinkStoreID = linkStoreID
	if linkStoreID != 0 {
		store := &model.Store{}
		store.ID = linkStoreID
		if err = GetEntity(db, store); err == nil {
			if store.LinkStoreID != 0 {
				realLinkStoreID = store.LinkStoreID
			} else {
				realLinkStoreID = linkStoreID
			}
		}
	}
	return realLinkStoreID, err
}

func GetStoreCategoryMap(db *DaoDB, parentID, level, storeID, categoryID int) (storeCatMaps []*model.StoreCategoryMap, err error) {
	sql := `
		SELECT a.* 
		FROM store_category_map a
		WHERE a.deleted_at = ?
	`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
	}
	if parentID >= 0 {
		sql += " AND a.parent_id = ?"
		sqlParams = append(sqlParams, parentID)
	}
	if level > 0 {
		sql += " AND a.level = ?"
		sqlParams = append(sqlParams, level)
	}
	if storeID > 0 {
		sql += " AND a.store_id = ?"
		sqlParams = append(sqlParams, storeID)
	}
	if categoryID > 0 {
		sql += " AND a.category_id = ?"
		sqlParams = append(sqlParams, categoryID)
	}
	sql += " ORDER BY a.level, a.store_category_seq"
	err = GetRows(db, &storeCatMaps, sql, sqlParams)
	if err != nil {
		return nil, err
	}
	return storeCatMaps, err
}

func InsertStoreCategories(db *DaoDB, userName string, storeID int) (err error) {
	sql := `
		INSERT INTO store_category_map 
		(created_at, updated_at, last_operator, deleted_at, store_id, category_id, store_category_name, store_category_seq, level, parent_id,is_hidden)
		SELECT ?, ?, ?, ?, ?, id, name, seq, level, parent_id,is_hidden
		FROM sku_category 
		WHERE deleted_at = ? 
		AND is_exd_spec = ?
	`
	sqlParams := []interface{}{
		time.Now(), time.Now(), userName, utils.DefaultTimeValue, storeID,
		utils.DefaultTimeValue, model.NO,
	}
	_, err = ExecuteSQL(db, sql, sqlParams)
	return err
}

func DeleteStoreCategroies(db *DaoDB, userName string, storeID int) (err error) {
	sql := `
		UPDATE store_category_map 
		SET deleted_at = ?, last_operator = ?
		WHERE deleted_at <> ? 
		AND store_id = ?
	`
	sqlParams := []interface{}{
		time.Now(), userName,
		utils.DefaultTimeValue,
		storeID,
	}
	_, err = ExecuteSQL(db, sql, sqlParams)
	return err
}

func DeleteStoreCategroies2(db *DaoDB, storeID int) (err error) {
	sql := `
		DELETE FROM store_category_map WHERE store_id = ?
	`
	sqlParams := []interface{}{
		storeID,
	}
	_, err = ExecuteSQL(db, sql, sqlParams)
	return err
}

func GetStorePushClient(db *DaoDB, storeID int, cID string) (storePushClient []*model.StorePushClient, err error) {
	sql := `
		SELECT * 
		FROM store_push_client
		WHERE deleted_at = ?
	`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
	}
	if storeID > 0 {
		sql += " AND store_id = ?"
		sqlParams = append(sqlParams, storeID)
	}
	if cID != "" {
		sql += " AND client_id = ?"
		sqlParams = append(sqlParams, cID)
	}
	err = GetRows(db, &storePushClient, sql, sqlParams)
	if err != nil {
		return nil, err
	}
	return storePushClient, err
}

func GetStoreAudit(db *DaoDB, auditStatuss []int, userID, keyword string) (storeAudit []*model.StoreAudit, err error) {
	sql := `
		SELECT * 
		FROM store_audit
		WHERE deleted_at = ?
	`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
	}
	if len(auditStatuss) > 0 {
		sql += " AND audit_status IN (" + GenQuestionMarks(len(auditStatuss)) + ")"
		sqlParams = append(sqlParams, auditStatuss)
	}
	if userID != "" {
		sql += " AND user_id = ?"
		sqlParams = append(sqlParams, userID)
	}
	if keyword != "" {
		sql += " AND (user_id LIKE ? OR name LIKE ? OR tel1 LIKE ? OR tel2 LIKE ? OR address LIKE ?)"
		sqlParams = append(sqlParams, "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
	}
	err = GetRows(db, &storeAudit, sql, sqlParams)
	if err != nil {
		return nil, err
	}
	return storeAudit, err
}

func GetStoreAuditPage(db *DaoDB, statuss []int, keyword string, applyTimeStart, applyTimeEnd, auditTimeStart, auditTimeEnd time.Time, pageSize, offset int) (pagedInfo *model.PagedInfo, err error) {
	var requestList []*tStoreAudit
	sql := `
		SELECT SQL_CALC_FOUND_ROWS DISTINCT a.*, b.name user_name, c.name city_name
		FROM store_audit a 
		LEFT JOIN user b ON b.user_id = a.user_id 
		LEFT JOIN place c ON c.code = a.city_code 
		WHERE a.deleted_at = ?
	`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
	}
	if len(statuss) > 0 {
		sql += " AND a.audit_status IN (" + GenQuestionMarks(len(statuss)) + ")"
		sqlParams = append(sqlParams, statuss)
	}
	if applyTimeStart != utils.ZeroTimeValue && applyTimeEnd != utils.ZeroTimeValue {
		sql += " AND a.created_at BETWEEN ? AND ?"
		sqlParams = append(sqlParams, applyTimeStart, applyTimeEnd)
	}
	if auditTimeStart != utils.ZeroTimeValue && auditTimeEnd != utils.ZeroTimeValue {
		sql += " AND a.updated_at BETWEEN ? AND ?"
		sqlParams = append(sqlParams, auditTimeStart, auditTimeEnd)
	}
	if keyword != "" {
		sql += " AND (a.user_id LIKE ? OR a.name LIKE ? OR a.tel1 LIKE ? OR a.tel2 LIKE ? OR a.address LIKE ?)"
		sqlParams = append(sqlParams, "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
	}
	sql += " ORDER BY a.updated_at LIMIT ? OFFSET ?"
	pageSize = jxutils.FormalizePageSize(pageSize)
	sqlParams = append(sqlParams, pageSize, offset)
	txDB, _ := Begin(db)
	defer Commit(db, txDB)
	if err = GetRowsTx(txDB, &requestList, sql, sqlParams...); err == nil {
		return &model.PagedInfo{
			TotalCount: GetLastTotalRowCount2(db, txDB),
			Data:       requestList,
		}, nil
	}
	return pagedInfo, err
}

func GetBrands(db *DaoDB, name string, brandID int, poolKey string, isManage bool, userID string) (brands []*model.Brand, err error) {
	sqlParams := []interface{}{}
	sql := `
		SELECT a.* 
		  FROM brand a 
	`
	if isManage {
		sql += ` JOIN brand_user b ON a.id = b.brand_id AND b.user_id = ?`
		sqlParams = append(sqlParams, userID)
	}
	sql += `
		 WHERE a.deleted_at = ? 
	`
	sqlParams = append(sqlParams, utils.DefaultTimeValue)
	if name != "" {
		sql += " AND a.name LIKE ?"
		sqlParams = append(sqlParams, "%"+name+"%")
	}
	if brandID != 0 {
		sql += " AND a.id = ?"
		sqlParams = append(sqlParams, brandID)
	}
	if poolKey != "" {
		sql += " AND a.secret_number_pool_key = ?"
		sqlParams = append(sqlParams, poolKey)
	}
	err = GetRows(db, &brands, sql, sqlParams)
	return brands, err
}

func GetStoreAcctIncome(db *DaoDB, storeID int, incomeTypes []int, vendorOrderID string, fromTime, toTime time.Time) (storeAcctIncomes []*model.StoreAcctIncome, err error) {
	sql := `
		SELECT * 
		  FROM store_acct_income 
		 WHERE 1 = 1
	`
	sqlParams := []interface{}{}
	if storeID != 0 {
		sql += " AND store_id = ?"
		sqlParams = append(sqlParams, storeID)
	}
	if len(incomeTypes) > 0 {
		sql += " AND type IN (" + GenQuestionMarks(len(incomeTypes)) + ")"
		sqlParams = append(sqlParams, incomeTypes)
	}
	if vendorOrderID != "" {
		sql += " AND vendor_order_id = ?"
		sqlParams = append(sqlParams, vendorOrderID)
	}
	if !utils.IsTimeZero(fromTime) {
		sql += " AND created_at >= ?"
		sqlParams = append(sqlParams, fromTime)
	}
	if !utils.IsTimeZero(toTime) {
		sql += " AND created_at <= ?"
		sqlParams = append(sqlParams, toTime)
	}
	err = GetRows(db, &storeAcctIncomes, sql, sqlParams)
	return storeAcctIncomes, err
}

func GetStoreAcctIncomeTotal(db *DaoDB, storeID int, incomeTypes []int, vendorOrderID string, fromTime, toTime time.Time) (incomeTotal int, err error) {
	var income *model.StoreAcctIncome
	sql := `
		SELECT SUM(income_price) income_price
		  FROM store_acct_income 
		 WHERE 1 = 1
	`
	sqlParams := []interface{}{}
	if storeID != 0 {
		sql += " AND store_id = ?"
		sqlParams = append(sqlParams, storeID)
	}
	if len(incomeTypes) > 0 {
		sql += " AND type IN (" + GenQuestionMarks(len(incomeTypes)) + ")"
		sqlParams = append(sqlParams, incomeTypes)
	}
	if vendorOrderID != "" {
		sql += " AND vendor_order_id = ?"
		sqlParams = append(sqlParams, vendorOrderID)
	}
	if !utils.IsTimeZero(fromTime) {
		sql += " AND created_at >= ?"
		sqlParams = append(sqlParams, fromTime)
	}
	if !utils.IsTimeZero(toTime) {
		sql += " AND created_at <= ?"
		sqlParams = append(sqlParams, toTime)
	}
	if err = GetRow(db, &income, sql, sqlParams); err == nil && income != nil {
		return income.IncomePrice, err
	}
	return 0, err
}

func GetStoreAcctExpend(db *DaoDB, storeID int, expendTypes []int, vendorOrderID string, fromTime, toTime time.Time) (storeAcctExpends []*model.StoreAcctExpend, err error) {
	sql := `
		SELECT * 
		  FROM store_acct_expend 
		 WHERE 1 = 1
	`
	sqlParams := []interface{}{}
	if storeID != 0 {
		sql += " AND store_id = ?"
		sqlParams = append(sqlParams, storeID)
	}
	if len(expendTypes) > 0 {
		sql += " AND type IN (" + GenQuestionMarks(len(expendTypes)) + ")"
		sqlParams = append(sqlParams, expendTypes)
	}
	if vendorOrderID != "" {
		sql += " AND vendor_order_id = ?"
		sqlParams = append(sqlParams, vendorOrderID)
	}
	if !utils.IsTimeZero(fromTime) {
		sql += " AND created_at >= ?"
		sqlParams = append(sqlParams, fromTime)
	}
	if !utils.IsTimeZero(toTime) {
		sql += " AND created_at <= ?"
		sqlParams = append(sqlParams, toTime)
	}
	err = GetRows(db, &storeAcctExpends, sql, sqlParams)
	return storeAcctExpends, err
}

func GetStoreAcctExpendTotal(db *DaoDB, storeID int, expendTypes []int, vendorOrderID string, fromTime, toTime time.Time) (expendTotal int, err error) {
	var expend *model.StoreAcctExpend
	sql := `
		SELECT SUM(expend_price) expend_price
		  FROM store_acct_expend 
		 WHERE 1 = 1
	`
	sqlParams := []interface{}{}
	if storeID != 0 {
		sql += " AND store_id = ?"
		sqlParams = append(sqlParams, storeID)
	}
	if len(expendTypes) > 0 {
		sql += " AND type IN (" + GenQuestionMarks(len(expendTypes)) + ")"
		sqlParams = append(sqlParams, expendTypes)
	}
	if vendorOrderID != "" {
		sql += " AND vendor_order_id = ?"
		sqlParams = append(sqlParams, vendorOrderID)
	}
	if !utils.IsTimeZero(fromTime) {
		sql += " AND created_at >= ?"
		sqlParams = append(sqlParams, fromTime)
	}
	if !utils.IsTimeZero(toTime) {
		sql += " AND created_at <= ?"
		sqlParams = append(sqlParams, toTime)
	}
	if err = GetRow(db, &expend, sql, sqlParams); err == nil && expend != nil {
		return expend.ExpendPrice, err
	}
	return 0, err
}

type GetStoreAcctExpendLastCreateWayBillFeeResult struct {
	ID               int `orm:"column(id)" json:"id"`
	ExpID            int `orm:"column(exp_id)" json:"expID"` // 支出记录id(金额补充)
	IncID            int `orm:"column(inc_id)" json:"incID"` // 退费记录id(金额退款)
	ExpendPrice      int `json:"expendPrice"`                // 运单支出金额
	MulitExpendPrice int `json:"mulitExpendPrice"`           // 运单补充金额
	MulitIncomePrice int `json:"mulitIncomePrice"`           // 运单退还金额
}

func GetStoreAcctExpendLastCreateWayBillFee(db *DaoDB, vendorOrderID string) (expend *GetStoreAcctExpendLastCreateWayBillFeeResult, lastFee int, err error) {
	sql := `
		SELECT a.id, b.id exp_id, c.id inc_id,
				a.expend_price, b.expend_price mulit_expend_price, c.income_price mulit_income_price
		  FROM store_acct_expend a
	 LEFT JOIN store_acct_expend b ON a.id = b.exp_id
	 LEFT JOIN store_acct_income c ON a.id = c.exp_id 
		 WHERE 1 = 1
		   AND a.type = ?
	`
	sqlParams := []interface{}{
		20, // partner.StoreAcctTypeExpendCreateWaybillEx 零食运费
	}
	if vendorOrderID != "" {
		sql += " AND a.vendor_order_id = ?"
		sqlParams = append(sqlParams, vendorOrderID)
	}
	sql += ` 
		ORDER BY a.created_at DESC
		LIMIT 1
	`
	if err = GetRow(db, &expend, sql, sqlParams); err == nil && expend != nil {
		lastFee = expend.ExpendPrice
		if expend.ExpID != 0 {
			lastFee += expend.MulitExpendPrice
		}
		if expend.IncID != 0 {
			lastFee -= expend.MulitIncomePrice
		}
	}
	return expend, lastFee, err
}

func GetStoreManageState(db *DaoDB, storeIDs, brandIDs []int, vendorID, sortType, offset, pageSize int) (pagedInfo *model.PagedInfo, err error) {
	var (
		requestList                    []*GetStoreManageStateResult
		GetStoreManageStateSortTypeMap = map[int]string{
			1: "a.cover_area",
			2: "c.market_scale",
			3: "a.open_time",
			4: "a.sku_count",
			5: "a.high_sku_count",
			6: "a.act_ample",
			7: "a.null_order_count",
			8: "a.refuse_order_count",
			9: "a.store_score",
		}
	)
	sql := `
		SELECT SQL_CALC_FOUND_ROWS DISTINCT a.*, b.name store_name, c.vendor_store_id, c.market_scale, b.comment
		FROM store_manage_state a 
		LEFT JOIN store b ON b.id = a.store_id AND b.deleted_at = ?
		LEFT JOIN store_map c ON c.store_id = a.store_id AND c.vendor_id = a.vendor_id AND c.deleted_at = ? 
		WHERE a.vendor_status <> ?
	`
	sqlParams := []interface{}{
		utils.DefaultTimeValue, utils.DefaultTimeValue,
		model.StoreStatusDisabled,
	}
	if len(storeIDs) > 0 {
		sql += " AND a.store_id IN (" + GenQuestionMarks(len(storeIDs)) + ")"
		sqlParams = append(sqlParams, storeIDs)
	}
	if len(brandIDs) > 0 {
		sql += " AND b.brand_id IN (" + GenQuestionMarks(len(brandIDs)) + ")"
		sqlParams = append(sqlParams, brandIDs)
	}
	if vendorID != -1 {
		sql += " AND a.vendor_id = ?"
		sqlParams = append(sqlParams, vendorID)
	}
	if sortType != 0 {
		tempSortType := 0
		if sortType < 0 {
			tempSortType = -sortType
		} else {
			tempSortType = sortType
		}
		if GetStoreManageStateSortTypeMap[tempSortType] != "" {
			sql += " ORDER BY " + GetStoreManageStateSortTypeMap[tempSortType]
			if sortType < 0 {
				sql += " DESC"
			}
		}
	}
	sql += " LIMIT ? OFFSET ?"
	pageSize = jxutils.FormalizePageSize(pageSize)
	sqlParams = append(sqlParams, pageSize, offset)
	txDB, _ := Begin(db)
	defer Commit(db, txDB)
	if err = GetRowsTx(txDB, &requestList, sql, sqlParams...); err == nil {
		return &model.PagedInfo{
			TotalCount: GetLastTotalRowCount2(db, txDB),
			Data:       requestList,
		}, nil
	}
	return pagedInfo, err
}

func GetStoreManageStateSimple(db *DaoDB, storeIDs, brandIDs []int, vendorID int) (pagedInfo []*model.StoreManageState, err error) {
	sql := `
		SELECT a.*
		FROM store_manage_state a 
		LEFT JOIN store b ON b.id = a.store_id AND b.deleted_at = ?
	`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
	}
	if len(storeIDs) > 0 {
		sql += " AND a.store_id IN (" + GenQuestionMarks(len(storeIDs)) + ")"
		sqlParams = append(sqlParams, storeIDs)
	}
	if len(brandIDs) > 0 {
		sql += " AND b.brand_id IN (" + GenQuestionMarks(len(brandIDs)) + ")"
		sqlParams = append(sqlParams, brandIDs)
	}
	if vendorID != -1 {
		sql += " AND a.vendor_id = ?"
		sqlParams = append(sqlParams, vendorID)
	}
	err = GetRows(db, &pagedInfo, sql, sqlParams...)
	return pagedInfo, err
}

func GetStoreMapAudit(db *DaoDB, storeIDs, vendorIDs, auditStatuss []int, fromTime, toTime time.Time, offset, pageSize int) (page *model.PagedInfo, err error) {
	var (
		storeMapAudits []*model.StoreMapAudit
	)
	sql := `
		SELECT SQL_CALC_FOUND_ROWS *
		  FROM store_map_audit
         WHERE 1 = 1
	`
	sqlParams := []interface{}{}
	if len(storeIDs) > 0 {
		sql += " AND store_id IN (" + GenQuestionMarks(len(storeIDs)) + ")"
		sqlParams = append(sqlParams, storeIDs)
	}
	if len(vendorIDs) > 0 {
		sql += " AND vendor_id IN (" + GenQuestionMarks(len(vendorIDs)) + ")"
		sqlParams = append(sqlParams, vendorIDs)
	}
	if len(auditStatuss) > 0 {
		sql += " AND audit_status IN (" + GenQuestionMarks(len(auditStatuss)) + ")"
		sqlParams = append(sqlParams, auditStatuss)
	}
	if fromTime != utils.ZeroTimeValue {
		sql += " AND a.created_at > ?"
		sqlParams = append(sqlParams, fromTime)
	}
	if toTime != utils.ZeroTimeValue {
		sql += " AND a.created_at < ?"
		sqlParams = append(sqlParams, toTime)
	}
	sql += " LIMIT ? OFFSET ?"
	pageSize = jxutils.FormalizePageSize(pageSize)
	offset = jxutils.FormalizePageOffset(offset)
	sqlParams = append(sqlParams, pageSize, offset)
	txDB, _ := Begin(db)
	defer Commit(db, txDB)
	if err = GetRowsTx(txDB, &storeMapAudits, sql, sqlParams...); err == nil {
		page = &model.PagedInfo{
			TotalCount: GetLastTotalRowCount2(db, txDB),
			Data:       storeMapAudits,
		}
	}
	return page, err
}

func GetBrandUser(db *DaoDB, brandID int, userID string) (brandUsers []*GetBrandUserResult, err error) {
	sql := `
		SELECT a.*, b.name 
		  FROM brand_user a
		LEFT JOIN user b ON a.user_id = b.user_id
		 WHERE a.deleted_at = ?
	`
	sqlParams := []interface{}{utils.DefaultTimeValue}
	if brandID != 0 {
		sql += " AND a.brand_id = ?"
		sqlParams = append(sqlParams, brandID)
	}
	if userID != "" {
		sql += " AND a.user_id = ?"
		sqlParams = append(sqlParams, userID)
	}
	err = GetRows(db, &brandUsers, sql, sqlParams)
	return brandUsers, err
}

func GetBrandBalance(db *DaoDB, brandID int) (result int, err error) {
	var (
		balance = &struct {
			Balance int
		}{}
	)
	sql := `
		SELECT a.balance - b.balance balance 
		  FROM (
				SELECT IFNULL(SUM(price),0) balance
		    	  FROM brand_bill
		    	 WHERE brand_id = ? 
			  	   AND bill_type = ?
				) a,
			   (
				SELECT IFNULL(SUM(price), 0) balance
		  		  FROM brand_bill
				 WHERE brand_id = ? 
			  	   AND bill_type = ?
				) b 
	`
	sqlParams := []interface{}{brandID, model.BrandBillTypeIncome, brandID, model.BrandBillTypeExpend}
	err = GetRow(db, &balance, sql, sqlParams)
	return balance.Balance, err
}

// GetBrandBillOrderExpend 获取订单品牌支出记录
func GetBrandBillOrderExpend(db *DaoDB, brandId int, vendorOrderID string) (int, error) {
	var Price = &struct {
		Price int
	}{}

	sql := `SELECT IFNULL(SUM(price),0) price FROM brand_bill
		    	 WHERE brand_id = ? AND bill_type = ? AND vendor_order_id = ? AND fee_type IN (?,?,?) `
	sqlParam := []interface{}{brandId, model.BrandBillTypeExpend, vendorOrderID, model.BrandBillFeeTypeDelivery, model.BrandBillFeeTypeTipFee, model.BrandBillFeeTypeDeductFee}

	err := GetRow(db, &Price, sql, sqlParam)
	return Price.Price, err
}

// GetBrandBillOrderIncome 获取品牌订单的退还记录
func GetBrandBillOrderIncome(db *DaoDB, brandId int, vendorOrderID string) (int, error) {
	var Price = &struct {
		Price int
	}{}

	sql := `SELECT IFNULL(SUM(price),0) price FROM brand_bill
		    	 WHERE brand_id = ? AND bill_type = ? AND vendor_order_id = ? AND fee_type IN (?,?,?) `
	sqlParam := []interface{}{brandId, model.BrandBillTypeIncome, vendorOrderID, model.BrandBillFeeTypeDelivery, model.BrandBillFeeTypeTipFee, model.BrandBillFeeTypeDeductFee}

	err := GetRow(db, &Price, sql, sqlParam)
	return Price.Price, err
}

func GetBrandBill(db *DaoDB, brandID int, vendorOrderID string, billType, feeType int, vendorWaybillOrderID string) (result []*model.BrandBill, err error) {
	sql := `
		SELECT * 
		  FROM brand_bill
		 WHERE 1 = 1
	`
	sqlParams := []interface{}{}
	if brandID != 0 {
		sql += " AND brand_id = ?"
		sqlParams = append(sqlParams, brandID)
	}
	if billType != 0 {
		sql += " AND bill_type = ?"
		sqlParams = append(sqlParams, billType)
	}
	if feeType != 0 {
		sql += " AND fee_type = ?"
		sqlParams = append(sqlParams, feeType)
	}
	if vendorOrderID != "" {
		sql += " AND vendor_order_id = ?"
		sqlParams = append(sqlParams, vendorOrderID)
	}
	if vendorWaybillOrderID != "" {
		sql += " AND order_id = ?"
		sqlParams = append(sqlParams, vendorWaybillOrderID)
	}
	err = GetRows(db, &result, sql, sqlParams)
	return result, err
}

func GetBrandCategoryMap(db *DaoDB, parentID, level, brandID, categoryID int) (brandCatMaps []*model.BrandCategoryMap, err error) {
	sql := `
		SELECT a.* 
		FROM brand_category_map a
		WHERE a.deleted_at = ?
	`
	sqlParams := []interface{}{
		utils.DefaultTimeValue,
	}
	if parentID >= 0 {
		sql += " AND a.parent_id = ?"
		sqlParams = append(sqlParams, parentID)
	}
	if level > 0 {
		sql += " AND a.level = ?"
		sqlParams = append(sqlParams, level)
	}
	if brandID > 0 {
		sql += " AND a.brand_id = ?"
		sqlParams = append(sqlParams, brandID)
	}
	if categoryID > 0 {
		sql += " AND a.category_id = ?"
		sqlParams = append(sqlParams, categoryID)
	}
	sql += " ORDER BY a.level, a.brand_category_seq"
	err = GetRows(db, &brandCatMaps, sql, sqlParams)
	if err != nil {
		return nil, err
	}
	return brandCatMaps, err
}

func GetBrandSecretNumbers(db *DaoDB, brandID int) (results []*model.SecretNumber, err error) {
	sql := `
		SELECT a.*
		  FROM secret_number a
	 LEFT JOIN brand b ON a.pool_key = b.secret_number_pool_key
		 WHERE b.deleted_at = ? AND b.id = ?
	`
	sqlParams := []interface{}{utils.DefaultTimeValue, brandID}
	err = GetRows(db, &results, sql, sqlParams)
	return results, err
}

func DeleteBrandCategroies2(db *DaoDB, brandID int) (err error) {
	sql := `
		DELETE FROM brand_category_map WHERE brand_id = ?
	`
	sqlParams := []interface{}{
		brandID,
	}
	_, err = ExecuteSQL(db, sql, sqlParams)
	return err
}

func InsertBrandCategories(db *DaoDB, userName string, brandID int) (err error) {
	sql := `
		INSERT INTO brand_category_map 
		(created_at, updated_at, last_operator, deleted_at, brand_id, category_id, brand_category_name, brand_category_seq, level, parent_id)
		SELECT ?, ?, ?, ?, ?, id, name, seq, level, parent_id
		FROM sku_category 
		WHERE deleted_at = ? 
		AND is_exd_spec = ?
	`
	sqlParams := []interface{}{
		time.Now(), time.Now(), userName, utils.DefaultTimeValue, brandID,
		utils.DefaultTimeValue, model.NO,
	}
	_, err = ExecuteSQL(db, sql, sqlParams)
	return err
}

//
//// 根据国美门店id获取门店名称
//func GetStoreByVendorId(db *DaoDB, vendorOrderID string, vendorCode int) (storeMaps []*model.StoreCourierMap, err error) {
//	if vendorOrderID == "" || vendorCode == 0 {
//		return nil, err
//	}
//	sql := `
//	SELECT t1.*
//	FROM store_courier_map t1
//	LEFT JOIN store t2 ON t1.store_id = t2.id AND t1.deleted_at = ?
//	WHERE t1.deleted_at = ?  AND t2.
//	`
//	sqlParams := []interface{}{
//		utils.DefaultTimeValue,
//	}
//	if len(vendorOrderID) > 0 {
//		sql += " AND t1.vendor_store_id  = ? "
//		sqlParams = append(sqlParams, vendorOrderID)
//	}
//
//	sql += " AND t1.audit_status IN (" + GenQuestionMarks(len(auditStatuss)) + ")"
//	sqlParams = append(sqlParams, auditStatuss)
//	if err = GetRows(db, &courierStoreList, sql, sqlParams...); err == nil {
//		return courierStoreList, nil
//	}
//}

func GetBrandBill2(db *DaoDB, brandID int, vendorOrderID string, billType, feeType int, vendorWaybillOrderID string, createAt string) (result []*RefundOrder, err error) {
	vendor := []int{101, 102, 103}
	brandID2 := []int{131, 132, 137, 139}
	sql := `
		select a.vendor_order_id order_id from  brand_bill a  
		inner JOIN order_status os on a.vendor_order_id = os.ref_vendor_order_id and os.status = ?  and os.vendor_id  IN (` + GenQuestionMarks(len(vendor)) + `)` + `
		WHERE a.brand_id in (` + GenQuestionMarks(len(brandID2)) + `)` + ` and  a.bill_type <> ? and os.remark <> ? and os.status <> ?  GROUP BY a.vendor_order_id
`
	var data []*RefundOrder
	param := []interface{}{115, vendor, brandID2, 1, "没有及时抢单", -100}
	if err := GetRows(GetDB(), &data, sql, param...); err != nil {
		return nil, err
	}
	return data, err
}

//获取门店品牌信息
func GetStoreBrandInfos(storeID int) (date *BrandInfos, err error) {
	var detail *BrandInfos
	sqlParams := []interface{}{}
	sql := "SELECT b.`name`,b.logo FROM store s LEFT JOIN brand b ON s.brand_id = b.id WHERE s.id= ? "
	if storeID >= 0 {
		sqlParams = append(sqlParams, storeID)
	}
	if err := GetRow(GetDB(), &detail, sql, sqlParams); err != nil {
		return nil, err
	}
	return detail, err
}

// 查询FreightTemplate
func QueryStoreBindInfo(storeID int) (*model.FreightTemplate, error) {
	if storeID == model.NO {
		return nil, errors.New("storeId 不能为0")
	}
	if _, ok := FreightTemplateMap[storeID]; ok {
		return FreightTemplateMap[storeID], nil
	}

	var (
		sqlParams []interface{}
		bindInfo  *model.FreightTemplate
	)
	sql := "SELECT a.* FROM freight_template a "
	sql += "WHERE a.store_id = ? "
	sqlParams = append(sqlParams, storeID)
	if err := GetRow(GetDB(), &bindInfo, sql, sqlParams...); err != nil {
		return nil, err
	}
	FreightTemplateMap[storeID] = bindInfo
	return bindInfo, nil
}

//向FreightTemplate 插入数据
func InsertIntoFreightTemplate(storeID int, vendorStoreID string, templateID, warehouseID, fenceID, tradeLimitID int64) error {
	var (
		sqlStr    []string
		tStr      = ""
		sqlParams []interface{}
	)
	if storeID == 0 && utils.Str2Int(vendorStoreID) == 0 {
		return errors.New("storeID,vendorStoreID 必传")
	}

	sql := `UPDATE freight_template a SET  `

	if templateID != 0 {
		templateIDSql := ` a.template_id = ? `
		sqlParams = append(sqlParams, templateID)
		sqlStr = append(sqlStr, templateIDSql)
	}
	if warehouseID != 0 {
		warehouseIDSql := ` a.warehouse_id = ?  `
		sqlParams = append(sqlParams, warehouseID)
		sqlStr = append(sqlStr, warehouseIDSql)
	}
	if fenceID != 0 {
		fenceIDSql := ` a.fence_id = ?`
		sqlParams = append(sqlParams, fenceID)
		sqlStr = append(sqlStr, fenceIDSql)
	}
	if tradeLimitID != 0 {
		tradeLimitIDSql := ` a.fence_id = ?  `
		sqlParams = append(sqlParams, tradeLimitID)
		sqlStr = append(sqlStr, tradeLimitIDSql)
	}
	tStr = "WHERE a.store_id = ? AND a.vendor_store_id = ?"

	tStr2 := sql + strings.Join(sqlStr, ",") + tStr

	_, err := ExecuteSQL(GetDB(), tStr2, sqlParams...)
	fmt.Println(tStr2)
	return err
}

// GetCodeAndIDByMeiTuan 只获取美团平台的京西storeID
func GetCodeAndIDByMeiTuan(vendorStoreID string, vendorId int) (storeID int, err error) {
	err = GetRow(GetDB(), &storeID, "SELECT s.store_id FROM store_map s WHERE s.vendor_store_id = ? AND s.vendor_id = ? AND s.deleted_at = ?", vendorStoreID, vendorId, utils.DefaultTimeValue)
	return storeID, err
}

// BindJXPrintToStore 更新绑定门店的京西打印机 PrinterFontSize printer_sn printer_key  printer_vendor_id printer_font_size
func BindJXPrintToStore(storeId int64, printSn, printKey string) error {
	sql := ` UPDATE store SET printer_sn = ? , printer_key = ? , printer_vendor_id = ? , printer_font_size = ? WHERE id = ?`
	_, err := ExecuteSQL(GetDB(), sql, []interface{}{printSn, printKey, model.VendorIDJxprint, model.NO, storeId})
	return err
}

// GetStoreBaseByVendorStoreID 根据vendorStoreID获取门店基本信息
func GetStoreBaseByVendorStoreID(vendorStoreID string, vendorID int) (storeDetail *model.Store, err error) {
	if len(vendorStoreID) == 0 {
		return nil, errors.New("vendorStoreID不能为空")
	}

	sql := `SELECT t.* FROM store t WHERE t.id = (SELECT s.store_id FROM store_map s WHERE s.vendor_store_id= ? AND s.vendor_id= ? AND s.deleted_at= '1970-01-01 00:00:00' )`
	if err := GetRow(GetDB(), &storeDetail, sql, []interface{}{vendorStoreID, vendorID}); err != nil {
		return nil, err
	}
	return storeDetail, err
}

// StatisticsStoreInfo 统计所有的门店信息
func StatisticsStoreInfo(db *DaoDB, brandId, vendorId, storeList []int, operateNum, brandOperate string) ([]*StatisticsStore, error) {
	statistics := make([]*StatisticsStore, 0, 0)

	sql := ` SELECT count(s.status) count, s.status FROM store s  `
	param := make([]interface{}, 0, 0)
	if len(vendorId) > model.NO {
		sql += ` INNER JOIN store_map m ON s.id = m.store_id AND m.vendor_id IN (` + GenQuestionMarks(len(vendorId)) + `)`
		param = append(param, vendorId)
	}
	sql += ` WHERE 1=1 `

	if len(storeList) > model.NO {
		sql += ` AND s.id IN  (` + GenQuestionMarks(len(storeList)) + `)`
		param = append(param, storeList)
	}

	if len(brandId) > model.NO {
		sql += ` AND s.brand_id IN (` + GenQuestionMarks(len(brandId)) + `)`
		param = append(param, brandId)
	}

	if operateNum != "" {
		sql += ` AND s.market_man_phone = ?`
		param = append(param, operateNum)
	}
	if brandOperate != "" {
		sql += ` AND s.operator_phone2 = ?`
		param = append(param, brandOperate)
	}

	sql += ` GROUP BY s.status `
	if err := GetRows(db, &statistics, sql, param); err != nil {
		return nil, err
	}
	return statistics, nil
}

// StatisticsOrderInfo 统计订单信息
func StatisticsOrderInfo(db *DaoDB, startTime, endTime time.Time, storeId int, brandId, vendorId, storeList []int, operateNum, brandOperate string) ([]*StatisticsOrder, error) {
	parma := []interface{}{}
	sql := ` SELECT count(g.vendor_order_id) count,g.status status ,sum(g.total_shop_money) total_shop_money FROM goods_order g 
				INNER JOIN store s ON  IF(g.store_id <> 0,g.store_id,g.jx_store_id) = s.id 
`

	sql += `  WHERE g.order_created_at >= ? AND  g.order_created_at <= ?`
	parma = append(parma, startTime, endTime)
	if storeId != model.NO {
		sql += ` AND IF(g.store_id <> 0,g.store_id,g.jx_store_id)  = ?`
		parma = append(parma, storeId)
	} else if len(storeList) != model.NO {
		sql += ` AND IF(g.store_id <> 0,g.store_id,g.jx_store_id) IN (` + GenQuestionMarks(len(storeList)) + `)`
		parma = append(parma, storeList)
	}

	if len(vendorId) > model.NO {
		sql += ` AND g.vendor_id IN (` + GenQuestionMarks(len(vendorId)) + `)`
		parma = append(parma, vendorId)
	}

	sql += ` GROUP BY g.status `
	orderStatistics := make([]*StatisticsOrder, 0, 0)
	if err := GetRows(db, &orderStatistics, sql, parma...); err != nil {
		return nil, err
	}
	return orderStatistics, nil
}

// StatisticsAfsOrderInfo 售后单信息统计
func StatisticsAfsOrderInfo(db *DaoDB, startTime, endTime time.Time, storeId int, brandId, vendorId, storeList []int, operateNum, brandOperate string) ([]*StatisticsOrder, error) {
	parma := []interface{}{}
	sql := `SELECT count(a.vendor_order_id) count,a.status status ,sum(a.afs_total_shop_money) total_shop_money FROM afs_order a  
			INNER JOIN store s ON  IF(a.store_id <> 0,a.store_id,a.jx_store_id) = s.id 
`
	sql += ` WHERE a.afs_created_at >= ? AND a.afs_created_at <= ?`
	parma = append(parma, startTime, endTime)

	if storeId != model.NO {
		sql += ` AND IF(a.store_id <> 0,a.store_id,a.jx_store_id) = ?`
		parma = append(parma, storeId)
	} else if len(storeList) != model.NO {
		sql += ` AND IF(a.store_id <> 0,a.store_id,a.jx_store_id) IN (` + GenQuestionMarks(len(storeList)) + `)`
		parma = append(parma, storeList)
	}

	if len(vendorId) > 0 {
		sql += ` AND a.vendor_id IN (` + GenQuestionMarks(len(vendorId)) + `)`
		parma = append(parma, vendorId)
	}

	if operateNum != "" {
		sql += ` AND s.market_man_phone = ?`
		parma = append(parma, operateNum)
	}
	if brandOperate != "" {
		sql += ` AND s.operator_phone2 = ?`
		parma = append(parma, brandOperate)
	}
	if len(brandId) != 0 {
		sql += `AND s.brand_id IN (` + GenQuestionMarks(len(brandId)) + `)`
		parma = append(parma, brandId)
	}

	sql += ` GROUP BY a.status`
	orderStatistics := make([]*StatisticsOrder, 0, 0)
	if err := GetRows(db, &orderStatistics, sql, parma...); err != nil {
		return nil, err
	}
	return orderStatistics, nil
}

// StatisticsIncome 统计平台和市场收入
func StatisticsIncome(db *DaoDB, startTime, endTime time.Time, storeId int, brandId, vendorId, storeList []int, operateNum, brandOperate string) ([]*StatisticsIncomeInfo, error) {
	parma := []interface{}{}

	sql := `
		SELECT t1.jx_store_id id,t3.name,
			SUM(ROUND(IF(t1.earning_type = 1, t1.total_shop_money-t1.earning_price-IFNULL(t2.desired_fee,0), t1.total_shop_money *(t1.order_pay_percentage/2)/100),3)) total_income,
			SUM(ROUND(IF(t1.earning_type = 1, t1.total_shop_money-t1.earning_price-IFNULL(t2.desired_fee,0), t1.total_shop_money *(t1.order_pay_percentage/2)/100) * (t3.jx_brand_fee_factor/10),3)) jx_income,
			SUM(ROUND(IF(t1.earning_type = 1, t1.total_shop_money-t1.earning_price-IFNULL(t2.desired_fee,0), t1.total_shop_money *(t1.order_pay_percentage/2)/100) * (t3.market_add_fee_factor/10),3)) market_income,
			count(t1.vendor_order_id) order_count,
			sum(t1.vendor_price) order_sku_price,
			sum(t1.package_price) server_fee
		FROM goods_order t1 
		LEFT JOIN waybill t2 ON t1.vendor_waybill_id = t2.vendor_waybill_id AND t1.waybill_vendor_id = t2.waybill_vendor_id AND t1.vendor_order_id = t2.vendor_order_id
		LEFT JOIN store t3 ON t1.jx_store_id = t3.id
		WHERE  t1.order_created_at >= ?  AND  t1.order_created_at  <= ? AND t1.status = 110 `
	parma = append(parma, startTime, endTime)
	if storeId != model.NO {
		sql += ` AND t1.jx_store_id = ?`
		parma = append(parma, storeId)
	} else if len(storeList) != model.NO {
		sql += ` AND t1.jx_store_id IN (` + GenQuestionMarks(len(storeList)) + `)`
		parma = append(parma, storeList)
	}

	if operateNum != "" {
		sql += ` AND t3.market_man_phone = ?`
		parma = append(parma, operateNum)
	}
	if brandOperate != "" {
		sql += ` AND t3.operator_phone2 = ?`
		parma = append(parma, brandOperate)
	}
	if len(brandId) != model.NO {
		sql += ` AND t3.brand_id IN (` + GenQuestionMarks(len(brandId)) + `)`
		parma = append(parma, brandId)
	}

	if len(vendorId) != model.NO {
		sql += ` AND t1.vendor_id IN (` + GenQuestionMarks(len(vendorId)) + `)`
		parma = append(parma, vendorId)
	}

	sql += ` GROUP BY t1.jx_store_id ORDER BY order_count DESC`

	//sql2 := ` SELECT settle.id,COUNT(settle.vendor_order_id) order_count,settle.name name,
	//                 SUM(settle.total_income) total_income,SUM(settle.jx_income) jx_income,
	//			     SUM(settle.market_income) market_income, SUM(settle.order_sku_price) order_sku_price
	//	      FROM ( ` + sql + `) AS settle  GROUP BY id ORDER BY order_count DESC`

	incomeInfo := make([]*StatisticsIncomeInfo, 0, 0)
	if err := GetRows(db, &incomeInfo, sql, parma...); err != nil {
		return nil, err
	}

	return incomeInfo, nil
}

// StatisticsFineFee 统计门店罚款支出
func StatisticsFineFee(db *DaoDB, startTime, endTime time.Time, storeId []int) ([]*model.StoreFine, error) {
	parma := []interface{}{storeId, startTime, endTime}
	sql := ` SELECT * FROM store_fine WHERE store_id IN (` + GenQuestionMarks(len(storeId)) + `)` + ` AND finish_time >= ? AND finish_time <= ?`

	fine := make([]*model.StoreFine, 0, 0)
	if err := GetRows(db, &fine, sql, parma...); err != nil {
		return nil, err
	}
	if len(fine) == model.NO {
		return nil, nil
	}

	return fine, nil
}

// StatisticsSettlement 统计京西门店结算信息
func StatisticsSettlement(db *DaoDB, storeId []int, start, end time.Time, vendorId []int, size, offset int, rank string) (pagedInfo *model.PagedInfo, err error) {
	var (
		fields []string
	)
	sql := `
				SELECT 
						SQL_CALC_FOUND_ROWS
						gs.jx_store_id,
						s.name,
						b.id AS brand_id,
						b.name AS brand_name,
						sm1.vendor_store_id AS mt_store_id,
						sm2.vendor_store_id AS jd_store_id,
						sm3.vendor_store_id AS sg_store_id,
						city.name AS city_name,
						district.name AS district_name,
						s.market_man_phone,
						u_market.name AS market_man_name,  -- 修正别名
						u_operator1.name AS operator1_name,
						u_operator2.name AS operator2_name,
						u_operator3.name AS operator3_name,
						s.jx_brand_fee_factor,
						s.market_add_fee_factor,
						s.pay_percentage,
						COALESCE(COUNT(gs.vendor_order_id), 0) AS order_count,  -- 处理 NULL
						COALESCE(SUM(w.desired_fee), 0) AS total_desired_fee,
						s.package_setting,
						SUM(ROUND(IF(gs.earning_type = 1, (gs.total_shop_money-gs.earning_price), gs.total_shop_money *(gs.order_pay_percentage/2)/100) * (s.jx_brand_fee_factor/10),3)-IFNULL(w.desired_fee,0)) jx_income,
						SUM(ROUND(IF(gs.earning_type = 1, (gs.total_shop_money-gs.earning_price-IFNULL(w.desired_fee,0)) , gs.total_shop_money *(gs.order_pay_percentage/2)/100) * (s.market_add_fee_factor/10),3)-IFNULL(w.desired_fee,0)) market_income,
						SUM(ROUND(IF(gs.earning_type = 1, gs.earning_price, gs.total_shop_money- (gs.total_shop_money *(gs.order_pay_percentage/2)/100)) -IFNULL(w.desired_fee,0),3)-s.package_setting) store_income,
						SUM(ROUND(IF(gs.earning_type = 1, gs.total_shop_money-gs.earning_price, gs.total_shop_money- (gs.total_shop_money *(1-(gs.order_pay_percentage/2)/100))) ,3)-IFNULL(w.desired_fee,0)) platform_income,
						COALESCE(SUM(gs.total_shop_money), 0) AS total_shop_money,-- 平台结算
						COALESCE(SUM(ao.refund_money), 0) AS refund_money -- 售后退款
				FROM  goods_order gs 
				LEFT JOIN store_map sm1 ON gs.jx_store_id = sm1.store_id AND sm1.vendor_id = 1 AND sm1.deleted_at =  '1970-01-01 00:00:00'   
				LEFT JOIN store_map sm2 ON gs.jx_store_id = sm2.store_id AND sm2.vendor_id = 0 AND sm2.deleted_at =  '1970-01-01 00:00:00'
				LEFT JOIN store_map sm3 ON gs.jx_store_id = sm3.store_id AND sm3.vendor_id = 3 AND sm3.deleted_at =  '1970-01-01 00:00:00'
				LEFT JOIN  store s ON  s.id = gs.jx_store_id
				LEFT JOIN brand b ON b.id = s.brand_id 
				LEFT JOIN place city ON city.code = s.city_code
				LEFT JOIN place district ON district.code = s.district_code  -- 别名避免歧义
				LEFT JOIN user u_market ON u_market.mobile = s.market_man_phone
				LEFT JOIN user u_operator1 ON u_operator1.mobile = s.operator_phone
				LEFT JOIN user u_operator2 ON u_operator2.mobile = s.operator_phone2
				LEFT JOIN user u_operator3 ON u_operator3.mobile = s.operator_phone3
				LEFT JOIN waybill w ON w.vendor_order_id = gs.vendor_order_id AND w.status IN (100,105)
				LEFT JOIN afs_order ao ON ao.vendor_order_id = gs.vendor_order_id  AND ao.status IN (160,180) 
						WHERE 1=1   
			`
	param := []interface{}{}
	if !utils.IsTimeZero(start) && !utils.IsTimeZero(end) {
		sql += ` AND gs.order_finished_at BETWEEN ? AND ?  AND gs.status = 110  `
		param = append(param, start, end)
	}
	if len(storeId) != 0 {
		sql += ` AND IF(gs.jx_store_id != 0, gs.jx_store_id, gs.store_id) IN (` + dao.GenQuestionMarks(len(storeId)) + `)`
		param = append(param, storeId)
	}
	if len(vendorId) != 0 {
		sql += ` AND gs.vendor_id IN (` + GenQuestionMarks(len(vendorId)) + `)`
		param = append(param, vendorId)
	}
	sql += ` AND s.deleted_at = ? `
	param = append(param, utils.DefaultTimeValue)

	sql += `
	GROUP BY
		s.id, s.name, sm1.vendor_store_id, sm2.vendor_store_id, sm3.vendor_store_id,
		city.name, district.name, s.market_man_phone, u_market.name,
		u_operator1.name, u_operator2.name, u_operator3.name,
		s.jx_brand_fee_factor, s.market_add_fee_factor, s.pay_percentage, s.package_setting `
	if rank != "" {
		fields = strings.Split(rank, ",")
		sql += fmt.Sprintf(` ORDER BY %s %s `, fields[0], fields[1])
	} else {
		sql += fmt.Sprintf(`ORDER BY  order_count desc`)
	}

	sql += ` LIMIT ? OFFSET ?`
	param = append(param, size, offset)

	txDB, _ := Begin(db)
	defer Commit(db, txDB)
	var msgList []*model.JxSettlementInfo
	if err = GetRowsTx(txDB, &msgList, sql, param...); err != nil {
		return nil, err
	}

	if len(msgList) > 0 {
		for _, v := range msgList {
			// 服务费
			v.PackageSetting = v.PackageSetting * v.OrderCount
			if v.BrandId == 1 || v.BrandId == 38 { // 京西/好菜
				// 袋子费
				v.PackagingFee = 40 * v.OrderCount
				v.JxIncome -= float64(v.PackagingFee)
				v.MarketIncome -= float64(v.PackagingFee)
				v.StoreIncome -= float64(v.PackagingFee)
			} else {
				if v.PayPercentage != 0 && v.JxIncome == 0 {
					v.JxIncome = float64(v.TotalShopMoney) - v.StoreIncome
				}
			}

			v.Profit = v.JxIncome + v.MarketIncome + float64(v.PackageSetting)
		}
	}

	sortWay := SortOption{}
	if len(fields) != 0 {
		sortWay.Field = fields[0]
		switch fields[1] {
		case "ASC", "asc":
			sortWay.Ascending = true
		case "DESC", "desc":
			sortWay.Ascending = false
		default:
			sortWay.Ascending = false
		}
	}
	SortSettlement(msgList, nil, sortWay)

	pagedInfo = &model.PagedInfo{
		TotalCount: GetLastTotalRowCount2(db, txDB),
		Data:       msgList,
	}
	return pagedInfo, nil
}

// StatisticsSettlementByCity 根据城市统计结算
func StatisticsSettlementByCity(db *DaoDB, cityCode []string, start, end time.Time, vendorId []int, size, offset int, rank string) (pagedInfo *model.PagedInfo, err error) {
	var (
		fields []string
	)
	sql := `
				SELECT 
						SQL_CALC_FOUND_ROWS
						p.name AS city_name,
						u.name AS user_name,
						u.mobile,
						s.brand_id,
						s.package_setting,
						COUNT(gs.vendor_order_id) AS order_count,
						COALESCE(SUM(w.desired_fee), 0) AS total_desired_fee,
						SUM(ROUND(IF(gs.earning_type = 1, (gs.total_shop_money-gs.earning_price), gs.total_shop_money *(gs.order_pay_percentage/2)/100) * (s.jx_brand_fee_factor/10),3)-IFNULL(w.desired_fee,0)) jx_income,
						SUM(ROUND(IF(gs.earning_type = 1, (gs.total_shop_money-gs.earning_price-IFNULL(w.desired_fee,0)) , gs.total_shop_money *(gs.order_pay_percentage/2)/100) * (s.market_add_fee_factor/10),3)-IFNULL(w.desired_fee,0)) market_income,
						SUM(ROUND(IF(gs.earning_type = 1, gs.earning_price, gs.total_shop_money- (gs.total_shop_money *(gs.order_pay_percentage/2)/100)) -IFNULL(w.desired_fee,0),3)-s.package_setting) store_income,
						SUM(ROUND(IF(gs.earning_type = 1, gs.total_shop_money-gs.earning_price, gs.total_shop_money- (gs.total_shop_money *(1-(gs.order_pay_percentage/2)/100))) ,3)-IFNULL(w.desired_fee,0)) platform_income,						
						COALESCE(SUM(ao.refund_money), 0) AS refund_money, -- 售后退款
						COALESCE(SUM(gs.total_shop_money), 0) AS total_shop_money -- 平台结算
				FROM goods_order gs
				LEFT JOIN waybill w ON w.vendor_order_id = gs.vendor_order_id  AND w.status IN (100,105)
				LEFT JOIN store s ON s.id = IF(gs.jx_store_id != 0, gs.jx_store_id, gs.store_id)
				LEFT JOIN user u ON u.mobile = s.market_man_phone
				LEFT JOIN place p ON p.code = s.city_code
				LEFT JOIN afs_order ao ON ao.vendor_order_id = gs.vendor_order_id AND ao.status IN (160, 180)
				WHERE 1=1
			`
	param := []interface{}{}
	if !utils.IsTimeZero(start) && !utils.IsTimeZero(end) {
		sql += ` AND gs.order_finished_at BETWEEN ? AND ?  AND gs.status = 110  `
		param = append(param, start, end)
	}
	if len(vendorId) != 0 {
		sql += ` AND gs.vendor_id IN (` + GenQuestionMarks(len(vendorId)) + `)`
		param = append(param, vendorId)
	}
	if len(cityCode) != 0 {
		sql += ` AND s.city_code IN (` + dao.GenQuestionMarks(len(cityCode)) + `)`
		param = append(param, cityCode)
	}

	sql += ` AND s.deleted_at = ? `
	param = append(param, utils.DefaultTimeValue)

	sql += ` GROUP BY p.name,u.name, u.mobile,s.id `

	if rank != "" {
		fields = strings.Split(rank, ",")
		sql += fmt.Sprintf(` ORDER BY %s %s `, fields[0], fields[1])
	} else {
		sql += fmt.Sprintf(`ORDER BY  order_count desc`)
	}

	sql += ` LIMIT ? OFFSET ?`
	param = append(param, size, offset)

	txDB, _ := Begin(db)
	defer Commit(db, txDB)
	var msgList []*model.SettlementByCityCode
	if err = GetRowsTx(txDB, &msgList, sql, param...); err != nil {
		return nil, err
	}

	if len(msgList) > 0 {
		for _, v := range msgList {
			// 服务费
			v.PackageSetting = v.PackageSetting * v.OrderCount
			if v.BrandId == 1 || v.BrandId == 38 { // 京西/好菜
				// 袋子费
				v.PackagingFee = 40 * v.OrderCount
				v.JxIncome -= float64(v.PackagingFee)
				v.MarketIncome -= float64(v.PackagingFee)
				v.StoreInCome -= float64(v.PackagingFee)
			}

			v.Profit = v.JxIncome + v.MarketIncome + float64(v.PackageSetting)
		}
	}

	sortWay := SortOption{}
	if len(fields) != 0 {
		sortWay.Field = fields[0]
		switch fields[1] {
		case "ASC", "asc":
			sortWay.Ascending = true
		case "DESC", "desc":
			sortWay.Ascending = false
		default:
			sortWay.Ascending = false
		}
	}
	SortSettlement(nil, msgList, sortWay)
	pagedInfo = &model.PagedInfo{
		TotalCount: GetLastTotalRowCount2(db, txDB),
		Data:       msgList,
	}
	return pagedInfo, nil
}

// SortOption 排序选项
type SortOption struct {
	Field     string
	Ascending bool // true 升序
	//ThenBy    *SortOption // 用于多级排序
}

func SortSettlement(store []*model.JxSettlementInfo, code []*model.SettlementByCityCode, option SortOption) {
	if store != nil {
		sort.Slice(store, func(i, j int) bool {
			return compareByStore(store[i], store[j], option)
		})
	} else if code != nil {
		sort.Slice(code, func(i, j int) bool {
			return compareByCode(code[i], code[j], option)
		})
	}

}

func compareByStore(a, b *model.JxSettlementInfo, option SortOption) bool {
	var result bool

	switch option.Field {
	case "order_count":
		result = a.OrderCount < b.OrderCount
	case "package_setting":
		result = a.PackageSetting < b.PackageSetting
	case "total_desired_fee":
		result = a.TotalDesiredFee < b.TotalDesiredFee
	case "refund_money":
		result = a.RefundMoney < b.RefundMoney
	case "total_shop_money":
		result = a.TotalShopMoney < b.TotalShopMoney
	case "platform_income":
		result = a.PlatformIncome < b.PlatformIncome
	case "store_income":
		result = a.StoreIncome < b.StoreIncome
	case "jx_income":
		result = a.JxIncome < b.JxIncome
	case "market_income":
		result = a.MarketIncome < b.MarketIncome
	default:
		result = a.OrderCount < b.OrderCount
	}

	// 处理降序
	if !option.Ascending {
		result = !result
	}

	// 如果相等且有下一级排序，则继续比较
	//if result == false && a.FirstName == b.FirstName && option.ThenBy != nil {
	//	return comparePeople(a, b, *option.ThenBy)
	//}

	return result
}

func compareByCode(a, b *model.SettlementByCityCode, option SortOption) bool {
	var result bool

	switch option.Field {
	case "order_count":
		result = a.OrderCount < b.OrderCount
	case "package_setting":
		result = a.PackageSetting < b.PackageSetting
	case "total_desired_fee":
		result = a.TotalDesiredFee < b.TotalDesiredFee
	case "refund_money":
		result = a.RefundMoney < b.RefundMoney
	case "total_shop_money":
		result = a.TotalShopMoney < b.TotalShopMoney
	case "platform_income":
		result = a.PlatformIncome < b.PlatformIncome
	case "store_income":
		result = a.StoreInCome < b.StoreInCome
	case "jx_income":
		result = a.JxIncome < b.JxIncome
	case "market_income":
		result = a.MarketIncome < b.MarketIncome
	default:
		result = a.OrderCount < b.OrderCount
	}

	// 处理降序
	if !option.Ascending {
		result = !result
	}

	// 如果相等且有下一级排序，则继续比较
	//if result == false && a.FirstName == b.FirstName && option.ThenBy != nil {
	//	return comparePeople(a, b, *option.ThenBy)
	//}

	return result
}
