package mtwm

import (
	"fmt"
	"strings"
	"time"

	"git.rosy.net.cn/baseapi/platformapi/mtwmapi"

	"git.rosy.net.cn/jx-callback/business/jxutils/tasksch"
	"git.rosy.net.cn/jx-callback/business/partner"

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

const (
	RefreshCommentTime           = 7 * 24 * time.Hour // 此值必须大于24小时
	RefreshCommentTimeInterval   = 60 * time.Minute
	BAD_COMMENTS_MAX_MODIFY_TIME = 24 * 6 // 小时
)

func (c *PurchaseHandler) StartRefreshComment() {
	utils.AfterFuncWithRecover(5*time.Second, func() {
		c.refreshCommentOnce()
	})
}

func (c *PurchaseHandler) refreshCommentOnce() {
	c.RefreshComment(time.Now().Add(-RefreshCommentTime), time.Now())
	utils.AfterFuncWithRecover(RefreshCommentTimeInterval, func() {
		c.refreshCommentOnce()
	})
}

func formalizeTagList(mtwmTagList string) (outTagList string) {
	if mtwmTagList != "" {
		outTagList = string(utils.Format4Output(strings.Split(mtwmTagList, ","), true))
	}
	return outTagList
}

func (c *PurchaseHandler) RefreshComment(fromTime, toTime time.Time) (err error) {
	startTime := time.Now().Add(-24 * time.Hour)
	//endTime := time.Now().Add(-RefreshCommentTime)
	endDateStr := startTime.Format("20060102")
	startDateStr := time.Now().Add(-RefreshCommentTime).Format("20060102")
	storeIDs, _ := dao.GetOrderStoreIDs(dao.GetDB(), fromTime, toTime, model.VendorIDMTWM)
	task := tasksch.NewParallelTask("mtwm RefreshComment", nil, jxcontext.AdminCtx,
		func(task *tasksch.ParallelTask, batchItemList []interface{}, params ...interface{}) (retVal interface{}, err error) {
			storeID := batchItemList[0].(int)

			storeDetail, _ := dao.GetStoreDetail(dao.GetDB(), storeID, model.VendorIDMTWM, "")
			commentList, _ := getAPI(storeDetail.VendorOrgCode, storeID, storeDetail.VendorStoreID).CommentQuery(storeDetail.VendorStoreID, startDateStr, endDateStr, 0, 0, mtwmapi.CommentReplyStatusNotReplied)
			var orderCommentList []*model.OrderComment
			if len(commentList) == model.NO || commentList == nil {
				return nil, nil
			}
			for _, mtwmComment := range commentList {
				createdTime, err := utils.TryStr2Time(mtwmComment.CommentTime)
				if err == nil {
					orderComment := &model.OrderComment{
						VendorOrderID:  utils.Int64ToStr(mtwmComment.CommentID), // 美团评价不能得到订单号，以评价ID代替
						VendorID:       model.VendorIDMTWM,
						UserCommentID:  utils.Int64ToStr(mtwmComment.CommentID),
						VendorStoreID:  storeDetail.VendorStoreID,
						TagList:        formalizeTagList(mtwmComment.CommentLables),
						Score:          int8(mtwmComment.FoodCommentScore),
						ModifyDuration: BAD_COMMENTS_MAX_MODIFY_TIME,
						OriginalMsg:    string(utils.MustMarshal(mtwmComment)),
						IsReplied:      int8(mtwmComment.ReplyStatus),
						StoreID:        storeDetail.ID,
					}
					if orderComment.IsReplied == 0 {
						orderComment.Content = mtwmComment.CommentContent
						orderComment.CommentCreatedAt = createdTime
					} else {
						orderComment.Content = mtwmComment.AddComment
						if updatedTime, err := utils.TryStr2Time(mtwmComment.CommentTime); err == nil {
							orderComment.CommentCreatedAt = updatedTime
						}
					}

					foodNameList := make(map[string]int, 0)
					skuIdMap := make(map[string]int, 0)
					for _, fn := range mtwmComment.PraiseRetailList {
						skuIdMap[fn.SkuId] = 1
						foodNameList[fn.Name] = 1
					}
					for _, fn := range mtwmComment.CriticRetailList {
						skuIdMap[fn.SkuId] = 1
						foodNameList[fn.Name] = 1
					}

					for _, fn := range mtwmComment.CommentOrderDetail {
						if len(fn.FoodName)-strings.LastIndex(fn.FoodName, "）") > 3 {
							foodNameList[strings.TrimSpace(fn.FoodName)] = 1
						} else {
							foodNameList[strings.TrimSpace(fn.FoodName[0:strings.LastIndex(fn.FoodName, "（")])] = 1
						}
					}
					nameList := make([]string, 0, 0)
					skuIdList := make([]int, 0, 0)
					for k, _ := range foodNameList {
						nameList = append(nameList, k)
					}
					for k, _ := range skuIdMap {
						skuIdList = append(skuIdList, utils.Str2Int(k))
					}

					if len(foodNameList) > 0 || len(skuIdList) > 0 {
						vendorOrderID, _ := dao.GetBadCommentOrderId(storeDetail.ID, time.Now().Add(-RefreshCommentTime), startTime, nameList, nil)
						if vendorOrderID != "" {
							orderComment.VendorOrderID2 = vendorOrderID
						} else if len(skuIdList) > 0 {
							vendorOrderID, _ = dao.GetBadCommentOrderId(storeDetail.ID, time.Now().Add(-RefreshCommentTime), startTime, nil, skuIdList)
							orderComment.VendorOrderID2 = vendorOrderID
						}
					}
					orderCommentList = append(orderCommentList, orderComment)
				}
			}

			if len(orderCommentList) > 0 {
				err = partner.CurOrderManager.OnOrderComments(orderCommentList)
			}

			return orderCommentList, nil
		}, storeIDs)

	task.Run()
	resultList, err2 := task.GetResult(0)
	if err = err2; err != nil {
		globals.SugarLogger.Debugf("----------resultList err:= %v", err)
		return err
	}

	if len(resultList) != 0 {
		globals.SugarLogger.Debugf("----------resultList:= %d", len(resultList))
	}
	//var orderCommentList []*model.OrderComment
	//for _, result := range resultList {
	//	orderComment := result.(*model.OrderComment)
	//	orderCommentList = append(orderCommentList, orderComment)
	//}
	//
	//if len(orderCommentList) > 0 {
	//	err = partner.CurOrderManager.OnOrderComments(orderCommentList)
	//}
	//
	return err
}

func (c *PurchaseHandler) ReplyOrderComment(ctx *jxcontext.Context, vendorOrgCode string, orderComment *model.OrderComment, replyComment string) (err error) {
	if globals.EnableMtwmStoreWrite {
		err = getAPI(vendorOrgCode, orderComment.StoreID, orderComment.VendorStoreID).CommentAddReply(orderComment.VendorStoreID, utils.Str2Int64(orderComment.UserCommentID), replyComment)
	}
	return err
}

func GetMtwmCommentList4ShanGou(key string, appOrgCode string, startTime, endTime string) error {
	var (
		db      = dao.GetDB()
		now     = time.Now()
		errs    = make([]string, 0, 0)
		pageNum = 1
	)
	end, _ := utils.TryStr2Time(endTime)
	if end.Year() == now.Year() && end.Month() == now.Month() && end.Day() == now.Day() {
		return fmt.Errorf("结束时间不能是当前时间")
	}
	configList, err := dao.QueryConfigs(db, key, "Cookie", "")
	if err != nil {
		return err
	}
	if len(configList) != model.YES {
		return fmt.Errorf("查询异常,请输入正确的key或者添加此key")
	}

	param := map[string]interface{}{
		"wmPoiId":   -1,
		"appType":   3,
		"pageNum":   pageNum,
		"rate":      0,
		"reply":     -1,
		"context":   -1,
		"startDate": startTime,
		"endDate":   endTime,
		"timeType":  4,
	}
	for {
		param["pageNum"] = pageNum
		commentList, err := getAPI(appOrgCode, 0, "").GetComment4ShanGou(param, true, configList[0].Value)
		if err != nil {
			return err
		}
		if len(commentList) == model.NO && pageNum == model.YES {
			return fmt.Errorf("查询参数暂未获取到数据")
		}
		// 差评订单数据
		orderCommentList := CommentListData(db, commentList, startTime, endTime)
		if len(orderCommentList) > 0 {
			err2 := partner.CurOrderManager.OnOrderComments(orderCommentList)
			if err2 != nil {
				errs = append(errs, err2.Error())
			}
		}
		if len(commentList) >= 10 {
			pageNum += 1
		} else {
			break
		}
	}

	if len(errs) != model.NO {
		return fmt.Errorf("%s", strings.Join(errs, ","))
	}

	return nil
}

func CommentListData(db *dao.DaoDB, skuList []*mtwmapi.CommentsList, startTime, endTime string) []*model.OrderComment {
	st, _ := utils.TryStr2Time(startTime)
	et, _ := utils.TryStr2Time(endTime)
	orderCommentList := make([]*model.OrderComment, 0, len(skuList))

	for _, mtwmComment := range skuList {
		store, err := dao.GetStoreDetailByVendorStoreID(db, utils.Int2Str(mtwmComment.WmPoiId), model.VendorIDMTWM, "")
		if err != nil {
			continue
		}
		createdTime, _ := utils.TryStr2Time(mtwmComment.CreateTime)
		orderComment := &model.OrderComment{
			VendorOrderID:  utils.Int64ToStr(mtwmComment.Id), // 美团评价不能得到订单号，以评价ID代替
			VendorID:       model.VendorIDMTWM,
			UserCommentID:  utils.Int64ToStr(mtwmComment.UserId),
			VendorStoreID:  utils.Int2Str(mtwmComment.WmPoiId),
			TagList:        "",
			Score:          int8(mtwmComment.FoodCommentScore),
			ModifyDuration: BAD_COMMENTS_MAX_MODIFY_TIME,
			OriginalMsg:    string(utils.MustMarshal(mtwmComment)),
			IsReplied:      0,
			StoreID:        0,
		}
		if len(mtwmComment.ECommentList) != 0 {
			orderComment.IsReplied = 1
		}

		if orderComment.IsReplied == 0 {
			orderComment.Content = mtwmComment.MasterCleanComment
			orderComment.CommentCreatedAt = createdTime
		} else {
			orderComment.Content = mtwmComment.Comment
			orderComment.CommentCreatedAt = utils.Timestamp2Time(int64(mtwmComment.Utime))
		}

		// 商品的名称集合
		foodNameList := make(map[string]int, 0)
		// 好评商品
		for _, fn := range mtwmComment.PraiseFoodList {
			foodNameList[fn] = 1
		}
		// 差评商品
		for _, fn := range mtwmComment.CriticFoodList {
			foodNameList[fn] = 1
		}
		// 列表商品
		for _, fn := range mtwmComment.SpuCommentList {
			foodNameList[fn.SpuName] = 1
		}
		// 包含（）中文括号的商品
		for _, fn := range mtwmComment.OrderStatus.Details {
			if len(fn.FoodName)-strings.LastIndex(fn.FoodName, "）") > 3 {
				foodNameList[strings.TrimSuffix(fn.FoodName, " ")] = 1
			} else {
				foodNameList[strings.TrimSuffix(fn.FoodName[0:strings.LastIndex(fn.FoodName, "（")], " ")] = 1
			}
		}

		orderComment.StoreID = store.ID
		if len(foodNameList) > 0 {
			foodName := make([]string, 0, len(foodNameList))
			for fnl, _ := range foodNameList {
				foodName = append(foodName, fnl)
			}
			vendorOrderID, _ := dao.GetBadCommentOrderId(store.ID, st.AddDate(0, 0, -7), et.AddDate(0, 0, 7), foodName, nil)
			if vendorOrderID != "" {
				orderComment.VendorOrderID2 = vendorOrderID
			}
		}
		orderCommentList = append(orderCommentList, orderComment)

	}

	return orderCommentList
}
