package jxprint

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/jxprintapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
	"regexp"
	"strings"
)

var (
	CurPrinterHandler *PrinterHandler
	regexpPrint       = regexp.MustCompile(`\${.*?}`)
)

type PrinterHandler struct {
}

func init() {
	CurPrinterHandler = new(PrinterHandler)
	partner.RegisterPrinterPlatform(CurPrinterHandler)
}

func (c *PrinterHandler) GetVendorID() int {
	return model.VendorIDJxprint
}

func (c *PrinterHandler) PrintMsg(ctx *jxcontext.Context, printSn, orderSeq, msgTitle, msgContent string) (printerStatus *partner.PrinterStatus, err error) {
	if printSn != "" {
		printSn = strings.Split(printSn, "_")[0]
		if _, err = api.JxPrintAPI.DoPrint(printSn, msgContent, utils.Str2Int(orderSeq)); err == nil {
			return c.GetPrinterStatus(ctx, printSn, "")
		}
	}
	printerStatus = &partner.PrinterStatus{
		PrintResult: partner.PrintResultNoPrinter,
	}
	return printerStatus, err
}

func (c *PrinterHandler) GetPrinterStatus(ctx *jxcontext.Context, id1, id2 string) (printerStatus *partner.PrinterStatus, err error) {
	tmpStatus, err := api.JxPrintAPI.GetPrinterStatus(id1)
	if err == nil {
		printerStatus = &partner.PrinterStatus{
			PrinterStatus: int(tmpStatus),
			PrintResult:   partner.PrintResultSuccess,
		}
		return printerStatus, nil
		//printerStatus.Printed, printerStatus.Waiting, err = api.FeieAPI.QueryOrderInfoByDate(printerSN, time.Now())
	}
	return nil, err
}

func (c *PrinterHandler) RegisterPrinter(ctx *jxcontext.Context, id1, id2, printerName string, storeID int64) (newID1, newID2 string, err error) {
	if globals.EnableStoreWrite {
		err = api.JxPrintAPI.AddPrinter([]*jxprintapi.AddPrinterParam{
			&jxprintapi.AddPrinterParam{
				PrintNo: id1,         // 打印机编号
				Name:    printerName, // 门店名称
				SIM:     id2,         // printKey-指定验证用户号码
				StoreId: storeID,     // 门店id
			},
		})
	}
	return "", "", err
}

func (c *PrinterHandler) UnregisterPrinter(ctx *jxcontext.Context, id1, id2 string) (err error) {
	if globals.EnableStoreWrite {
		err = api.JxPrintAPI.DelPrinter([]string{id1}, id2)
	}
	return err
}

func (c *PrinterHandler) BindPrinter(ctx *jxcontext.Context, mapData map[string]interface{}) (bindResult *partner.BindPrinterResult, err error) {
	return nil, fmt.Errorf("%s打印机当前不支持扫码绑定", model.VendorChineseNames[model.VendorIDJxprint])
}

func (c *PrinterHandler) RebindPrinter(ctx *jxcontext.Context, lastBindResult *partner.BindPrinterResult) (bindResult *partner.BindPrinterResult, err error) {
	return nil, fmt.Errorf("%s打印机当前不支持扫码绑定", model.VendorChineseNames[model.VendorIDJxprint])
}

func (c *PrinterHandler) getOrderContent(order *model.GoodsOrder, storeTel string, storeDetail *dao.StoreDetail) (content string) {
	//	expectedDeliveryTime := order.ExpectedDeliveredTime
	//	if utils.IsTimeZero(expectedDeliveryTime) {
	//		expectedDeliveryTime = order.OrderCreatedAt.Add(1 * time.Hour)
	//	}
	//	orderParams := []interface{}{}
	//	getCode := ""
	//	if order.VendorID == model.VendorIDEBAI {
	//		getCode = fmt.Sprintf("<b>饿百取货码:%s</b><br><br>\n", jxutils.GetEbaiOrderGetCode(order))
	//	}
	//	orderFmt := ``
	//	if storeDetail != nil {
	//		if storeDetail.BrandIsPrint == model.NO {
	//			orderFmt += `
	//		<sound>您有新订单啦！</sound><br>
	//		<center><b>%s</b></center><br><br>
	//		`
	//			if order.VendorOrgCode == "34665" {
	//				orderParams = append(orderParams, globals.StoreNameEbai2)
	//			} else {
	//				orderParams = append(orderParams, storeDetail.BrandName)
	//			}
	//		}
	//	}
	//	orderFmt += `
	//<center>手机买菜上京西</center><br>
	//<center>极速到家送惊喜</center><br>
	//--------------------------------<br>
	//下单时间: %s<br>
	//预计送达: %s<br>
	//订单编号: %s<br>
	//<br>
	//
	//<b>%s#%d</b><br>
	//<qrc>%s</qrc><br>
	//` + getCode +
	//		`客户: %s<br>
	//电话: %s<br>
	//地址: %s<br>
	//<br>
	//客户备注: <br>
	//<b>%s</b><br>
	//<br>
	//
	//<br>
	//商品明细: <br>
	//品名    数量    单价       小计<br>
	//--------------------------------<br>`
	//	// <BOLD>实际支付:</BOLD>%s<BR>
	//	orderParams = append(orderParams,
	//		utils.Time2Str(order.OrderCreatedAt),
	//		utils.Time2Str(expectedDeliveryTime),
	//		order.VendorOrderID,
	//		jxutils.GetVendorName(order.VendorID),
	//		order.OrderSeq,
	//		order.VendorOrderID,
	//		order.ConsigneeName,
	//		order.ConsigneeMobile,
	//		order.ConsigneeAddress,
	//		order.BuyerComment,
	//		// jxutils.IntPrice2StandardCurrencyString(order.ActualPayPrice),
	//	)
	//
	//	for _, sku := range order.Skus {
	//		orderFmt += `%s<br>`
	//		orderFmt += `%8s%10s%10s<br>`
	//		orderParams = append(orderParams, sku.SkuName, "x"+utils.Int2Str(sku.Count), jxutils.IntPrice2StandardCurrencyString(sku.SalePrice), jxutils.IntPrice2StandardCurrencyString(sku.SalePrice*int64(sku.Count)))
	//	}
	//	orderFmt += `<br>
	//共%d种%d件商品
	//<br>
	//--------------------------------<br>
	//<center><hb>商品质量问题请联系:</hb></center><br>
	//<center><hb>%s:%s</hb></center><br>
	//<br>
	//更多信息请关注官方微信: %s<br>
	//<br>
	//<br>
	//--------------------------------<br>
	//--------------------------------<br>
	//<br>
	//`
	//	orderParams = append(orderParams, order.SkuCount, order.GoodsCount, order.StoreName, storeTel, "京西菜市")
	//	return fmt.Sprintf(strings.Replace(orderFmt, "\n", "", -1), orderParams...)
	return ""
}

func (c *PrinterHandler) getOrderContentByTemplate(order *model.GoodsOrder, storeTel string, storeDetail *dao.StoreDetail) (content string) {
	//orderFmt := ""
	//if storeDetail != nil {
	//	//开头加上语音
	//	if storeDetail.PrinterSound != "" {
	//		orderFmt += "<sound>" + storeDetail.PrinterSound + "</sound><br>"
	//	}
	//}
	////把带有${}的变量换成实际值
	//template := storeDetail.PrinterTemplate
	//regexpValues := regexpPrint.FindAllStringSubmatch(template, -1)
	//for _, v := range regexpValues {
	//	switch v[0] {
	//	case "${下单时间}":
	//		template = strings.ReplaceAll(template, v[0], utils.Time2Str(order.OrderCreatedAt))
	//	case "${预计送达}":
	//		expectedDeliveryTime := order.ExpectedDeliveredTime
	//		if utils.IsTimeZero(expectedDeliveryTime) {
	//			expectedDeliveryTime = order.OrderCreatedAt.Add(1 * time.Hour)
	//		}
	//		template = strings.ReplaceAll(template, v[0], utils.Time2Str(expectedDeliveryTime))
	//	case "${订单号}":
	//		template = strings.ReplaceAll(template, v[0], order.VendorOrderID)
	//	case "${平台名}":
	//		template = strings.ReplaceAll(template, v[0], jxutils.GetVendorName(order.VendorID))
	//	case "${订单序号}":
	//		template = strings.ReplaceAll(template, v[0], utils.Int2Str(order.OrderSeq))
	//	case "${客户名}":
	//		template = strings.ReplaceAll(template, v[0], order.ConsigneeName)
	//	case "${客户电话}":
	//		template = strings.ReplaceAll(template, v[0], order.ConsigneeMobile)
	//	case "${客户地址}":
	//		template = strings.ReplaceAll(template, v[0], order.ConsigneeAddress)
	//	case "${备注}":
	//		template = strings.ReplaceAll(template, v[0], order.BuyerComment)
	//	case "${商品种数}":
	//		template = strings.ReplaceAll(template, v[0], utils.Int2Str(order.SkuCount))
	//	case "${商品件数}":
	//		template = strings.ReplaceAll(template, v[0], utils.Int2Str(order.GoodsCount))
	//	case "${门店名}":
	//		template = strings.ReplaceAll(template, v[0], order.StoreName)
	//	case "${门店电话}":
	//		template = strings.ReplaceAll(template, v[0], storeTel)
	//	case "${商品明细}":
	//		skus := ""
	//		skuParams := []interface{}{}
	//		for i := 0; i < len(order.Skus); i++ {
	//			skus += "%s<br>"
	//			skus += "%8s%10s%10s<br><br>"
	//			skuParams = append(skuParams, order.Skus[i].SkuName)
	//			skuParams = append(skuParams, "x"+utils.Int2Str(order.Skus[i].Count))
	//			skuParams = append(skuParams, jxutils.IntPrice2StandardCurrencyString(order.Skus[i].SalePrice))
	//			skuParams = append(skuParams, jxutils.IntPrice2StandardCurrencyString(order.Skus[i].SalePrice*int64(order.Skus[i].Count)))
	//		}
	//		skus = fmt.Sprintf(skus, skuParams...)
	//		template = strings.ReplaceAll(template, v[0], skus)
	//	}
	//}
	//orderFmt += template
	//return strings.Replace(orderFmt, "\n", "", -1)
	return ""
}

func (c *PrinterHandler) PrintOrder(ctx *jxcontext.Context, store *model.Store, storeDetail *dao.StoreDetail, order *model.GoodsOrder, printType string, afs *model.AfsOrder) (printerStatus *partner.PrinterStatus, err error) {
	if len(order.Skus) == 0 {
		return
	}
	var printData = make(map[string]string, 0)
	switch printType {
	case "order": // 订单状态
		printData = ManagerOrderPrint(order, store.Tel1, storeDetail, printType, afs)
		printData[OrderStatus] = utils.Int2Str(order.Status)
	case "wayBill": // 运单状态
		printData = ManagerOrderPrint(order, store.Tel1, storeDetail, printType, afs)
		printData[WayBillStatus] = order.VendorStatus
	case "store": // 门店状态
		printData[StoreStatus] = utils.Int2Str(store.Status)
	case "enter": // 催单
		printData[ReminderStatus] = "1"
	case "afs": // 售后
		printData = ManagerOrderPrint(order, store.Tel1, storeDetail, printType, afs)
		printData[OrderStatus] = utils.Int2Str(afs.Status)
	}
	printData[AppID] = "1000" // 菜市应用
	if printData[VendorID] == utils.Int2Str(model.VendorIDEBAI) && (printData[OrderStatus] == utils.Int2Str(model.OrderStatusFinishedPickup) || printData[OrderStatus] == utils.Int2Str(model.OrderStatusWaitAccepted)) {
		printData[OrderStatus] = utils.Int2Str(model.OrderStatusNew)
	}
	orderPrint, err := json.Marshal(printData)
	if err != nil {
		return nil, err
	}
	orderSeq := utils.Int2Str(order.VendorID) + utils.Int2Str(order.OrderSeq)
	return c.PrintMsg(ctx, store.PrinterSN, orderSeq, "", string(orderPrint))
}

func (c *PrinterHandler) PrintCancelOrRefundOrder(ctx *jxcontext.Context, printType int, store *model.Store, storeDetail *dao.StoreDetail, order *model.GoodsOrder) (printerStatus *partner.PrinterStatus, err error) {
	order2 := order
	order2.Status = model.OrderStatusCanceled
	return c.PrintOrder(ctx, store, storeDetail, order, "order", nil)
}

// PrintStore 打印门店
func (c *PrinterHandler) PrintStore(ctx *jxcontext.Context, store *model.Store, storeDetail *dao.StoreDetail, vendorCode int) (printerStatus *partner.PrinterStatus, err error) {
	data := make(map[string]interface{}, 0)
	data[StoreStatus] = utils.Int2Str(store.Status)
	data[StoreName] = storeDetail.VendorStoreName
	data[VendorName] = model.VendorChineseNames[vendorCode]
	orderPrint, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}

	return c.PrintMsg(ctx, store.PrinterSN, "99999", "", string(orderPrint))
}

func (c *PrinterHandler) EmptyPrintList(ctx *jxcontext.Context, id1, id2 string) (err error) {
	if globals.EnableStoreWrite {
		err = api.JxPrintAPI.DelPrinterSeq(id1)
	}
	return err
}

func (c *PrinterHandler) PlayText(ctx *jxcontext.Context, id1, id2, orderID, text string) (printerStatus *partner.PrinterStatus, err error) {
	return nil, err
}

func (c *PrinterHandler) SetSound(ctx *jxcontext.Context, id1, id2, sound string) (err error) {
	if globals.EnableStoreWrite {
		err = api.JxPrintAPI.UpdatePrinter(&jxprintapi.UpdatePrinterParam{
			PrintNo: id1,
			Volume:  utils.Str2Int(sound),
		})
	}
	return err
}

func GetPrintList(printNo, printKey string, status, isOnline int, page, size int) ([]*jxprintapi.PrintList, int64, error) {
	return api.JxPrintAPI.GetPrintList(printNo, printKey, status, isOnline, page, size)
}
