package ebai

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/ebaiapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/jxutils/weixinmsg"
	"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/business/partner/im"
	"git.rosy.net.cn/jx-callback/globals/api"
	"time"
)

const (
	IMVendorIDELM = 3 //饿了么
)

// OnImMessage 用户/骑手 发送/已读消息 回调
func (p *PurchaseHandler) OnImMessage(msg *ebaiapi.CallbackMsg) (response *ebaiapi.CallbackResponse) {
	str, err := json.Marshal(msg.Data)

	err = im.ReadMsgFromVendor(IMVendorIDELM, msg.Source, str)
	if err != nil {
		return api.EbaiAPI.Err2CallbackResponse(msg.Cmd, err, msg.Cmd)
	}
	return nil
}

// InvoiceApply 用户申请发票
func (p *PurchaseHandler) InvoiceApply(msg *ebaiapi.CallbackMsg) (response *ebaiapi.CallbackResponse) {

	var (
		db            = dao.GetDB()
		applyNo       = ""
		storeId       = ""
		vendorStoreId = ""
		orderId       = ""
	)

	switch msg.Cmd {
	case ebaiapi.CmdImInvoicApply:
		invoice := &ebaiapi.InvoiceApplyBody{}
		if err := utils.Map2StructByJson(msg.Body, invoice, false); err != nil {
			return api.EbaiAPI.Err2CallbackResponse(msg.Cmd, err, msg.Cmd)
		}
		orderId = invoice.OrderList[0].OrderId
		invoiceData, _ := dao.GetInvoiceInfo(db, orderId)
		applyNo = invoice.ApplicationNo
		storeId = invoice.ShopId
		vendorStoreId = invoice.BaiduShopId
		localOrder, _ := partner.CurOrderManager.LoadOrder(orderId, model.VendorIDEBAI)

		if invoiceData == nil {
			invoiceObj := &model.InvoiceMsg{
				ModelIDCUL:            model.ModelIDCUL{},
				OrderId:               orderId,
				StoreID:               localOrder.JxStoreID,
				VendorID:              model.VendorIDEBAI,
				InvoiceTaskId:         invoice.ApplicationNo,
				Status:                invoice.Status,
				PushType:              1,
				InvoiceTitle:          invoice.BuyerTitle.TitleName,
				TaxpayerId:            invoice.BuyerTitle.TaxPayerNum,
				NeedInvoiceByCategory: 1,
				CompanyAddress:        invoice.BuyerTitle.RegisterAddress,
				CompanyPhone:          invoice.BuyerTitle.RegisterPhone,
				AccountBank:           invoice.BuyerTitle.BankName,
				AccountNumber:         invoice.BuyerTitle.BankAccount,
				Email:                 invoice.BuyerContact.Email,
				InvoiceAmount:         utils.Float64TwoInt64(invoice.TotalInvoiceAmount * 100),
				InvoiceUrl:            "",
				InvoiceId:             "",
			}
			if len(invoice.OrderList) > 1 {
				orderList := make(map[string]float64, 0)
				for _, v := range invoice.OrderList {
					orderList[v.OrderId] = v.InvoiceAmount
				}
				invoiceObj.Remark = string(utils.MustMarshal(orderList))
			}
			dao.WrapAddIDCULEntity(invoiceObj, "system")
			if err := dao.CreateEntity(db, invoiceObj); err != nil {
				return api.EbaiAPI.Err2CallbackResponse(msg.Cmd, err, msg.Cmd)
			}
		}
	case ebaiapi.CmdImInvoicEmail:
		invoice := &ebaiapi.InvoiceEmailPush{}
		if err := utils.Map2StructByJson(msg.Body, invoice, false); err != nil {
			return api.EbaiAPI.Err2CallbackResponse(msg.Cmd, err, msg.Cmd)
		}
		applyNo = invoice.ApplicationNo
		storeId = invoice.ShopId
		vendorStoreId = invoice.BaiduShopId
		invoiceData, _ := dao.GetInvoiceInfoByTaskId(db, invoice.ApplicationNo)
		if invoiceData != nil {
			invoiceData.UpdatedAt = time.Now()
			invoiceData.Email = invoice.Email
			dao.UpdateEntity(db, invoiceData, "UpdatedAt", "Email")
			orderId = invoiceData.OrderId
		}
	}

	if orderId != "" {
		localOrder, _ := partner.CurOrderManager.LoadOrder(orderId, model.VendorIDEBAI)
		if localOrder != nil {
			content2 := fmt.Sprintf("发票单号:%s,用户申请发票,请老板提供发票信息!", applyNo)
			if _, err := weixinmsg.SendStoreMessage(jxcontext.AdminCtx, fmt.Sprintf("饿了么用户申请发票:%s", localOrder.StoreName), content2, []int{utils.Str2Int(storeId)}, nil, "", model.MessageTypeStore, true, true); err != nil {
				im.PushMsgByCid(vendorStoreId, model.VendorIDEBAI, content2)
			}
		}
	}

	return api.EbaiAPI.Err2CallbackResponse(msg.Cmd, nil, msg.Cmd)
}

// BusinessSendMsg 向门店发送消息
//func BusinessSendMsg(param *ebaiapi.BusinessSendMsgReq) error {
//	err := api.EbaiAPI.BusinessSendMsg(param)
//	return err
//}

// GetStoreIMStatus 查询门店IM开关状态
//func GetStoreIMStatus(platformShopId string) (string, error) {
//	retVal, err := api.EbaiAPI.GetStoreIMStatus(platformShopId)
//	return retVal, err
//}

// UpdateIMStatus 更新店铺IM开关状态 1-开启,-1-关闭
//func UpdateIMStatus(platformShopId string, status int) error {
//	err := api.EbaiAPI.UpdateIMStatus(platformShopId, status)
//	return err
//}
