package svc

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

func StorePayInfo(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	engine := MasterDb(c)
	store := db.GetStoreIdEg(engine, arg["store_id"])
	if store == nil {
		e.OutErr(c, 400, e.NewErr(400, "门店不存在"))
		return
	}
	res := map[string]string{
		"name": store.Name, "logo": store.Logo,
	}
	e.OutSuc(c, res, nil)
	return
}
func StorePayScan(c *gin.Context) {
	kind := c.DefaultQuery("type", "alipay") //1:支付宝 2：微信
	id, _ := c.GetQuery("id")
	if id == "" {
		e.OutErr(c, e.ERR_INVALID_ARGS, nil)
		return
	}
	engine := MasterDb(c)
	data := db.GetStorePayQrcodeById(engine, id)
	if data == nil {
		e.OutErr(c, 400, e.NewErr(400, "桌码不存在"))
		return
	}
	if data.IsUse != 1 {
		e.OutErr(c, 400, e.NewErr(400, "桌码不可用"))
		return
	}
	type RefundReq struct {
		StoreId    string `json:"store_id" `
		StoreType  string `json:"store_type" `
		AppId      string `json:"app_id" `
		AppLogo    string `json:"app_logo"`
		InviteCode string `json:"invite_code"`
	}
	store := db.GetStoreIdEg(engine, utils.IntToStr(data.Uid))
	if store == nil {
		e.OutErr(c, 400, e.NewErr(400, "门店不存在"))
		return
	}
	user, _ := db.UserProfileFindByID(engine, store.Uid)
	var appId = ""
	var appLogo = ""
	var inviteCode = user.InviteCode
	if kind != "alipay" {
		communityTeamStoreWxAppletId := db.SysCfgGet(c, "community_team_store_wx_applet_id")
		var wxApplet model.WxAppletList
		MasterDb(c).Where("id=?", communityTeamStoreWxAppletId).Get(&wxApplet)
		appId = wxApplet.OriginalAppId
		appLogo = wxApplet.AppletLogo
	}

	var result = RefundReq{
		StoreId:    utils.IntToStr(data.Uid),
		AppId:      appId,
		StoreType:  utils.IntToStr(store.StoreType),
		InviteCode: inviteCode,
		AppLogo:    appLogo,
	}
	e.OutSuc(c, result, nil)
	return
}
func StoreScan(c *gin.Context) {
	kind := c.DefaultQuery("type", "alipay") //1:支付宝 2：微信
	id, _ := c.GetQuery("id")
	if id == "" {
		e.OutErr(c, e.ERR_INVALID_ARGS, nil)
		return
	}
	engine := MasterDb(c)
	data := db.GetStoreQrcodeById(engine, id)
	if data == nil {
		e.OutErr(c, 400, e.NewErr(400, "桌码不存在"))
		return
	}
	if data.IsUse != 1 {
		e.OutErr(c, 400, e.NewErr(400, "桌码不可用"))
		return
	}
	type RefundReq struct {
		StoreId     string `json:"store_id" `
		StoreType   string `json:"store_type" `
		TableNumber string `json:"table_number" `
		AppId       string `json:"app_id" `
		AppLogo     string `json:"app_logo"`
		InviteCode  string `json:"invite_code"`
	}
	store := db.GetStoreIdEg(engine, utils.IntToStr(data.Uid))
	if store == nil {
		e.OutErr(c, 400, e.NewErr(400, "门店不存在"))
		return
	}
	user, _ := db.UserProfileFindByID(engine, store.Uid)
	var appId = ""
	var appLogo = ""
	var inviteCode = user.InviteCode
	if kind != "alipay" && kind != "alipay_applet" {
		communityTeamStoreWxAppletId := db.SysCfgGet(c, "community_team_store_wx_applet_id")
		var wxApplet model.WxAppletList
		MasterDb(c).Where("id=?", communityTeamStoreWxAppletId).Get(&wxApplet)
		appId = wxApplet.OriginalAppId
		appLogo = wxApplet.AppletLogo
	}

	var result = RefundReq{
		StoreId:     utils.IntToStr(data.Uid),
		TableNumber: data.TableNum,
		AppId:       appId,
		StoreType:   utils.IntToStr(store.StoreType),
		InviteCode:  inviteCode,
		AppLogo:     appLogo,
	}
	e.OutSuc(c, result, nil)
	return
}
func BankStore(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	arg["store_type"] = "0"
	user, _ := GetDefaultUser(c, c.GetHeader("Authorization"))
	var store = make([]map[string]string, 0)
	if arg["cid"] == "2" || arg["is_like"] == "1" {
		store = db.GetStoreLike(MasterDb(c), arg)
	} else {
		store = db.GetStore(MasterDb(c), arg)
	}
	storeList := make([]map[string]interface{}, 0)
	for _, v := range store {
		km := v["km"]
		if utils.StrToFloat64(v["km"]) < 1 {
			v["km"] = utils.IntToStr(int(utils.StrToFloat64(v["km"])*1000)) + "m"
		} else {
			v["km"] = GetCommissionPrec(c, v["km"], "2", "1")
			v["km"] += "km"
		}
		if utils.StrToFloat64(km) <= 0 || utils.StrToFloat64(v["lat"]) == 0 || utils.StrToFloat64(v["lng"]) == 0 {
			v["km"] = "-"
		}
		label := make([]string, 0)
		if v["is_new"] == "1" {
			label = append(label, "新门店")
		}
		isWork := "1"
		if v["work_state"] == "1" {
			isWork = "0"
		}
		tmp := map[string]interface{}{
			"lat":      v["lat"],
			"lng":      v["lng"],
			"address":  v["address"],
			"name":     v["name"],
			"id":       v["id"],
			"km":       v["km"],
			"time_str": v["timer"],
			"uid":      v["uid"],
			"phone":    v["phone"],
			"logo":     v["logo"],
			"is_work":  isWork,
			"is_like":  "0",
			"fan":      "",
			"label":    label,
		}
		if utils.StrToInt(v["fan"]) > 0 {
			tmp["fan"] = v["fan"]
		}
		if user != nil {
			count, _ := MasterDb(c).Where("uid=? and store_id=?", user.Info.Uid, v["id"]).Count(&model.CommunityTeamStoreLike{})
			if count > 0 {
				tmp["is_like"] = "1"
			}
		}
		storeList = append(storeList, tmp)
	}
	e.OutSuc(c, storeList, nil)
	return
}
func BankNotice(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.GetBankNotice(MasterDb(c), arg)
	list := make([]map[string]string, 0)
	if data != nil {
		for _, v := range *data {
			tmp := map[string]string{
				"id":          utils.IntToStr(v.Id),
				"title":       v.Title,
				"content":     v.Content,
				"create_time": v.CreateTime.Format("2006-01-02 15:04"),
			}
			list = append(list, tmp)
		}
	}
	e.OutSuc(c, list, nil)
	return
}
func BankActivity(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	list := make([]map[string]interface{}, 0)
	cate := db.GetActivityCate(MasterDb(c), arg["uid"])
	if cate != nil {
		ids := make([]int, 0)
		for _, v := range *cate {
			ids = append(ids, v.Id)
		}
		activityMap := make(map[int][]map[string]interface{})
		if len(ids) > 0 {
			activity := db.GetActivity(MasterDb(c), ids)
			if activity != nil {
				scheme, host := ImageBucket(c)
				for _, v := range *activity {
					_, ok := activityMap[v.Cid]
					if ok == false {
						activityMap[v.Cid] = make([]map[string]interface{}, 0)
					}
					var skip md.Skip
					json.Unmarshal(utils.MarshalJSONCamelCase2JsonSnakeCase(v.Skip), &skip)
					tmp := map[string]interface{}{
						"name": v.Name, "img": ImageFormatWithBucket(scheme, host, v.Img), "skip": skip,
					}
					activityMap[v.Cid] = append(activityMap[v.Cid], tmp)
				}
			}
		}
		for _, v := range *cate {
			tmpList := make([]map[string]interface{}, 0)
			_, ok := activityMap[v.Id]
			if ok {
				tmpList = activityMap[v.Id]
			}
			tmp := map[string]interface{}{
				"name": v.Name,
				"list": tmpList,
			}
			list = append(list, tmp)
		}
	}
	e.OutSuc(c, list, nil)
	return
}
func BankCardDetail(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	detail := db.GetCardDetail(MasterDb(c), arg)
	if detail == nil {
		e.OutErr(c, 400, e.NewErr(400, "记录不存在"))
		return
	}
	tmp := map[string]string{
		"id":         utils.IntToStr(detail.Id),
		"title":      detail.Title,
		"first_tip":  detail.FirstTip,
		"second_tip": detail.SecondTip,
		"time_str":   "",
		"content":    detail.Content,
		"type":       "0",
	}
	if tmp["time_str"] != "" {
		tmp["type"] = "1"
	}
	if detail.IsUse == 0 {
		tmp["type"] = "2"
	}
	e.OutSuc(c, tmp, nil)
	return
}
func BankCard(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	list := make([]map[string]string, 0)
	data := db.GetCard(MasterDb(c), arg)
	if data != nil {
		scheme, host := ImageBucket(c)
		for _, v := range *data {
			tmp := map[string]string{
				"id":         utils.IntToStr(v.Id),
				"title":      v.Title,
				"first_tip":  v.FirstTip,
				"second_tip": v.SecondTip,
				"time_str":   "",
				"img":        ImageFormatWithBucket(scheme, host, v.Img),
				"type":       "0",
			}
			if tmp["time_str"] != "" {
				tmp["type"] = "1"
			}
			if v.IsUse == 0 {
				tmp["type"] = "2"
			}
			list = append(list, tmp)
		}
	}
	e.OutSuc(c, list, nil)
	return
}
func NewStore(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	arg["store_type"] = "3"
	user, _ := GetDefaultUser(c, c.GetHeader("Authorization"))
	var store = make([]map[string]string, 0)
	if arg["cid"] == "2" {
		store = db.GetStoreLike(MasterDb(c), arg)
	} else {
		store = db.GetStore(MasterDb(c), arg)
	}
	storeList := make([]map[string]interface{}, 0)
	for _, v := range store {
		km := v["km"]
		if utils.StrToFloat64(v["km"]) < 1 {
			v["km"] = utils.IntToStr(int(utils.StrToFloat64(v["km"])*1000)) + "m"
		} else {
			v["km"] = GetCommissionPrec(c, v["km"], "2", "1")
			v["km"] += "km"
		}
		if utils.StrToFloat64(km) <= 0 || utils.StrToFloat64(v["lat"]) == 0 || utils.StrToFloat64(v["lng"]) == 0 {
			v["km"] = "-"
		}
		tmp := map[string]interface{}{
			"lat":        v["lat"],
			"lng":        v["lng"],
			"address":    v["address"],
			"name":       v["name"],
			"id":         v["id"],
			"km":         v["km"],
			"time_str":   v["timer"],
			"uid":        v["uid"],
			"store_id":   v["uid"],
			"store_type": v["store_type"],
			"phone":      v["phone"],
			"logo":       v["logo"],
			"is_like":    "0",
			"fan":        "",
		}
		if user != nil {
			count, _ := MasterDb(c).Where("uid=? and store_id=?", user.Info.Uid, v["id"]).Count(&model.CommunityTeamStoreLike{})
			if count > 0 {
				tmp["is_like"] = "1"
			}
		}
		storeList = append(storeList, tmp)
	}
	e.OutSuc(c, storeList, nil)
	return
}
func StoreLike(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	arg["store_type"] = "0"
	storeId := GetStoreId(c)

	if utils.StrToInt(storeId) > 0 {
		arg["store_id"] = storeId
		storeData := db.GetStoreIdEg(MasterDb(c), storeId)
		if storeData.StoreType == 0 {
			arg["store_id"] = "0"
		}
		arg["store_type"] = utils.IntToStr(storeData.StoreType)
	}
	user, _ := GetDefaultUser(c, c.GetHeader("Authorization"))
	store := db.GetStoreLike(MasterDb(c), arg)
	storeList := make([]map[string]interface{}, 0)
	for _, v := range store {
		km := v["km"]
		if utils.StrToFloat64(v["km"]) < 1 {
			v["km"] = utils.IntToStr(int(utils.StrToFloat64(v["km"])*1000)) + "m"
		} else {
			v["km"] = GetCommissionPrec(c, v["km"], "2", "1")
			v["km"] += "km"
		}
		if utils.StrToFloat64(km) <= 0 || utils.StrToFloat64(v["lat"]) == 0 || utils.StrToFloat64(v["lng"]) == 0 {
			v["km"] = "-"
		}
		label := make([]string, 0)
		tmp := map[string]interface{}{
			"lat":        v["lat"],
			"lng":        v["lng"],
			"address":    v["address"],
			"work_state": v["work_state"],
			"name":       v["name"],
			"id":         v["id"],
			"uid":        v["uid"],
			"km":         v["km"],
			"time_str":   v["timer"],
			"phone":      v["phone"],
			"label":      label,
			"is_like":    "0",
		}
		if user != nil {
			count, _ := MasterDb(c).Where("uid=? and store_id=?", user.Info.Uid, v["id"]).Count(&model.CommunityTeamStoreLike{})
			if count > 0 {
				tmp["is_like"] = "1"
			}
		}

		storeList = append(storeList, tmp)
	}
	e.OutSuc(c, storeList, nil)
	return
}
func GetStoreId(c *gin.Context) string {
	storeId := c.GetHeader("store_id")
	if utils.StrToInt(storeId) == 0 {
		storeId = c.GetHeader("storeId")
	}
	if utils.StrToInt(storeId) == 0 {
		storeId = c.GetHeader("storeid")
	}
	if utils.StrToInt(storeId) == 0 {
		storeId = c.GetHeader("StoreId")
	}
	return storeId
}
func Store(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	arg["store_type"] = "0"
	storeId := GetStoreId(c)
	if utils.StrToInt(storeId) > 0 {
		arg["store_id"] = storeId
		storeData := db.GetStoreIdEg(MasterDb(c), storeId)
		if storeData.StoreType == 0 {
			arg["store_id"] = "0"
		}
		arg["store_type"] = utils.IntToStr(storeData.StoreType)
	}
	user, _ := GetDefaultUser(c, c.GetHeader("Authorization"))
	store := db.GetStore(MasterDb(c), arg)
	storeList := make([]map[string]interface{}, 0)
	for _, v := range store {
		km := v["km"]
		if utils.StrToFloat64(v["km"]) < 1 {
			v["km"] = utils.IntToStr(int(utils.StrToFloat64(v["km"])*1000)) + "m"
		} else {
			v["km"] = GetCommissionPrec(c, v["km"], "2", "1")
			v["km"] += "km"
		}
		if utils.StrToFloat64(km) <= 0 || utils.StrToFloat64(v["lat"]) == 0 || utils.StrToFloat64(v["lng"]) == 0 {
			v["km"] = "-"
		}
		label := make([]string, 0)
		tmp := map[string]interface{}{
			"lat":        v["lat"],
			"lng":        v["lng"],
			"address":    v["address"],
			"work_state": v["work_state"],
			"name":       v["name"],
			"id":         v["id"],
			"uid":        v["uid"],
			"km":         v["km"],
			"time_str":   v["timer"],
			"phone":      v["phone"],
			"label":      label,
			"is_like":    "0",
		}
		if user != nil {
			count, _ := MasterDb(c).Where("uid=? and store_id=?", user.Info.Uid, v["id"]).Count(&model.CommunityTeamStoreLike{})
			if count > 0 {
				tmp["is_like"] = "1"
			}
		}

		storeList = append(storeList, tmp)
	}
	e.OutSuc(c, storeList, nil)
	return
}
func StoreAddLike(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 := GetUser(c)
	count, _ := MasterDb(c).Where("uid=? and store_id=?", user.Info.Uid, arg["id"]).Count(&model.CommunityTeamStoreLike{})
	if count > 0 {
		e.OutErr(c, 400, e.NewErr(400, "已收藏"))
		return
	}
	var data = model.CommunityTeamStoreLike{
		Uid:     user.Info.Uid,
		StoreId: utils.StrToInt(arg["id"]),
		Time:    time.Now(),
	}
	MasterDb(c).Insert(&data)
	store := db.GetStoreIdEg(MasterDb(c), arg["id"])
	store.Fan++
	MasterDb(c).Where("id=?", store.Id).Cols("fan").Update(store)
	e.OutSuc(c, "success", nil)
	return
}

func StoreCancelLike(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 := GetUser(c)
	MasterDb(c).Where("uid=? and store_id=?", user.Info.Uid, arg["id"]).Delete(&model.CommunityTeamStoreLike{})
	store := db.GetStoreIdEg(MasterDb(c), arg["id"])
	store.Fan--
	if store.Fan < 0 {
		store.Fan = 0
	}
	MasterDb(c).Where("id=?", store.Id).Cols("fan").Update(store)
	e.OutSuc(c, "success", nil)
	return
}
