package xiaowm

import (
	"fmt"
	"strings"
	"time"

	"git.rosy.net.cn/jx-callback/business/model/dao"

	"git.rosy.net.cn/baseapi/platformapi/xiaowmapi"

	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
)

var (
	CurPrinterHandler *PrinterHandler
)

type PrinterHandler struct {
}

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

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)
	}
	getCode := ""
	if order.VendorID == model.VendorIDEBAI {
		getCode = fmt.Sprintf("<big>淘宝闪购取货码:%s**\n", jxutils.GetEbaiOrderGetCode(order))
	}
	buyerComment := order.BuyerComment
	if buyerComment == "" {
		buyerComment = " "
	}
	orderFmt := `
<big>    %s**
         手机买菜上京西*
         极速到家送惊喜*`
	if order.BusinessType == model.BusinessTypeDingshida {
		orderFmt += `<big>    预订单*`
	} else {
		orderFmt += `<big>    立即送达*`
	}
	orderFmt += `------------------------------*
下单时间: %s*
预计送达: %s*
订单编号: %s*
*
<big>%s\#%d**
<qrcA4>%s*
` + getCode +
		`客户: %s*
电话: %s*
地址: %s*
*
客户备注: *
<big>%s*
商品明细: *
`
	orderFmt += `品名            数量         
--------------------------------*
`
	//	pricePoints := `品名   数量    单价         小计
	//--------------------------------*
	//`
	// <S011>实际支付: %s*
	orderParams := []interface{}{
		globals.StoreName,
		utils.Time2Str(order.OrderCreatedAt),
		utils.Time2Str(expectedDeliveryTime),
		order.VendorOrderID,
		jxutils.GetVendorName(order.VendorID),
		order.OrderSeq,
		order.VendorOrderID,
		order.ConsigneeName,
		order.ConsigneeMobile,
		order.ConsigneeAddress,
		buyerComment,
		// jxutils.IntPrice2StandardCurrencyString(order.ActualPayPrice),
	}
	//switch order.EarningType {
	//case model.EarningTypePoints: // 扣点
	//	orderFmt += pricePoints
	//case model.EarningTypeQuote: // 报价
	//	orderFmt += priceQuote
	//}
	for _, sku := range order.Skus {
		orderFmt += `%s %25s*`
		orderParams = append(orderParams, sku.SkuName, "x"+utils.Int2Str(sku.Count))
		//switch order.EarningType {
		//case model.EarningTypePoints: // 扣点
		//	orderFmt += `%s*`
		//	orderFmt += `%8s%10s%10s*`
		//	orderParams = append(orderParams, sku.SkuName, "x"+utils.Int2Str(sku.Count), jxutils.IntPrice2StandardCurrencyString(sku.VendorPrice), jxutils.IntPrice2StandardCurrencyString(sku.VendorPrice*int64(sku.Count)))
		//case model.EarningTypeQuote: // 报价
		//	orderFmt += `%s %25s*`
		//	orderParams = append(orderParams, sku.SkuName, "x"+utils.Int2Str(sku.Count))
		//}

	}
	orderFmt += `
*
<S011>共%d种%d件商品*
--------------------------------*
<S020>商品质量问题请联系:*
<S020>%s:%s*
*
更多信息请关注官方微信: %s*
--------------------------------
--------------------------------
*<BEEP13500,3,2,1>*
`
	// <QR>http://weixin.qq.com/r/tkkDGzTERmk5rXB49xyk</QR>
	orderParams = append(orderParams, order.SkuCount, order.GoodsCount, order.StoreName, storeTel, globals.StoreName)
	content = fmt.Sprintf(strings.Replace(orderFmt, "\n", "", -1), escapeString4Printer(orderParams)...)
	return content
}

func (c *PrinterHandler) getOrderContentBig(order *model.GoodsOrder, storeTel string, storeDetail *dao.StoreDetail) (content string) {
	expectedDeliveryTime := order.ExpectedDeliveredTime
	if utils.IsTimeZero(expectedDeliveryTime) {
		expectedDeliveryTime = order.OrderCreatedAt.Add(1 * time.Hour)
	}
	getCode := ""
	if order.VendorID == model.VendorIDEBAI {
		getCode = fmt.Sprintf("<big>淘宝闪购取货码:%s**\n", jxutils.GetEbaiOrderGetCode(order))
	}
	buyerComment := order.BuyerComment
	if buyerComment == "" {
		buyerComment = " "
	}
	orderFmt := `
<big>    %s**
         手机买菜上京西*
         极速到家送惊喜*`
	if order.BusinessType == model.BusinessTypeDingshida {
		orderFmt += `<big>    预订单*`
	} else {
		orderFmt += `<big>    立即送达*`
	}
	orderFmt += `------------------------------*
<big>下单时间: %s**
<big>预计送达: %s**
<big>订单编号: %s*
*
<big>%s\#%d*
<qrcA4>%s*
` + getCode +
		`<big>客户: %s*
<big>电话: %s*
<big>地址: %s*
*
<big>客户备注: *
<big>%s*
<big>商品明细: *
<big>品名数量单价小计*
--------------------------------*
`
	// <big>实际支付: %s*
	orderParams := []interface{}{
		globals.StoreName,
		utils.Time2Str(order.OrderCreatedAt),
		utils.Time2Str(expectedDeliveryTime),
		order.VendorOrderID,
		jxutils.GetVendorName(order.VendorID),
		order.OrderSeq,
		order.VendorOrderID,
		order.ConsigneeName,
		order.ConsigneeMobile,
		order.ConsigneeAddress,
		buyerComment,
		// jxutils.IntPrice2StandardCurrencyString(order.ActualPayPrice),
	}
	for _, sku := range order.Skus {
		switch order.EarningType {
		case model.EarningTypePoints: // 扣点
			orderFmt += `<big>%s*`
			orderFmt += `<big>%s %s %s*`
			orderParams = append(orderParams, sku.SkuName, "x"+utils.Int2Str(sku.Count), jxutils.IntPrice2StandardCurrencyString(sku.VendorPrice), jxutils.IntPrice2StandardCurrencyString(sku.VendorPrice*int64(sku.Count)))
		case model.EarningTypeQuote: // 报价
			orderFmt += `<big>%s    %s*`
			orderParams = append(orderParams, sku.SkuName, "x"+utils.Int2Str(sku.Count))
		}
	}
	orderFmt += `
<big>共%d种%d件商品*
--------------------------------*
<S020>商品质量问题请联系:*
<S020>%s:%s*
*
<big>更多信息请关注官方微信: %s*
--------------------------------
--------------------------------
*<BEEP13500,3,2,1>*
`
	// <QR>http://weixin.qq.com/r/tkkDGzTERmk5rXB49xyk</QR>
	orderParams = append(orderParams, order.SkuCount, order.GoodsCount, order.StoreName, storeTel, globals.StoreName)
	content = fmt.Sprintf(strings.Replace(orderFmt, "\n", "", -1), escapeString4Printer(orderParams)...)
	return content
}

func (c *PrinterHandler) getOrderContent2(order *model.GoodsOrder, storeTel string) (content string) {
	expectedDeliveryTime := order.ExpectedDeliveredTime
	if utils.IsTimeZero(expectedDeliveryTime) {
		expectedDeliveryTime = order.OrderCreatedAt.Add(1 * time.Hour)
	}
	getCode := ""
	if order.VendorID == model.VendorIDEBAI {
		getCode = fmt.Sprintf("|7淘宝闪购取货码:%s\n\n", jxutils.GetEbaiOrderGetCode(order))
	}
	buyerComment := order.BuyerComment
	if buyerComment == "" {
		buyerComment = " "
	}
	orderFmt := `
|7    %s
|5       手机买菜上京西
|5       极速到家送惊喜`
	if order.BusinessType == model.BusinessTypeDingshida {
		orderFmt += `|5       预订单`
	} else {
		orderFmt += `|5       立即送达`
	}
	orderFmt += `|5--------------------------------
|5下单时间: %s
|5预计送达: %s
|5订单编号: %s
|5
|7%s\#%d
` + getCode + `|5
|2%s
|5客户: %s
|5电话: %s
|5地址: %s
|5
|5客户备注:
|7%s
|5
|5
|5商品明细:
|5品名   数量             
|5--------------------------------
`
	// |6实际支付: %s
	orderParams := []interface{}{
		globals.StoreName,
		utils.Time2Str(order.OrderCreatedAt),
		utils.Time2Str(expectedDeliveryTime),
		order.VendorOrderID,
		jxutils.GetVendorName(order.VendorID),
		order.OrderSeq,
		order.VendorOrderID,
		order.ConsigneeName,
		order.ConsigneeMobile,
		order.ConsigneeAddress,
		buyerComment,
		// jxutils.IntPrice2StandardCurrencyString(order.ActualPayPrice),
	}
	for _, sku := range order.Skus {
		orderFmt += `|5%s`
		orderFmt += `|5%8s`
		orderParams = append(orderParams, sku.SkuName, "x"+utils.Int2Str(sku.Count))
		// jxutils.IntPrice2StandardCurrencyString(sku.SalePrice), jxutils.IntPrice2StandardCurrencyString(sku.SalePrice*int64(sku.Count))
	}
	orderFmt += `
|5
|6共%d种%d件商品
|5--------------------------------
|5商品质量问题请联系:
|5%s:%s
|5
|5更多信息请关注官方微信: %s
|5--------------------------------
|5--------------------------------
`
	orderParams = append(orderParams, order.SkuCount, order.GoodsCount, order.StoreName, storeTel, globals.StoreName)
	return fmt.Sprintf(orderFmt, escapeString4Printer(orderParams)...)
}

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

func (c *PrinterHandler) PrintMsg(ctx *jxcontext.Context, printerNumber, printerToken, msgTitle, msgContent string) (printerStatus *partner.PrinterStatus, err error) {
	if printerNumber != "" {
		if globals.EnableStoreWrite {
			_, err = api.XiaoWMAPI.SendMsg(printerNumber, printerToken, msgContent)
		}
		if err == nil {
			printerStatus, err = c.GetPrinterStatus(ctx, printerNumber, printerToken)
		}
	} else {
		printerStatus = &partner.PrinterStatus{
			PrintResult: partner.PrintResultNoPrinter,
		}
	}
	return printerStatus, err
}

func (c *PrinterHandler) GetPrinterStatus(ctx *jxcontext.Context, printerNumber, printerToken string) (printerStatus *partner.PrinterStatus, err error) {
	runningState, paperState, err := api.XiaoWMAPI.GetPrinterStatus(printerNumber, printerToken)
	if err == nil {
		printerStatus = &partner.PrinterStatus{
			PrintResult: partner.PrintResultSuccess,
		}
		if runningState == xiaowmapi.RunningStateOffline {
			printerStatus.PrinterStatus = partner.PrinterStatusOffline
		} else {
			if paperState == xiaowmapi.PaperStateLackPaper {
				printerStatus.PrinterStatus = partner.PrinterStatusOnlineAbnormal
			} else {
				printerStatus.PrinterStatus = partner.PrinterStatusOnlineOK
			}
		}
	}
	return printerStatus, err
}

func (c *PrinterHandler) PrintOrder(ctx *jxcontext.Context, store *model.Store, storeDetail *dao.StoreDetail, order *model.GoodsOrder, printType string, asfOrder *model.AfsOrder) (printerStatus *partner.PrinterStatus, err error) {
	var content string
	if isV500(store.PrinterSN) {
		content = c.getOrderContent2(order, store.Tel1)
	} else {
		if store.PrinterFontSize == partner.PrinterFontSizeBig {
			content = c.getOrderContentBig(order, store.Tel1, storeDetail)
		} else {
			content = c.getOrderContent(order, store.Tel1, storeDetail)
		}
	}
	return c.PrintMsg(ctx, store.PrinterSN, store.PrinterKey, order.VendorOrderID, content)
}

func (c *PrinterHandler) PrintStore(ctx *jxcontext.Context, store *model.Store, storeDetail *dao.StoreDetail, vendorId int) (printerStatus *partner.PrinterStatus, err error) {
	return nil, err
}

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

func isV500(printerNo string) bool {
	printerNoNum := utils.Str2Int64WithDefault("1"+printerNo, 0)
	return printerNoNum > 1000000000
}

func (c *PrinterHandler) RegisterPrinter(ctx *jxcontext.Context, printerNumber, notUsed, printerName string, storeID int64) (newID1, printerToken string, err error) {
	if printerNumber == "" { //len(printerNumber) != len("7JizmSyiXNzkggaqU") {
		err = fmt.Errorf("外卖管家打印机设备编号:%s长度不合法", printerNumber)
	} else {
		if globals.EnableStoreWrite {
			printerToken, err = api.XiaoWMAPI.AuthPrinter(printerNumber, "", "")
		}
		if err == nil {
			if _, err = c.GetPrinterStatus(ctx, printerNumber, printerToken); err != nil {
				if globals.EnableStoreWrite {
					c.UnregisterPrinter(ctx, printerNumber, printerToken)
				}
			}
		}
	}
	return "", printerToken, err
}

func (c *PrinterHandler) UnregisterPrinter(ctx *jxcontext.Context, printerNumber, printerToken string) (err error) {
	if globals.EnableStoreWrite {
		err = api.XiaoWMAPI.DelPrinter(printerNumber, printerToken)
	}
	return err
}

func escapeString4Printer(params []interface{}) []interface{} {
	for k, v := range params {
		if vStr, ok := v.(string); ok {
			vStr = strings.Replace(vStr, "*", "\\*", -1)
			params[k] = strings.Replace(vStr, "#", "\\#", -1)
		}
	}
	return params
}

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

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

func (c *PrinterHandler) EmptyPrintList(ctx *jxcontext.Context, id1, id2 string) (err error) {
	return err
}

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

func (c *PrinterHandler) SetSound(ctx *jxcontext.Context, id1, id2, sound string) (err error) {
	return fmt.Errorf("%s打印机当前不支持设置声音", model.VendorChineseNames[model.VendorIDXiaoWM])
}
