package controllers

import (
	"bytes"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/dingdingapi"
	"git.rosy.net.cn/jx-callback/business/jxutils/ddmsg"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/partner/im"
	"io/ioutil"
	"net/http"

	"github.com/astaxie/beego/server/web/context"

	"git.rosy.net.cn/baseapi/platformapi/jdapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/partner/purchase/jd"
	"git.rosy.net.cn/jx-callback/globals"
	"github.com/astaxie/beego/server/web"
)

// Operations about JDOrder
type DjswController struct {
	web.Controller
}

func (c *DjswController) handleMsg(handler func(*jdapi.API, interface{}) *jdapi.CallbackResponse) (callbackResponse *jdapi.CallbackResponse) {
	callbackMsg, mapData, callbackResponse := jdapi.GetCallbackMsg(getUsefulRequest(c.Ctx))
	if callbackResponse == nil {
		if jdAPI := jd.GetAPIbyKey(callbackMsg.AppKey); jdAPI != nil {
			if callbackResponse = jdAPI.CheckCallbackValidation(mapData, callbackMsg.Sign); callbackResponse == nil {
				callbackResponse = handler(jdAPI, callbackMsg.Param)
			}
		} else {
			callbackResponse = jdapi.Err2CallbackResponse(fmt.Errorf("没有匹配的appKey,非法请求"), "")
		}
	}
	return callbackResponse
}

func (c *DjswController) orderStatus() {
	if c.Ctx.Input.Method() == http.MethodPost {
		callbackResponse := c.handleMsg(func(a *jdapi.API, obj interface{}) (callbackResponse *jdapi.CallbackResponse) {
			callbackResponse = jd.OnOrderMsg(obj.(*jdapi.CallbackOrderMsg), a)
			return callbackResponse
		})
		c.Data["json"] = c.transferResponse("orderStatus", callbackResponse)
		c.ServeJSON()
	} else {
		c.Abort("404")
	}
}

func (c *DjswController) NewOrder() {
	c.orderStatus()
}

func (c *DjswController) OrderAdjust() {
	c.orderStatus()
}

func (c *DjswController) OrderWaitOutStore() {
	c.orderStatus()
}

func (c *DjswController) PickFinishOrder() {
	c.orderStatus()
}

func (c *DjswController) DeliveryOrder() {
	c.orderStatus()
}

func (c *DjswController) FinishOrder() {
	c.orderStatus()
}

func (c *DjswController) LockOrder() {
	c.orderStatus()
}

func (c *DjswController) UnlockOrder() {
	c.orderStatus()
}

func (c *DjswController) UserCancelOrder() {
	c.orderStatus()
}

func (c *DjswController) ApplyCancelOrder() {
	c.orderStatus()
}

func (c *DjswController) VenderAuditApplyCancelOrder() {
	c.orderStatus()
}

func (c *DjswController) PushDeliveryStatus() {
	if c.Ctx.Input.Method() == http.MethodPost {
		callbackResponse := c.handleMsg(func(a *jdapi.API, obj interface{}) (callbackResponse *jdapi.CallbackResponse) {
			callbackResponse = jd.OnWaybillMsg(obj.(*jdapi.CallbackDeliveryStatusMsg))
			return callbackResponse
		})
		c.Data["json"] = c.transferResponse("PushDeliveryStatus", callbackResponse)
		c.ServeJSON()
	} else {
		c.Abort("404")
	}
}

func (c *DjswController) OrderCommentPush() {
	c.orderStatus()
}

func (c *DjswController) Token() {
	urlValues, err := utils.HTTPBody2Values(c.Ctx.Input.RequestBody, false)
	globals.SugarLogger.Info(utils.Format4Output(utils.Format4Output(err, false), false))
	globals.SugarLogger.Info(utils.Format4Output(utils.Format4Output(urlValues, false), false))
	jd.OnTokenChange(urlValues)
	c.Data["json"] = c.transferResponse("Token", nil)
	c.ServeJSON()
}

func (c *DjswController) StockIsHave() {
	if c.Ctx.Input.Method() == http.MethodPost {
		callbackResponse := c.handleMsg(func(a *jdapi.API, obj interface{}) (callbackResponse *jdapi.CallbackResponse) {
			return callbackResponse
		})
		c.Data["json"] = c.transferResponse("StockIsHave", callbackResponse)
		c.ServeJSON()
	} else {
		c.Abort("404")
	}
}

func (c *DjswController) SinglePromoteCreate() {
	if c.Ctx.Input.Method() == http.MethodPost {
		callbackResponse := c.handleMsg(func(a *jdapi.API, obj interface{}) (callbackResponse *jdapi.CallbackResponse) {
			callbackResponse = jd.OnActMsg(obj.(*jdapi.CallbackOrderMsg))
			return callbackResponse
		})
		c.Data["json"] = c.transferResponse("SinglePromoteCreate", callbackResponse)
		c.ServeJSON()
	} else {
		c.Abort("404")
	}
}

func (c *DjswController) StoreCrud() {
	if c.Ctx.Input.Method() == http.MethodPost {
		callbackResponse := c.handleMsg(func(a *jdapi.API, obj interface{}) (callbackResponse *jdapi.CallbackResponse) {
			callbackResponse = jd.OnStoreMsg(obj.(*jdapi.CallbackOrderMsg))
			return callbackResponse
		})
		callbackResponse = jdapi.Err2CallbackResponse(nil, "")
		c.Data["json"] = c.transferResponse("StoreCrud", callbackResponse)
		c.ServeJSON()
	} else {
		c.Abort("404")
	}
}

func (c *DjswController) transferResponse(funcName string, inCallbackResponse *jdapi.CallbackResponse) (outCallbackResponse *jdapi.CallbackResponse) {
	if globals.IsCallbackAlwaysReturnSuccess() {
		return jdapi.SuccessResponse
	}
	if inCallbackResponse == nil {
		return jdapi.SuccessResponse
	}
	return inCallbackResponse
}

func (c *DjswController) EndOrderFinance() {
	c.nullOperation()
}

func (c *DjswController) FinanceAdjustment() {
	c.nullOperation()
}

func (c *DjswController) DeliveryCarrierModify() {
	c.nullOperation()
}

func (c *DjswController) NewApplyAfterSaleBill() {
	c.orderStatus()
}

func (c *DjswController) UpdateApplyAfterSaleBill() {
	c.orderStatus()
}

func (c *DjswController) NewAfterSaleBill() {
	c.orderStatus()
}

func (c *DjswController) AfterSaleBillStatus() {
	c.orderStatus()
}

func (c *DjswController) OrderAccounting() {
	c.orderStatus()
}

func getUsefulRequest(ctx *context.Context) *http.Request {
	ctx.Request.Body = ioutil.NopCloser(bytes.NewReader(ctx.Input.RequestBody))
	return ctx.Request
}

func (c *DjswController) nullOperation() {
	c.Data["json"] = c.transferResponse("nullOperation", nil)
	c.ServeJSON()
}

func (c *DjswController) UpdateSku() {
	c.nullOperation()
}

func (c *DjswController) OrderAddTips() {
	c.orderStatus()
}

func (c *DjswController) OrderInfoChange() {
	if c.Ctx.Input.Method() == http.MethodPost {
		callbackResponse := c.handleMsg(func(a *jdapi.API, obj interface{}) (callbackResponse *jdapi.CallbackResponse) {
			callbackResponse = jd.OnOrderInfoChangeMsg(obj.(*jdapi.CallbackOrderInfoChangeMsg))
			return callbackResponse
		})
		c.Data["json"] = c.transferResponse("OrderInfoChange", callbackResponse)
		c.ServeJSON()
	} else {
		c.Abort("404")
	}
}

// OrderInvoice 发票申请
func (c *DjswController) OrderInvoice() {
	if c.Ctx.Input.Method() == http.MethodPost {
		callbackResponse := c.handleMsg(func(a *jdapi.API, obj interface{}) (callbackResponse *jdapi.CallbackResponse) {
			callbackResponse = jd.OnInvoiceMsg(obj.(*jdapi.CallbackInvoiceMsg))
			return callbackResponse
		})
		callbackResponse = jdapi.Err2CallbackResponse(nil, "")
		c.Data["json"] = c.transferResponse("StoreCrud", callbackResponse)
		c.ServeJSON()
	} else {
		c.Abort("404")
	}
}

func (c *DjswController) imMsg() {
	if c.Ctx.Input.Method() == http.MethodPost {
		msg, url, err := jdapi.ImChatRiskMsg(getUsefulRequest(c.Ctx))
		globals.SugarLogger.Debugf("-----------jdmsg := %s", utils.Format4Output(msg, false))
		globals.SugarLogger.Debugf("-----------jdmsg URL:= %s", url)
		if err == nil {
			var base *jdapi.BaseInfo
			if utils.UnmarshalUseNumber(msg, &base); err == nil {
				if url == "msgReadAck" || url == "chatRiskMsg" {
					ddmsg.SendUserMessage(dingdingapi.MsgTyeText, "2452A93EEB9111EC9B06525400E86DC0", fmt.Sprintf("jdIm:%s消息推送", url), utils.Format4Output(msg, false))
				}
				err = im.ReadMsgFromVendor(model.VendorIDJD, url, []byte(base.JdParamJson))
			}
		}

		if err != nil {
			c.Data["json"] = -1
		} else {
			c.Data["json"] = 0
		}
		c.ServeJSON()
	} else {
		c.Abort("404")
	}
}

// ChatRiskMsg 风控消息推送
func (c *DjswController) ChatRiskMsg() {
	c.imMsg()
}

// MsChatMessage 用户消息
func (c *DjswController) MsChatMessage() {
	c.imMsg()
}

// MsgReadAck 消息已读
func (c *DjswController) MsgReadAck() {
	c.imMsg()
}

//免费开卡接不到回调
//func (c *DjswController) MemberCreateCard() {
//	if c.Ctx.Input.Method() == http.MethodPost {
//		callbackResponse := c.handleMsg(func(a *jdapi.API, obj interface{}) (callbackResponse *jdapi.CallbackResponse) {
//			callbackResponse = jd.MemberCreateMsg(obj.(*jdapi.CallbackMemberMsg))
//			return callbackResponse
//		})
//		c.Data["json"] = c.transferResponse("MemberCreateCard", callbackResponse)
//		c.ServeJSON()
//	} else {
//		c.Abort("404")
//	}
//}
//
//func (c *DjswController) MemberRenewCard() {
//	if c.Ctx.Input.Method() == http.MethodPost {
//		callbackResponse := c.handleMsg(func(a *jdapi.API, obj interface{}) (callbackResponse *jdapi.CallbackResponse) {
//			callbackResponse = jd.MemberRenewMsg(obj.(*jdapi.CallbackMemberMsg))
//			return callbackResponse
//		})
//		c.Data["json"] = c.transferResponse("MemberRenewCard", callbackResponse)
//		c.ServeJSON()
//	} else {
//		c.Abort("404")
//	}
//}
