package hdl

import (
	"applet/app/db"
	"applet/app/db/model"
	"applet/app/e"
	"applet/app/md"
	storeSvc "applet/app/store/svc"
	"applet/app/svc"
	"applet/app/utils"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
	"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/ownStore/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/ownStore/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/ownStore/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)
	arg.StoreUid = utils.IntToStr(user.Info.Uid)
	data, total, _ := db.GetStoreOrderList(svc.MasterDb(c), arg, 0)
	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,
				"platform_commission": v.PlatformCommission,
				"commission":          v.Commission,
				"table_num":           v.TableNum,
				"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.store_uid=" + utils.IntToStr(user.Info.Uid) + " and ctpo.state=1"
	if arg["uid"] != "" {
		str += " and ctpo.uid=" + arg["uid"]
	}
	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,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
		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"],
			"amount":              v["amount"],
			"phone":               v["phone"],
			"uid":                 v["uid"],
			"agent_commission":    v["agent_commission"],
			"platform_commission": v["platform_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/ownStore/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
}
func StoreOrderConfirm(c *gin.Context) {
	storeSvc.StoreOrderConfirm(c)
}
func UserStoreInfo(c *gin.Context) {
	user := svc.GetUser(c)
	data, _ := db.SysModFindBySkipIdentifierWithUid(c, svc.MasterDb(c), "pub.flutter.user_store", user.Info.Uid)
	if data == nil {
		data = &model.SysModule{
			ModName:        "user_store",
			Position:       "user_store",
			SkipIdentifier: "pub.flutter.user_store",
			Title:          "店铺模板",
			Uid:            user.Info.Uid,
			State:          1,
			Data:           "{\"icon\":\"\",\"icon_url\":\"\",\"name\":\"\",\"store_detail_url\":\"\",\"address\":\"\",\"phone\":\"\",\"time_str\":\"\",\"notice_str\":\"\",\"banner_title\":\"\",\"activity_title\":\"\"}",
			Platform:       1,
			CreateAt:       time.Now(),
			UpdateAt:       time.Now(),
		}
		svc.MasterDb(c).Insert(data)
	}
	var tmp = make(map[string]interface{})
	json.Unmarshal([]byte(data.Data), &tmp)
	h5Domain := svc.GetWebSiteDomainInfo(c, "wap")
	store := db.GetStoreIdEg(svc.MasterDb(c), utils.IntToStr(user.Info.Uid))
	if store != nil {
		tmp["icon"] = store.Logo
		tmp["icon_url"] = store.Logo
		tmp["name"] = store.Name
		tmp["address"] = store.Address
		tmp["phone"] = store.Phone
		tmp["lat"] = store.Lat
		tmp["lng"] = store.Lng
		tmp["province"] = store.Province
		tmp["city"] = store.City
		tmp["district"] = store.District
		tmp["province_id"] = store.ProvinceId
		tmp["city_id"] = store.CityId
		tmp["district_id"] = store.DistrictId
		tmp["work_state"] = utils.IntToStr(store.WorkState)
	}
	tmp["share_url"] = h5Domain + "/#/zy-user-store/pages/store-page/index?uid=" + utils.IntToStr(user.Info.Uid)
	e.OutSuc(c, tmp, nil)
	return
}
func UserStoreInfoSet(c *gin.Context) {
	var arg map[string]interface{}
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	user := svc.GetUser(c)
	data, _ := db.SysModFindBySkipIdentifierWithUid(c, svc.MasterDb(c), "pub.flutter.user_store", user.Info.Uid)
	data.Data = utils.SerializeStr(arg)
	svc.MasterDb(c).Where("mod_id=?", data.ModId).Cols("data").Update(data)
	store := db.GetStoreIdEg(svc.MasterDb(c), utils.IntToStr(user.Info.Uid))
	if store == nil {
		store = &model.CommunityTeamStore{
			Uid:      user.Info.Uid,
			CreateAt: time.Now(),
			UpdateAt: time.Now(),
			State:    1,
		}
		svc.MasterDb(c).Insert(store)
	}
	if gjson.Get(data.Data, "address").String() != "" {
		store.Address = gjson.Get(data.Data, "address").String()
	}
	if gjson.Get(data.Data, "lat").String() != "" {
		store.Lat = gjson.Get(data.Data, "lat").String()
	}
	if gjson.Get(data.Data, "lng").String() != "" {
		store.Lng = gjson.Get(data.Data, "lng").String()
	}
	if gjson.Get(data.Data, "province").String() != "" {
		store.Province = gjson.Get(data.Data, "province").String()
	}
	if gjson.Get(data.Data, "city").String() != "" {
		store.City = gjson.Get(data.Data, "city").String()
	}
	if gjson.Get(data.Data, "district").String() != "" {
		store.District = gjson.Get(data.Data, "district").String()
	}
	if gjson.Get(data.Data, "province_id").String() != "" {
		store.ProvinceId = utils.StrToInt(gjson.Get(data.Data, "province_id").String())
	}
	if gjson.Get(data.Data, "city_id").String() != "" {
		store.CityId = utils.StrToInt(gjson.Get(data.Data, "city_id").String())
	}
	if gjson.Get(data.Data, "district_id").String() != "" {
		store.DistrictId = utils.StrToInt(gjson.Get(data.Data, "district_id").String())
	}
	if gjson.Get(data.Data, "name").String() != "" {
		store.Name = gjson.Get(data.Data, "name").String()
	}
	if gjson.Get(data.Data, "work_state").String() != "" {
		store.WorkState = utils.StrToInt(gjson.Get(data.Data, "work_state").String())
	}
	if gjson.Get(data.Data, "time_str").String() != "" {
		store.Timer = gjson.Get(data.Data, "time_str").String()
	}
	if gjson.Get(data.Data, "phone").String() != "" {
		store.Phone = gjson.Get(data.Data, "phone").String()
	}
	if gjson.Get(data.Data, "icon_url").String() != "" {
		store.Logo = gjson.Get(data.Data, "icon_url").String()
	}
	svc.MasterDb(c).Where("id=?", store.Id).Cols("province_id,city_id,district_id,timer,phone,logo,work_state,name,province,city,district,address,lat,lng").Update(store)
	e.OutSuc(c, "success", nil)
	return
}
func UserStoreBanner(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)
	uid := user.Info.Uid
	activity := db.GetUserStoreActivity(svc.MasterDb(c), arg["type"], uid)
	data := make([]map[string]string, 0)
	if activity != nil {
		scheme := svc.SysCfgGet(c, "file_bucket_scheme")
		domain := svc.SysCfgGet(c, "file_bucket_host")
		linkTypeStr := []string{"内链分享", "外链分享"}
		scheme, host := svc.ImageBucket(c)

		for _, v := range *activity {
			tmp := map[string]string{
				"id":            utils.IntToStr(v.Id),
				"title":         v.Title,
				"link_type_str": linkTypeStr[v.LinkType],
				"img":           svc.ImageFormatWithBucket(scheme, host, v.Img),
				"img_url":       svc.ImageFormatWithBucket(scheme, domain, v.Img),
				"label":         v.Label,
				"uid":           utils.IntToStr(v.Uid),
			}
			data = append(data, tmp)
		}
	}
	e.OutSuc(c, data, nil)
	return
}

func UserStoreBannerDetail(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	data := db.GetUserStoreActivityById(svc.MasterDb(c), arg["id"])
	if data == nil {
		e.OutErr(c, 400, e.NewErr(400, "记录不存在"))
		return
	}
	scheme := svc.SysCfgGet(c, "file_bucket_scheme")
	domain := svc.SysCfgGet(c, "file_bucket_host")
	res := map[string]string{
		"id":        utils.IntToStr(data.Id),
		"uid":       utils.IntToStr(data.Uid),
		"title":     data.Title,
		"img":       data.Img,
		"img_url":   svc.ImageFormatWithBucket(scheme, domain, data.Img),
		"label":     data.Label,
		"content":   data.Content,
		"type":      data.Type,
		"url":       data.Url,
		"link_type": utils.IntToStr(data.LinkType),
		"sort":      utils.IntToStr(data.Sort),
	}
	e.OutSuc(c, res, nil)
	return
}
func UserStoreBannerSave(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)
	data := model.UserStoreActivity{}
	if arg["id"] == "" {
		data = model.UserStoreActivity{
			Uid:  user.Info.Uid,
			Type: arg["type"],
			Time: time.Now(),
		}
		svc.MasterDb(c).Insert(&data)
	} else {
		svc.MasterDb(c).Where("id=?", arg["id"]).Get(&data)
	}
	data.Label = arg["label"]
	data.Img = arg["img"]
	data.Title = arg["title"]
	data.Content = arg["content"]
	data.LinkType = utils.StrToInt(arg["link_type"])
	data.Url = arg["url"]
	data.Sort = utils.StrToInt(arg["sort"])
	svc.MasterDb(c).Where("id=?", data.Id).Update(&data)
	e.OutSuc(c, "success", nil)
	return
}
func UserStoreBannerDel(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	svc.MasterDb(c).Where("id=?", arg["id"]).Delete(&model.UserStoreActivity{})
	e.OutSuc(c, "success", nil)
	return
}
