package hdl

import (
	"applet/app/db"
	"applet/app/db/model"
	"applet/app/e"
	"applet/app/svc"
	"applet/app/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
	"time"
)

func City(c *gin.Context) {
	var arg = make(map[string]string)
	c.ShouldBindJSON(&arg)
	sql := `select IF(city.name='省直辖县级行政区划' or city.name='市辖区',province.name,city.name) as newname from city
LEFT JOIN province on province.id=city.province_id
where %s
order by CONVERT(newname USING gbk)`
	str := "1=1"
	if arg["name"] != "" {
		str += " and newname like '%" + arg["name"] + "%'"
	}
	sql = fmt.Sprintf(sql, str)
	nativeString, _ := db.QueryNativeString(svc.MasterDb(c), sql)
	nodeList := make([]map[string]string, 0)
	for _, item := range nativeString {
		tmp := map[string]string{
			"name": item["newname"],
		}
		nodeList = append(nodeList, tmp)
	}
	e.OutSuc(c, nodeList, nil)
	return
}
func BankStoreCate(c *gin.Context) {
	var res = []map[string]string{
		{"name": "全部网点", "value": ""},
		{"name": "附近网点", "value": "1"},
		{"name": "关注网点", "value": "2"},
	}
	e.OutSuc(c, res, nil)
	return
}
func BankStore(c *gin.Context) {
	svc.BankStore(c)
}
func Store(c *gin.Context) {
	svc.Store(c)
}
func StoreAddLike(c *gin.Context) {
	svc.StoreAddLike(c)
}
func StoreCancelLike(c *gin.Context) {
	svc.StoreCancelLike(c)
}
func User(c *gin.Context) {
	user, _ := svc.GetDefaultUser(c, c.GetHeader("Authorization"))
	res := map[string]string{
		"head_img":     "",
		"nickname":     "",
		"coupon_str":   "优惠券:",
		"coupon":       "0",
		"integral_str": "积分:",
		"integral":     "0",
	}
	if user != nil && user.Info.Uid > 0 {
		res["head_img"] = user.Profile.AvatarUrl
		res["nickname"] = user.Info.Nickname
		now := time.Now().Format("2006-01-02 15:04:05")
		count, _ := svc.MasterDb(c).Table("act_coupon_user").
			Where("store_type=? and uid = ? AND is_use = ? AND (valid_time_start < ? AND valid_time_end > ?)", 0,
				user.Info.Uid, 0, now, now).Count(&model.CommunityTeamCouponUser{})
		res["coupon"] = utils.Int64ToStr(count)
		mod, _ := db.SysModFindBySkipIdentifier(c, svc.MasterDb(c), "pub.flutter.community_team_store_index")
		if mod != nil {
			integralCoinId := gjson.Get(mod.Data, "integralCoinId").String()
			if utils.StrToInt(integralCoinId) > 0 {
				coin, _ := db.VirtualCoinGetOneById(svc.MasterDb(c), integralCoinId)
				if coin != nil {
					amount, _ := db.GetUserVirtualAmountOneEg(svc.MasterDb(c), user.Info.Uid, utils.StrToInt(integralCoinId))
					res["integral_str"] = coin.Name + ":"
					if amount != nil {
						res["integral"] = svc.GetCommissionPrec(c, amount.Amount, svc.SysCfgGet(c, "integral_prec"), "0")
					}
				}
			}
		}
	}
	e.OutSuc(c, res, nil)
	return
}
