package zhongwu

import (
	"fmt"
	"strings"
	"time"

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

	"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/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"
)

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("<S2>淘宝闪购取货码:%s</S2><RN>\n", jxutils.GetEbaiOrderGetCode(order))
	}
	var orderParams []interface{}
	orderFmt := ``
	if storeDetail != nil {
		if storeDetail.BrandIsPrint == model.NO {
			orderFmt += `
		<S2><C>%s</C></S2><RN><RN>
		`
			if order.VendorOrgCode == "34665" {
				orderParams = append(orderParams, globals.StoreNameEbai2)
			} else {
				orderParams = append(orderParams, storeDetail.BrandName)
			}
		}
	}
	orderFmt += `
<C>手机买菜上京西</C>
<C>极速到家送惊喜</C><RN>`
	if order.BusinessType == model.BusinessTypeDingshida {
		orderFmt += `<C>预订单</C><RN>`
	} else {
		orderFmt += `<C>立即送达</C><RN>`
	}
	orderFmt += `********************************
下单时间: %s<RN>
预计送达: %s<RN>
订单编号: %s<RN>
<RN>
<S2>%s#%d</S2><RN><RN>
<QR>%s</QR>
` + getCode + `<RN>
客户: %s<RN>
电话: %s<RN>
地址: %s<RN>
<RN>
客户备注: <RN>
<S2>%s</S2><RN>
<RN>
<RN>
商品明细: <RN>
品名    数量  <RN>
********************************<RN>`
	// <B1>实际支付:</B1>%s<RN>
	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  <R>%s</R><RN>`
		orderParams = append(orderParams, sku.SkuName, "x"+utils.Int2Str(sku.Count))
		//jxutils.IntPrice2StandardCurrencyString(sku.SalePrice), jxutils.IntPrice2StandardCurrencyString(sku.SalePrice*int64(sku.Count))
	}
	orderFmt += `<RN>
<B1>共%d种%d件商品</B1>
<RN>
********************************<RN>
<C><B1>商品质量问题请联系:</B1></C>
<C><B1>%s:%s</B1></C><RN>
更多信息请关注官方微信: %s<RN>
********************************<RN>
********************************<RN>
`
	// <QR>http://weixin.qq.com/r/tkkDGzTERmk5rXB49xyk</QR>
	orderParams = append(orderParams, order.SkuCount, order.GoodsCount, order.StoreName, storeTel, globals.StoreName)
	return fmt.Sprintf(strings.Replace(orderFmt, "\n", "", -1), orderParams...)
}

//退货/取消订单 正常尺寸模板
func (c *PrinterHandler) getCancelOrRefundOrderContent(order *model.GoodsOrder, printType int, storeDetail *dao.StoreDetail) (content string) {
	orderParams := []interface{}{}
	orderFmt := ``
	if storeDetail.BrandIsPrint == model.NO {
		orderFmt += `
		<S2><C>%s</C></S2><RN><RN>
		`
		if order.VendorOrgCode == "34665" {
			orderParams = append(orderParams, globals.StoreNameEbai2)
		} else {
			orderParams = append(orderParams, storeDetail.BrandName)
		}
	}

	if printType == model.YES { // 取消订单
		orderFmt = `<C>取消订单详情</C><RN>`
	} else { // 售后订单
		orderFmt = `<C>售后清淡详情</C><RN>`
	}

	orderFmt += `********************************
<S2>下单时间: %s<RN><RN></S2>
<S2>订单编号: %s<RN></S2>
<RN>
<S2>%s#%d</S2><RN><RN>
<S2><B1>共%d种%d件商品</B1></S2>
<RN>`

	orderParams = append(orderParams,
		utils.Time2Str(order.OrderCreatedAt),
		order.VendorOrderID,
		jxutils.GetVendorName(order.VendorID),
		order.OrderSeq,
	)
	orderParams = append(orderParams, order.SkuCount, order.GoodsCount)
	return fmt.Sprintf(strings.Replace(orderFmt, "\n", "", -1), orderParams...)
}

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("<S2>淘宝闪购取货码:%s</S2><RN>\n", jxutils.GetEbaiOrderGetCode(order))
	}
	orderParams := []interface{}{}
	orderFmt := ``
	if storeDetail.BrandIsPrint == model.NO {
		orderFmt += `
		<S2><C>%s</C></S2><RN><RN>
		`
		if order.VendorOrgCode == "34665" {
			orderParams = append(orderParams, globals.StoreNameEbai2)
		} else {
			orderParams = append(orderParams, storeDetail.BrandName)
		}
	}
	orderFmt += `
<C>手机买菜上京西</C>
<C>极速到家送惊喜</C><RN>`
	if order.BusinessType == model.BusinessTypeDingshida {
		orderFmt += `<C>预订单</C><RN>`
	} else {
		orderFmt += `<C>立即送达</C><RN>`
	}
	orderFmt += `********************************
<S2>下单时间: %s<RN><RN></S2>
<S2>预计送达: %s<RN><RN></S2>
<S2>订单编号: %s<RN></S2>
<RN>
<S2>%s#%d</S2><RN><RN>
<QR>%s</QR>
` + getCode + `<RN>
<S2>客户: %s<RN></S2>
<S2>电话: %s<RN></S2>
<S2>地址: %s<RN></S2>
<RN>
<S2>客户备注: <RN></S2>
<S2>%s</S2><RN>
<RN>
<RN>
<S2>商品明细: <RN></S2>
<S2>品名 数量<RN></S2>
********************************<RN>`
	// <S2><B1>实际支付:</B1>%s<RN></S2>
	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 += `<S2>%s  <R>%s</R></S2><RN>`
		orderParams = append(orderParams, sku.SkuName, "x"+utils.Int2Str(sku.Count))
		//jxutils.IntPrice2StandardCurrencyString(sku.SalePrice), jxutils.IntPrice2StandardCurrencyString(sku.SalePrice*int64(sku.Count))
	}
	orderFmt += `<RN>
<S2><B1>共%d种%d件商品</B1></S2>
<RN>
********************************<RN>
<C><B1>商品质量问题请联系:</B1></C>
<C><B1>%s:%s</B1></C><RN>
<B1>更多信息请关注官方微信: %s<RN></B1>
********************************<RN>
********************************<RN>
`
	// <QR>http://weixin.qq.com/r/tkkDGzTERmk5rXB49xyk</QR>
	orderParams = append(orderParams, order.SkuCount, order.GoodsCount, order.StoreName, storeTel, globals.StoreName)
	return fmt.Sprintf(strings.Replace(orderFmt, "\n", "", -1), orderParams...)
}

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

func (c *PrinterHandler) PrintMsg(ctx *jxcontext.Context, deviceID, deviceSecret, msgTitle, msgContent string) (printerStatus *partner.PrinterStatus, err error) {
	if deviceID != "" {
		var status int
		if globals.EnableStoreWrite {
			_, status, err = api.ZhongwuAPI.PrintMsg(deviceID, deviceSecret, msgContent)
		}
		if err == nil {
			printerStatus = c.translateStatus(status)
		}
	} else {
		printerStatus = &partner.PrinterStatus{
			PrintResult: partner.PrintResultNoPrinter,
		}
	}
	return printerStatus, err
}

func (c *PrinterHandler) GetPrinterStatus(ctx *jxcontext.Context, deviceID, deviceSecret string) (printerStatus *partner.PrinterStatus, err error) {
	status, err := api.ZhongwuAPI.GetPrinterStatus(deviceID, deviceSecret)
	if err == nil {
		printerStatus = c.translateStatus(status)
	}
	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) {
	content := ""
	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) {
	if len(order.Skus) == 0 {
		return
	}
	content := c.getCancelOrRefundOrderContent(order, printType, storeDetail)

	if content == "" {
		return nil, nil
	}

	return c.PrintMsg(ctx, store.PrinterSN, store.PrinterKey, order.VendorOrderID, content)
}

func (c *PrinterHandler) RegisterPrinter(ctx *jxcontext.Context, deviceID, deviceSecret, printerName string, storeID int64) (notUsed1, notUsed2 string, err error) {
	if deviceID == "" || deviceSecret == "" {
		err = fmt.Errorf("打印机ID与打印机密钥都不能为空")
	}
	_, err = c.GetPrinterStatus(ctx, deviceID, deviceSecret)
	return "", "", err
}

func (c *PrinterHandler) UnregisterPrinter(ctx *jxcontext.Context, deviceID, deviceSecret string) (err error) {
	// 中午云不需要注册
	return err
}

func (c *PrinterHandler) translateStatus(status int) (printerStatus *partner.PrinterStatus) {
	printerStatus = &partner.PrinterStatus{
		PrintResult: partner.PrintResultSuccess,
	}
	if status == zhongwuapi.PrinterStatusOnline {
		printerStatus.PrinterStatus = partner.PrinterStatusOnlineOK
	} else if status == zhongwuapi.PrinterStatusLackPaper {
		printerStatus.PrinterStatus = partner.PrinterStatusOnlineAbnormal
	} else {
		printerStatus.PrinterStatus = partner.PrinterStatusOffline
	}
	return printerStatus
}

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

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

func (c *PrinterHandler) EmptyPrintList(ctx *jxcontext.Context, id1, id2 string) (err error) {
	if globals.EnableStoreWrite {
		_, err = api.ZhongwuAPI.EmptyPrintQueue(id1, id2)
	}
	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.VendorIDZhongWu])
}
