package mtwm

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils/weixinmsg"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/business/partner/im"
	beego "github.com/astaxie/beego/server/web"
	"net/http"
	"net/url"
	"strings"
	"time"

	"git.rosy.net.cn/baseapi/platformapi/mtwmapi"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/jxutils/netprinter"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/globals"
)

// 美团回调接口
func OnCallbackMsg(msg *mtwmapi.CallbackMsg, msgType string) (response *mtwmapi.CallbackResponse) {
	if CurPurchaseHandler != nil {
		if msg.Cmd == mtwmapi.MsgTypeStoreStatusChanged || msg.Cmd == mtwmapi.MsgTypeStoreAuditStatusChanged {
			response = CurPurchaseHandler.onStoreStatusChanged(msg)
		} else if msg.Cmd == mtwmapi.MsgTypePrivateNumberDowngrade {
			response = CurPurchaseHandler.onNumberDowngrade(msg)
		} else if msg.Cmd == mtwmapi.MsgTypeStoreBind {
			// 门店授权发生变化 17,失去授权
			vendorStoreID := msg.FormData.Get("app_poi_code")
			storeDetail, _ := dao.GetStoreDetailByVendorStoreID(dao.GetDB(), vendorStoreID, model.VendorIDMTWM, "")
			_, err := netprinter.PrintStoreStatus(jxcontext.AdminCtx, storeDetail, model.VendorIDMTWM, -9)
			response = mtwmapi.Err2CallbackResponse(err, "")
		} else if msg.Cmd == mtwmapi.MsgTypeSkuUpdate {
			skuInfo, err := url.QueryUnescape(msg.FormData.Get("retail_data"))
			if err != nil {
				globals.SugarLogger.Debugf("QueryUnescape err := %v", err)
				return nil
			}
			dataMap := make([]*mtwmapi.VendorUpdateSkuCallback, 0, 0)
			if err = utils.UnmarshalUseNumber([]byte(skuInfo), &dataMap); err != nil {
				globals.SugarLogger.Debugf(" UnmarshalUseNumber err := %v", err)
				return nil
			}
			if len(dataMap) != 0 {
				var storeMap = make(map[string]map[int][]string, 0)
				var skuStatus = make(map[int][]string, 0)
				var operate = make(map[string]string, 0)
				for _, v := range dataMap {
					if v.AppFoodCode != "" && v.AppPoiCode != "" && v.DiffContents.IsSoldOut.Origin != v.DiffContents.IsSoldOut.Result {
						skuStatus[v.DiffContents.IsSoldOut.Result] = append(skuStatus[v.DiffContents.IsSoldOut.Result], v.AppFoodCode)
						storeMap[v.AppPoiCode] = skuStatus
						operate[v.AppFoodCode] = fmt.Sprintf("%s:%s:0↑-1↓:前%d->后%d", v.OpAppKey, v.OpName, v.DiffContents.IsSoldOut.Origin, v.DiffContents.IsSoldOut.Result)
					}
				}
				for k, v := range storeMap {
					storeDetail, _ := dao.GetStoreDetailByVendorStoreID(dao.GetDB(), k, model.VendorIDMTWM, "")
					if storeDetail != nil {
						for k2, v2 := range v {
							if len(v2) == 0 {
								continue
							}
							switch k2 {
							case 1: // 下架
								param := []interface{}{}
								param = append(param, 0, operate[v2[0]], time.Now(), storeDetail.ID, v2)
								sql := `UPDATE store_sku_bind SET status = ?,last_operator = ?,updated_at = ?  WHERE store_id = ? AND sku_id IN` + "(" + dao.GenQuestionMarks(len(v2)) + ")"
								dao.ExecuteSQL(dao.GetDB(), sql, param...)
							case 0: // 上架
								param := []interface{}{}
								param = append(param, 1, operate[v2[0]], time.Now(), storeDetail.ID, v2)
								sql := `UPDATE store_sku_bind SET status = ?,last_operator = ?,updated_at = ?  WHERE store_id = ? AND sku_id IN` + "(" + dao.GenQuestionMarks(len(v2)) + ")"
								dao.ExecuteSQL(dao.GetDB(), sql, param...)
							}
						}
					}
				}
			}
			return mtwmapi.Err2CallbackResponse(nil, "")
		} else {
			if orderID := GetOrderIDFromMsg(msg); orderID != "" {
				jxutils.CallMsgHandler(func() {
					switch msg.Cmd {
					case mtwmapi.MsgTypeWaybillStatus:
						response = CurPurchaseHandler.onWaybillMsg(msg)
					default:
						response = CurPurchaseHandler.onOrderMsg(msg)
					}
				}, jxutils.ComposeUniversalOrderID(orderID, model.VendorIDMTWM))
			}
			/*if msg.Cmd == mtwmapi.MsgTypeOrderRefund || msg.Cmd == mtwmapi.MsgTypeOrderPartialRefund {
				utils.CallFuncAsync(func() {
					OnFinancialMsg(msg)
				})
			} */
		}
	}
	return response
}

func GetOrderIDFromMsg(msg *mtwmapi.CallbackMsg) string {
	return msg.FormData.Get(mtwmapi.KeyOrderID)
}

func GetVendorStoreIDFromMsg(msg *mtwmapi.CallbackMsg) string {
	return msg.FormData.Get(mtwmapi.KeyAppPoiCode)
}

func GetVendorAppIdFromMsg(msg *mtwmapi.CallbackMsg) string {
	return msg.FormData.Get(mtwmapi.KeyAppID)
}

// OnImMsg  im消息回调
func OnImMsg(msg *mtwmapi.ImCallbackMsg) (response *mtwmapi.CallbackResponse) {
	if str, err := json.Marshal(msg.PushContent); err == nil {
		var PushContentReq = mtwmapi.PushContentReq{}
		if err = json.Unmarshal(str, &PushContentReq); err != nil {
			return mtwmapi.SignatureIsNotOk
		}
		storeDetail, err2 := dao.GetStoreDetailByVendorStoreID(dao.GetDB(), PushContentReq.AppPoiCode, model.VendorIDMTWM, utils.Int2Str(PushContentReq.AppID))
		if err2 != nil || storeDetail == nil {
			msg.PushContent = string(str)
			switch beego.BConfig.RunMode {
			case model.ServerTypeFruits:
				pushIMToGyOrPet(msg, model.ServerTypePet)
				return mtwmapi.SuccessResponse
			case model.ServerTypeVegetable:
				pushIMToGyOrPet(msg, model.ServerTypeFruits)
				return mtwmapi.SuccessResponse
			case model.ServerTypePet:
				return mtwmapi.SuccessResponse
			}
		}

		err = im.ReadMsgFromVendor(model.VendorIDMTWM, "", str)
		if err != nil {
			globals.SugarLogger.Debugf("OnImMsg提示：%v", err)
			return mtwmapi.SignatureIsNotOk
		}
	}
	return mtwmapi.SuccessResponse
}

func pushIMToGyOrPet(msg *mtwmapi.ImCallbackMsg, serverType string) {
	var (
		cl      = http.Client{}
		request = &http.Request{}
		err     error
	)
	params := make(map[string]interface{})
	params["timestamp"] = msg.Timestamp
	params["sig"] = msg.Sig
	params["app_id"] = msg.AppID
	params["biz_type"] = msg.BizType
	params["push_content"] = msg.PushContent

	switch serverType {
	case model.ServerTypeFruits:
		request, err = http.NewRequest(http.MethodPost, "http://callback-jxgy.jxc4.com/mtwm/iMCallback", strings.NewReader(utils.Map2URLValues(params).Encode()))
		if err != nil {
			return
		}
	case model.ServerTypePet:
		request, err = http.NewRequest(http.MethodPost, "http://callback-gblm.jxc4.com/mtwm/iMCallback", strings.NewReader(utils.Map2URLValues(params).Encode()))
		if err != nil {
			return
		}
	}

	request.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
	request.Header.Set("accept", "application/json, text/plain, */*")
	resp, err := cl.Do(request)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	return
}

func InvoiceCallback(invoice *mtwmapi.InvoiceCallback) (err error) {
	var db = dao.GetDB()
	localOrder, _ := partner.CurOrderManager.LoadOrder(invoice.OrderId, model.VendorIDMTWM)
	if localOrder == nil {
		return fmt.Errorf("订单不存在:%s", invoice.OrderId)
	}
	invoiceData, _ := dao.GetInvoiceInfo(db, invoice.OrderId)
	if invoiceData == nil {
		invoiceObj := &model.InvoiceMsg{
			ModelIDCUL:            model.ModelIDCUL{},
			OrderId:               invoice.OrderId,
			StoreID:               localOrder.JxStoreID,
			VendorID:              model.VendorIDMTWM,
			Status:                model.InvoiceStatusInit,
			InvoiceTaskId:         invoice.InvoiceTaskId,
			PushType:              utils.Str2Int(invoice.PushType),
			InvoiceTitle:          invoice.InvoiceTitle,
			TaxpayerId:            invoice.TaxpayerId,
			NeedInvoiceByCategory: invoice.NeedInvoiceByCategory,
			CompanyAddress:        invoice.CompanyAddress,
			CompanyPhone:          invoice.CompanyPhone,
			AccountBank:           invoice.AccountBank,
			AccountNumber:         invoice.AccountNumber,
			Email:                 invoice.Email,
			InvoiceAmount:         invoice.ItemTotalInvoiceAmount,
			InvoiceUrl:            "",
			InvoiceId:             "",
		}
		dao.WrapAddIDCULEntity(invoiceObj, "system")
		if err = dao.CreateEntity(db, invoiceObj); err != nil {
			return err
		}
	} else {
		invoiceData.InvoiceTaskId = invoice.InvoiceTaskId
		invoiceData.PushType = utils.Str2Int(invoice.PushType)
		invoiceData.InvoiceTitle = invoice.InvoiceTitle
		invoiceData.TaxpayerId = invoice.TaxpayerId
		invoiceData.NeedInvoiceByCategory = invoice.NeedInvoiceByCategory
		invoiceData.CompanyAddress = invoice.CompanyAddress
		invoiceData.CompanyPhone = invoice.CompanyPhone
		invoiceData.AccountBank = invoice.AccountBank
		invoiceData.AccountNumber = invoice.AccountNumber
		invoiceData.Email = invoice.Email
		invoiceData.InvoiceAmount = invoice.ItemTotalInvoiceAmount
		dao.UpdateEntity(db, invoiceData)
	}

	content2 := fmt.Sprintf("订单:%s,用户申请发票,请老板提供发票信息!", localOrder.VendorOrderID)
	if _, err = weixinmsg.SendStoreMessage(jxcontext.AdminCtx, fmt.Sprintf("美团用户申请发票:%s", localOrder.StoreName), content2, []int{localOrder.JxStoreID}, nil, "", model.MessageTypeStore, true, true); err != nil {
		im.PushMsgByCid(localOrder.VendorStoreID, localOrder.VendorID, content2)
	}
	return err
}
