package hdl

import (
	agentSvc "applet/app/agent/svc"
	"applet/app/db"
	"applet/app/db/model"
	"applet/app/e"
	"applet/app/md"
	"applet/app/svc"
	"applet/app/utils"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

// UserStoreList 门店列表
// @Summary      门店-列表
// @Tags         门店
// @Description  门店-列表
// @Accept       json
// @Produce      json
// @Param        req 	body      md.Store          true   "请求参数"
// @Success      200   {string} 				""
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/v1/communityTeam/agent/store/list [POST]
func UserStoreList(c *gin.Context) {
	var arg md.Store
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	user := svc.GetUser(c)
	list, count := db.GetUserList(svc.MasterDb(c), arg, user.Info.Uid)
	data := make([]map[string]interface{}, 0)
	if list != nil {
		currentMonth := utils.GetTimeRange("current_month")
		for _, v := range *list {
			store := v.CommunityTeamStore
			tmp := map[string]interface{}{
				"uid":                 utils.IntToStr(v.User.Uid),
				"create_at":           store.CreateAt.Format("2006-01-02 15:04:05"),
				"name":                "",
				"address":             "",
				"logo":                "",
				"order_count":         "0",
				"order_amount":        "0",
				"agent_commission":    "0",
				"platform_commission": "0",
				"base_commission":     "0",
				"work_state":          "",
			}
			count1, _ := svc.MasterDb(c).Where("store_uid=? and parent_uid=?", v.User.Uid, user.Info.Uid).In("state", []string{"1", "2"}).Count(&model.CommunityTeamOrder{})
			sum, _ := svc.MasterDb(c).Where("store_uid=? and parent_uid=? and create_at>=?", v.User.Uid, user.Info.Uid, time.Unix(currentMonth["start"], 0).Format("2006-01-02 15:04:05")).In("state", []string{"1", "2"}).Sum(&model.CommunityTeamOrder{}, "amount")
			tmp["order_count"] = utils.Int64ToStr(count1)
			tmp["order_amount"] = svc.GetCommissionPrec(c, utils.Float64ToStr(sum), "2", "")
			tmp["name"] = store.Name
			tmp["address"] = store.Address
			tmp["logo"] = store.Logo
			tmp["work_state"] = "营业中"
			if store.WorkState == 1 {
				tmp["work_state"] = "休息中"
			}
			tmp["agent_commission"] = store.AgentCommission
			data = append(data, tmp)
		}
	}
	res := map[string]interface{}{
		"total": count,
		"list":  data,
	}
	e.OutSuc(c, res, nil)
}

// UserStoreSave 门店编辑
// @Summary      门店-门店编辑
// @Tags         门店
// @Description  门店-门店编辑
// @Accept       json
// @Produce      json
// @Param        req 	body      md.StoreSave          true   "请求参数"
// @Success      200   {string} 				""
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/v1/communityTeam/agent/store/save [POST]
func UserStoreSave(c *gin.Context) {
	var arg md.StoreSave
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	store := db.GetUserStore(svc.MasterDb(c), utils.StrToInt(arg.Uid))
	if store == nil {
		e.OutErr(c, 400, e.NewErr(400, "门店不存在"))
		return
	}
	store.AgentCommission = arg.AgentCommission
	svc.MasterDb(c).Where("id=?", store.Id).Cols("agent_commission").Update(store)
	e.OutSuc(c, "success", nil)
	return
}

// UserStoreOrder 门店订单-订单管理共用一个
// @Summary      门店-门店订单
// @Tags         门店
// @Description  门店-门店订单
// @Accept       json
// @Produce      json
// @Param        req 	body      md.StoreOrder          true   "请求参数"
// @Success      200   {string} 				""
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/v1/communityTeam/agent/store/order [POST]
func UserStoreOrder(c *gin.Context) {
	var arg md.StoreOrder
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	user := svc.GetUser(c)
	data, total, _ := db.GetStoreOrderList(svc.MasterDb(c), arg, user.Info.Uid)
	list := make([]map[string]string, 0)
	if data != nil {
		stateList := []string{"待付款", "已支付", "已提货", "已取消"}
		for _, v := range *data {
			tmp := map[string]string{
				"oid":              utils.Int64ToStr(v.Oid),
				"uid":              utils.IntToStr(v.Uid),
				"phone":            "",
				"nickname":         "",
				"store_name":       "",
				"state_str":        stateList[v.State],
				"amount":           v.Amount,
				"agent_commission": v.AgentCommission,
				"state":            utils.IntToStr(v.State),
				"create_at":        v.CreateAt.Format("2006-01-02 15:04:05"),
				"confirm_at":       utils.Int64ToStr(v.Oid),
			}
			if v.ConfirmAt.IsZero() == false {
				tmp["confirm_at"] = v.ConfirmAt.Format("2006-01-02 15:04:05")
			}
			user1, _ := db.UserFindByID(svc.MasterDb(c), v.Uid)
			if user1 != nil {
				tmp["phone"] = user1.Phone
				tmp["nickname"] = user1.Nickname
			}
			store := db.GetUserStore(svc.MasterDb(c), v.StoreUid)
			if store != nil {
				tmp["store_name"] = store.Name
			}
			list = append(list, tmp)
		}
	}
	res := map[string]interface{}{
		"total": total,
		"state": []map[string]string{
			{"name": "待付款", "value": "0"},
			{"name": "已支付", "value": "1"},
			{"name": "已提货", "value": "2"},
			{"name": "已取消", "value": "3"},
		},
		"list": list,
	}
	e.OutSuc(c, res, nil)
}
func UserStoreOrderPay(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	user := svc.GetUser(c)
	str := "ctpo.parent_uid=" + utils.IntToStr(user.Info.Uid) + " and ctpo.state=1"
	if arg["uid"] != "" {
		str += " and ctpo.uid=" + arg["uid"]
	}
	if arg["store_id"] != "" {
		str += " and ctpo.store_uid=" + arg["store_id"]
	}
	if arg["store_name"] != "" {
		str += " and cts.name like '%" + arg["store_name"] + "%'"
	}
	if arg["phone"] != "" {
		str += " and u.phone like '%" + arg["phone"] + "%'"
	}
	if arg["oid"] != "" {
		str += " and ctpo.oid like '%" + arg["oid"] + "%'"
	}
	if arg["start_time"] != "" {
		str += " and ctpo.pay_at>='" + arg["start_time"] + "'"
	}
	if arg["end_time"] != "" {
		str += " and ctpo.pay_at<='" + arg["end_time"] + "'"
	}

	sql := `select ctpo.pay_at,ctpo.oid,cts.name,u.phone,ctpo.uid,ctpo.amount,ctpo.agent_commission,ctpo.platform_commission from community_team_pay_order ctpo 
		LEFT JOIN user u on u.uid=ctpo.uid
		LEFT JOIN community_team_store cts on cts.uid=ctpo.store_uid
		where %s order by ctpo.pay_at desc %s`
	size := utils.StrToInt(arg["size"])
	start := (utils.StrToInt(arg["p"]) - 1) * size
	sql = fmt.Sprintf(sql, str, "limit "+utils.IntToStr(start)+","+utils.IntToStr(size))
	nativeString, _ := db.QueryNativeString(svc.MasterDb(c), sql)
	list := make([]map[string]string, 0)
	for _, v := range nativeString {
		tmp := map[string]string{
			"time":             v["pay_at"],
			"name":             v["name"],
			"amount":           v["amount"],
			"phone":            v["phone"],
			"uid":              v["uid"],
			"agent_commission": v["agent_commission"],
			"oid":              v["oid"],
		}
		list = append(list, tmp)
	}
	sql1 := `select COUNT(*) as count from community_team_pay_order ctpo 
		LEFT JOIN user u on u.uid=ctpo.uid
		where %s `
	sql = fmt.Sprintf(sql, str)
	nativeString1, _ := db.QueryNativeString(svc.MasterDb(c), sql1)
	total := 0
	for _, v := range nativeString1 {
		total = utils.StrToInt(v["count"])
	}
	res := map[string]interface{}{
		"total": total,
		"list":  list,
	}

	e.OutSuc(c, res, nil)
	return
}

// UserStoreOrderDetail 门店订单详情-订单管理共用一个
// @Summary      门店-门店订单详情
// @Tags         门店
// @Description  门店-门店订单详情
// @Accept       json
// @Produce      json
// @Param        req 	body      md.StoreOrderDetail          true   "请求参数"
// @Success      200   {string} 				""
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/v1/communityTeam/agent/store/order/detail [POST]
func UserStoreOrderDetail(c *gin.Context) {
	var arg md.StoreOrderDetail
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	order := db.GetOrderByOid(svc.MasterDb(c), arg.Oid)
	if order == nil {
		e.OutErr(c, 400, e.NewErr(400, "订单不存在"))
		return
	}
	stateList := []string{"待付款", "已支付", "已提货", "已取消"}
	payMethodStr := []string{"余额支付", "支付宝支付", "微信支付"}
	orderInfoMap := make([]map[string]string, 0)
	res := map[string]interface{}{
		"oid":            utils.Int64ToStr(order.Oid),
		"uid":            utils.IntToStr(order.Uid),
		"phone":          order.Phone,
		"nickname":       "",
		"store_name":     "",
		"memo":           order.Memo,
		"coupon":         order.Coupon,
		"code":           order.Code,
		"amount":         order.Amount,
		"all_amount":     utils.Float64ToStr(utils.StrToFloat64(order.Amount) + utils.StrToFloat64(order.Coupon)),
		"pay_method_str": payMethodStr[order.PayMethod],
		"state_str":      stateList[order.State],
		"state":          utils.IntToStr(order.State),
		"create_at":      order.CreateAt.Format("2006-01-02 15:04:05"),
		"confirm_at":     "",
		"pay_at":         "",
		"order_info":     orderInfoMap,
	}
	if order.ConfirmAt.IsZero() == false {
		res["confirm_at"] = order.ConfirmAt.Format("2006-01-02 15:04:05")
	} else {
		res["confirm_at"] = order.Timer
		if order.IsNow == 1 {
			res["confirm_at"] = "立即提货"
		}
	}
	if order.PayAt.IsZero() == false {
		res["pay_at"] = order.PayAt.Format("2006-01-02 15:04:05")
	}

	user, _ := db.UserFindByID(svc.MasterDb(c), order.Uid)
	if user != nil {
		res["nickname"] = user.Nickname
		if order.Phone == "" {
			res["phone"] = user.Phone
		}
	}
	store := db.GetUserStore(svc.MasterDb(c), order.StoreUid)
	if store != nil {
		res["store_name"] = store.Name
	}
	orderInfo := db.GetOrderInfoAllEg(svc.MasterDb(c), arg.Oid)
	if orderInfo != nil {
		scheme, host := svc.ImageBucket(c)

		for _, v := range *orderInfo {
			skuData := make([]md.Sku, 0)
			json.Unmarshal([]byte(v.SkuInfo), &skuData)
			skuStr := ""
			for _, v1 := range skuData {
				if skuStr != "" {
					skuStr += ";"
				}
				skuStr += v1.Value
			}
			tmp := map[string]string{
				"sku_str":     skuStr,
				"goods_title": v.Title,
				"goods_img":   svc.ImageFormatWithBucket(scheme, host, v.Img),
				"num":         utils.IntToStr(v.Num),
				"amount":      utils.Float64ToStr(float64(v.Num) * utils.StrToFloat64(v.Price)),
			}
			orderInfoMap = append(orderInfoMap, tmp)
		}
		res["order_info"] = orderInfoMap
	}

	e.OutSuc(c, res, nil)
	return
}

// UserStoreTotal 销售额统计
// @Summary      门店-销售额统计
// @Tags         门店
// @Description  门店-销售额统计
// @Accept       json
// @Produce      json
// @Param        req 	body      md.StoreOrderTotal          true   "请求参数"
// @Success      200   {string} 				""
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/v1/communityTeam/agent/store/total [POST]
func UserStoreTotal(c *gin.Context) {
	var arg md.StoreOrderTotal
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	user := svc.GetUser(c)
	currentMonth := utils.GetTimeRange("current_month")
	today := utils.GetTimeRange("today")
	withinSevenDays := utils.GetTimeRange("within_seven_days")

	monthSum, _ := svc.MasterDb(c).Where("store_uid=? and parent_uid=? and create_at>=?", arg.StoreUid, user.Info.Uid, time.Unix(currentMonth["start"], 0).Format("2006-01-02 15:04:05")).In("state", []string{"1", "2"}).Sum(&model.CommunityTeamOrder{}, "amount")
	daySum, _ := svc.MasterDb(c).Where("store_uid=? and parent_uid=? and create_at>=?", arg.StoreUid, user.Info.Uid, time.Unix(today["start"], 0).Format("2006-01-02 15:04:05")).In("state", []string{"1", "2"}).Sum(&model.CommunityTeamOrder{}, "amount")
	withinSevenDaysSum, _ := svc.MasterDb(c).Where("store_uid=? and parent_uid=? and create_at>=?", arg.StoreUid, user.Info.Uid, time.Unix(withinSevenDays["start"], 0).Format("2006-01-02 15:04:05")).In("state", []string{"1", "2"}).Sum(&model.CommunityTeamOrder{}, "amount")
	list := []map[string]string{
		{"name": "本日销售额", "value": utils.Float64ToStr(daySum)},
		{"name": "近七日销售额", "value": utils.Float64ToStr(withinSevenDaysSum)},
		{"name": "本月销售额", "value": utils.Float64ToStr(monthSum)},
	}
	commission, _ := svc.MasterDb(c).Where("store_uid=? and parent_uid=? ", arg.StoreUid, user.Info.Uid).Sum(&model.CommunityTeamOrder{}, "agent_commission")

	store := db.GetStoreIdEg(svc.MasterDb(c), arg.StoreUid)
	res := map[string]interface{}{
		"list":            list,
		"platform_bili":   "-",
		"platform_amount": "-",
		"base_bili":       "-",
		"base_amount":     "-",
		"agent_bili":      store.AgentCommission + "%",
		"agent_amount":    utils.Float64ToStr(commission),
	}
	e.OutSuc(c, res, nil)
	return
}

func StoreWithdrawFlow(c *gin.Context) {
	agentSvc.StoreWithdrawFlow(c)
}
func StoreWithdrawTotal(c *gin.Context) {
	agentSvc.StoreWithdrawTotal(c)
}
func StoreWithdrawAudit(c *gin.Context) {
	agentSvc.StoreWithdrawAudit(c)
}
func StoreWithdrawAuditAll(c *gin.Context) {
	agentSvc.StoreWithdrawAuditAll(c)
}
func StoreWithdrawOutPut(c *gin.Context) {
	agentSvc.StoreWithdrawOutPut(c)
}
