package svc

import (
	"applet/app/db"
	"applet/app/db/model"
	"applet/app/md"
	"applet/app/utils"
	"applet/app/utils/logx"
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
	"xorm.io/xorm"
)

// 替换
func ReplaceOne(c *gin.Context, args *md.PrinterRequest) {
	eg := MasterDb(c)
	printerOne, _ := db.GetPrinterIndexById(eg, args.PrinterId, args.StoreId)
	if printerOne.Type == "bluetooth" {
		return
	}
	module, _ := db.GetAllPrinterModuleListByModuleIdOne(eg, printerOne.ModuleId)
	ReplaceStr(c, eg, args, printerOne, module.Content)
}

func GetReplaceContent(c *gin.Context, args *md.PrinterRequest) string {
	eg := MasterDb(c)
	printerOne, _ := db.GetPrinterIndexByBluetooth(eg, args.StoreId)
	if printerOne == nil {
		return ""
	}
	module, _ := db.GetAllPrinterModuleListByModuleIdOne(eg, printerOne.ModuleId)
	content := GetCommContent(args, printerOne, module.Content)
	return content
}

// 替换
func ReplaceMore(c *gin.Context, args *md.PrinterRequest) {
	eg := MasterDb(c)
	fmt.Println(args)

	//查出这个店铺下的所有打印机
	list, err := db.GetPrinterIndexAll(eg, args.StoreId)
	if err != nil {
		logx.Info(err)
		return
	}
	//循环拿出模板id
	var moduleIds = make([]int, 0)
	for _, v := range list {
		if v.IsUse == 0 || v.Type == "bluetooth" || (args.Ord["order_type"] == "face_to_pay" && v.LocationType != "reception") {
			continue
		}
		if v.ModuleId > 0 {
			moduleIds = append(moduleIds, v.ModuleId)
		}
	}
	if moduleIds == nil || len(moduleIds) == 0 {
		return
	}
	//查出对应模板数据
	moduleList, err := db.GetAllPrinterModuleListByModuleId(eg, moduleIds)
	if err != nil {
		logx.Info(err)
		return
	}
	moduleArr := make(map[int]model.CommunityTeamStorePrinterModule, 0)
	for _, v := range moduleList {
		moduleArr[v.Id] = v
	}
	//处理数据内容
	for _, v := range list {
		if v.IsUse == 0 {
			continue
		}
		moduleId := v.ModuleId
		moduleData := moduleArr[moduleId]
		if moduleData.Content == "" {
			continue
		}
		content := moduleData.Content
		ReplaceStr(c, eg, args, &v, content)
	}
}
func GetCommContent(arg *md.PrinterRequest, list *model.CommunityTeamStorePrinter, content string) string {
	goodsInfoStr := ReplaceGoodsInfo(arg.GoodsInfo, list.Type, 15, 22, 26, 32)
	content = strings.ReplaceAll(content, "{商品信息}", goodsInfoStr)
	content = strings.ReplaceAll(content, "{付款金额}", arg.Ord["payment"])
	content = strings.ReplaceAll(content, "{取餐号}", arg.Ord["num"])
	content = strings.ReplaceAll(content, "{桌号}", arg.Ord["table_num"])
	content = strings.ReplaceAll(content, "{订单号}", arg.Ord["main_ord_id"])
	content = strings.ReplaceAll(content, "{姓名}", arg.Ord["name"])
	content = strings.ReplaceAll(content, "{电话}", arg.Ord["phone"])
	content = strings.ReplaceAll(content, "{打印时间}", time.Now().Format("2006-01-02 15:04:05"))
	content = strings.ReplaceAll(content, "{收货地址}", arg.Ord["address"])
	content = strings.ReplaceAll(content, "{二维码链接}", arg.Ord["qrcode_url"])
	content = strings.ReplaceAll(content, "{二维码标签左}", "<QR>")
	content = strings.ReplaceAll(content, "{二维码标签右}", "</QR>")

	content = strings.ReplaceAll(content, "{商家名称}", arg.Ord["store_name"])
	content = strings.ReplaceAll(content, "{商家店铺首页二维码链接}", arg.Ord["store_qrcode_url"])

	if list.Type == "cloud" {
		content = strings.ReplaceAll(content, "{居中放大左}", "<FS><center>")
		content = strings.ReplaceAll(content, "{居中放大右}", "</center></FS>")
	} else {
		content = strings.ReplaceAll(content, "{居中放大左}", "<CB>")
		content = strings.ReplaceAll(content, "{居中放大右}", "</CB>")
		content = strings.ReplaceAll(content, "\n", "<BR>")
		content = strings.ReplaceAll(content, "\\n", "<BR>")
	}
	return content
}

// 字符替换
func ReplaceStr(c *gin.Context, eg *xorm.Engine, arg *md.PrinterRequest, list *model.CommunityTeamStorePrinter, content string) {
	content = GetCommContent(arg, list, content)
	fmt.Println(content)
	if arg.Ord["order_type"] == "face_to_pay" {
		arg.Ord["order_type"] = "3"
	}
	//加入打印明细
	var detailData = model.CommunityTeamStorePrinterDetail{
		OrdId:           arg.Ord["main_ord_id"],
		OrdType:         utils.StrToInt(arg.Ord["order_type"]),
		PrinterId:       list.Id,
		PrinterModuleId: list.ModuleId,
		PrintContent:    content,
		StoreId:         utils.StrToInt(arg.StoreId),
		CreateTime:      time.Now(),
		UpdateTime:      time.Now(),
	}
	has, err := db.DetailInsert(eg, &detailData)
	if has == 0 || err != nil {
		return
	}
	fmt.Println(detailData.Id)
	//调用打印机打印
	oids := fmt.Sprintf("%s%d%d", detailData.OrdId, detailData.PrinterId, detailData.CreateTime.Unix())
	oid, msg := CommDoing(c, content, list.SnNum, list.Type, oids)
	if msg != "" {
		return
	}
	detailData.State = 1
	if msg != "" {
		logx.Info(msg)
		detailData.State = 2
		detailData.FailMsg = msg
	} else {
		detailData.PrinterOid = oid
	}
	detailData.PrintTime = time.Now()
	detailData.UpdateTime = time.Now()
	_, err = db.DetailUpdate(eg, detailData.Id, &detailData, "printer_oid,print_time,update_time,state,fail_msg")
	logx.Info(err)
}

// 处理商品信息
func ReplaceGoodsInfo(goodsInfo []map[string]string, printerType string, nameLen, priceLen, numLen, pricesLen int) string {
	goodsInfoStr := ""
	var sub = []int{0, nameLen, priceLen, numLen, pricesLen}
	for _, v := range goodsInfo {
		name := v["name"]
		skuText := v["sku_text"]
		price := v["price"]
		num := v["num"]
		prices := v["prices"]
		goodsInfoStr += CheckStr(name, 0, sub)
		goodsInfoStr += CheckStr(price, 1, sub)
		goodsInfoStr += CheckStr(num, 2, sub)
		goodsInfoStr += CheckStr(prices, 3, sub)
		if printerType == "cloud" {
			goodsInfoStr += "\n"
		} else {
			goodsInfoStr += "<BR>"
		}
		if skuText != "" {
			goodsInfoStr += CheckStr(skuText, 0, sub)
			if printerType == "cloud" {
				goodsInfoStr += "\n"
			} else {
				goodsInfoStr += "<BR>"
			}
		}

	}
	return goodsInfoStr
}
func CheckStr(str string, index int, sub []int) string {
	kw := ""
	lens := len(str)
	if lens > 15 && index == 0 {
		if lens > 15 && lens <= 32 {
			kw += str
			for i := 0; i < 32-lens; i++ {
				kw += " "
			}
			kw += "<BR>"
			for i := 0; i < 15; i++ {
				kw += " "
			}
		}
		if lens > 32 {
			if lens > 16*4 {
				lens = 16 * 4
			}
			kw += str[0:lens]
			kw += "<BR>"
			str2 := str[lens:]
			str2Len := len(str2)
			kw += str2
			key := sub[index+1] - str2Len - sub[index]
			for i := 0; i < key; i++ {
				kw += " "
			}
		}
	} else {
		kw += str
		key := sub[index+1] - lens - sub[index]
		if index == 0 {
			key = 20 - lens
			if lens < 15 {
				key = 19 - lens
			}
			if lens < 10 {
				key = 18 - lens
			}
			if lens < 7 {
				key = 17 - lens
			}
			fmt.Println(lens)
			fmt.Println(key)
		}
		for i := 0; i < key; i++ {
			kw += " "
		}
	}
	return kw
}
