package hdl

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

func StoreOrderList(c *gin.Context) {
	svc.StoreOrderList(c)
}
func StoreOrderCate(c *gin.Context) {
	svc.StoreOrderCate(c)
}
func StoreOrderDetail(c *gin.Context) {
	svc.StoreOrderDetail(c)
}
func StoreOrderConfirm(c *gin.Context) {
	svc.StoreOrderConfirm(c)
}
func GetNewOrderNoticeList(c *gin.Context) {
	user := svc.GetUser(c)
	storeId := user.Info.Uid
	payTipOpen := db.SysCfgGet(c, "community_pay_tip_open")
	list := make([]string, 0)

	if payTipOpen == "1" {
		today := utils.GetTimeRange("today")
		todayTime := time.Unix(today["start"], 0).Format("2006-01-02 15:04:05")
		sql2 := `select * from community_team_pay_order where is_notice=0 and store_uid=? and state>0 and create_at>=? order by create_at asc`
		nativeString2, _ := db.QueryNativeString(svc.MasterDb(c), sql2, storeId, todayTime)
		payCodeTip := db.SysCfgGet(c, "community_pay_code_tip")
		payGoodsTip := db.SysCfgGet(c, "community_pay_goods_tip")
		payGoodsSecondTip := db.SysCfgGet(c, "community_pay_goods_second_tip")
		payGoodsTipType := db.SysCfgGet(c, "community_pay_goods_tip_type")
		for _, v := range nativeString2 {
			payCodeTipStr := strings.ReplaceAll(payCodeTip, "[金额]", svc.GetCommissionPrec(c, v["amount"], "2", "1"))
			list = append(list, payCodeTipStr)
			svc.MasterDb(c).Where("id=? ", v["id"]).Cols("is_notice").Update(&model.CommunityTeamPayOrder{IsNotice: 1})
		}
		sql := `select * from community_team_order where is_notice=0 and store_uid=? and state in(1,2)  and pay_at>=?  order by pay_at asc`
		nativeString, _ := db.QueryNativeString(svc.MasterDb(c), sql, storeId, todayTime)
		mainStr := payGoodsTip
		if payGoodsTipType == "1" {
			mainStr = payGoodsSecondTip
		}
		for k, v := range nativeString {
			sql1 := `select title,num,sku_info from community_team_order_info
	where oid=?
`
			queryNativeString, _ := db.QueryNativeString(svc.MasterDb(c), sql1, v["oid"])
			str := ""
			for _, v1 := range queryNativeString {
				tmp := make([]map[string]interface{}, 0)
				json.Unmarshal([]byte(v["sku_info"]), &tmp)
				skuStr := ""
				for _, v2 := range tmp {
					skuStr += utils.AnyToString(v2["value"])
				}
				str += " " + v1["title"] + skuStr + v1["num"] + " 份"
			}
			if payGoodsTipType == "1" {
				list = append(list, mainStr+str)
			}
			if payGoodsTipType != "1" && k == 0 {
				list = append(list, mainStr)
			}
			svc.MasterDb(c).Where("oid=? ", v["oid"]).Cols("is_notice").Update(&model.CommunityTeamOrder{IsNotice: 1})
		}

	}
	res := map[string]interface{}{
		"list": list,
	}
	e.OutSuc(c, res, nil)
	return
}
