package mtwmapi

import (
	"math"
	"strings"

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

const (
	CommentReplyStatusAll        = -1 //全部
	CommentReplyStatusNotReplied = 0  // 未回复
	CommentReplyStatusReplied    = 1  // 已回复

	MaxCommentQueryPageSize = 20
)

type OrderComment struct {
	AddComment           string   `json:"add_comment"`
	AddCommentTime       string   `json:"add_comment_time"`
	CommentContent       string   `json:"comment_content"`
	CommentID            int64    `json:"comment_id"`
	CommentLables        string   `json:"comment_lables"`
	CommentLableList     []string `json:"comment_lable_list"`
	CommentPictures      string   `json:"comment_pictures"`
	CommentTime          string   `json:"comment_time"`
	CriticFoodList       string   `json:"critic_food_list"`
	DeliveryCommentScore int      `json:"delivery_comment_score"`
	FoodCommentScore     int      `json:"food_comment_score"`
	OrderCommentScore    int      `json:"order_comment_score"`
	PackingScore         int      `json:"packing_score"`
	PraiseFoodList       string   `json:"praise_food_list"`
	ReplyStatus          int      `json:"reply_status"`
	Result               string   `json:"result"`
	ShipTime             int      `json:"ship_time"`
}

// 根据门店id批量查询评价信息（新版）
// http://developer.waimai.meituan.com/home/docDetail/191
func (a *API) CommentQuery(poiCode string, startDateStr, endDateStr string, offset, limit int, replyStatus int) (commentList []*OrderComment, err error) {
	params := map[string]interface{}{
		KeyAppPoiCode: poiCode,
		"start_time":  startDateStr,
		"end_time":    endDateStr,
		"pageoffset":  offset,
		"pagesize":    limit,
		"replyStatus": replyStatus,
	}
	if limit <= 0 {
		limit = math.MaxInt32
	}
	originalOffset := offset
	originalLimit := limit
	for {
		if limit <= 0 {
			break
		}
		if limit > MaxCommentQueryPageSize {
			limit = MaxCommentQueryPageSize
		}
		params["pageoffset"] = offset
		params["pagesize"] = limit
		result, err := a.AccessAPI("comment/query", true, params)
		if err != nil {
			return nil, err
		}
		var batchCommentList []*OrderComment
		err = utils.Map2StructByJson(result, &batchCommentList, false)
		if err != nil {
			return nil, err
		}
		for _, comment := range batchCommentList {
			if comment.CommentLables != "" {
				comment.CommentLableList = strings.Split(comment.CommentLables, ",")
			}
		}
		commentList = append(commentList, batchCommentList...)
		if len(batchCommentList) < limit {
			break
		}
		offset += limit
		limit = originalLimit + originalOffset - offset
	}
	return commentList, nil
}

// 根据评价id添加商家回复
// http://developer.waimai.meituan.com/home/docDetail/194
func (a *API) CommentAddReply(poiCode string, commentID int64, reply string) (err error) {
	_, err = a.AccessAPI("poi/comment/add_reply", false, map[string]interface{}{
		KeyAppPoiCode: poiCode,
		"comment_id":  commentID,
		"reply":       reply,
	})
	return err
}
