package localjx

import (
	"git.rosy.net.cn/jx-callback/business/model/dao"

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

	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
)

type GetJxShopUsersResult struct {
	model.User
	BuyCount         int                 `json:"buyCount"`
	ActualPayPrice   int                 `json:"actualPayPrice"`
	VendorID         int                 `orm:"column(vendor_id)" json:"vendorID"`
	GoodCommentCount int                 `json:"goodCommentCount"`
	BadCommentCount  int                 `json:"badCommentCount"`
	UserMembers      []*model.UserMember `json:"userMembers"`
}

func GetJxShopUsers(ctx *jxcontext.Context, keyword, fromTime, toTime string, vendorIDs []int, offset, pageSize int) (pagedInfo *model.PagedInfo, err error) {
	var (
		requestList []*GetJxShopUsersResult
		db          = dao.GetDB()
		fromTimeP   = utils.Str2Time(fromTime)
		toTimeP     = utils.Str2Time(toTime)
		sqlParams   = []interface{}{}
	)
	sql := ` 
		  SELECT SQL_CALC_FOUND_ROWS a.*, b.name, b.created_at, b.last_login_at 
			FROM (
				SELECT c.vendor_user_id, IF(c.consignee_mobile2 <> '',c.consignee_mobile2,c.consignee_mobile) mobile, 
				c.vendor_id,COUNT(*) buy_count, SUM(c.actual_pay_price) actual_pay_price, COUNT(d.score > 3) good_comment_count, 
				COUNT(d.score < 3) bad_comment_count
				  FROM goods_order c  
			 LEFT JOIN jx_bad_comments d ON d.order_id = c.vendor_order_id
			     WHERE 1 = 1
		`
	if fromTimeP != utils.ZeroTimeValue && toTimeP != utils.ZeroTimeValue {
		sql += ` AND c.order_created_at >= ? AND c.order_created_at <= ?`
		sqlParams = append(sqlParams, fromTimeP, toTimeP)
	}
	if len(vendorIDs) > 0 {
		sql += ` AND c.vendor_id IN(` + dao.GenQuestionMarks(len(vendorIDs)) + `) `
		sqlParams = append(sqlParams, vendorIDs)
	}
	sql += `       AND c.status <> ? 
			  GROUP BY 1,2,3)a
	   LEFT JOIN user b ON b.user_id = a.vendor_user_id
	       WHERE (b.deleted_at = ? OR b.deleted_at is null)
	`
	sqlParams = append(sqlParams, model.OrderStatusCanceled, utils.DefaultTimeValue)
	if keyword != "" {
		sql += " AND (a.user_id LIKE ? OR b.name LIKE ? OR a.mobile LIKE ?)"
		sqlParams = append(sqlParams, "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
	}
	sql += "LIMIT ? OFFSET ?"
	pageSize = jxutils.FormalizePageSize(pageSize)
	sqlParams = append(sqlParams, pageSize, offset)
	txDB, _ := dao.Begin(db)
	defer dao.Commit(db, txDB)
	if err = dao.GetRowsTx(txDB, &requestList, sql, sqlParams...); err == nil {
		pagedInfo = &model.PagedInfo{
			TotalCount: dao.GetLastTotalRowCount2(db, txDB),
			// Data:       requestList,
		}
		for _, v := range requestList {
			userMembers, _ := dao.GetUserMember(db, v.UserID, "", "", model.VendorIDJX, model.MemberTypeDiscountCard, model.YES)
			v.UserMembers = userMembers
		}
		pagedInfo.Data = requestList
	}
	return pagedInfo, err
}
