package controllers

import (
	"crypto/md5"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable"
	"git.rosy.net.cn/baseapi/platformapi/tiktok_shop/tiktok_api"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxstore/common"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/partner"
	taoVegetable "git.rosy.net.cn/jx-callback/business/partner/purchase/tao_vegetable"
	"git.rosy.net.cn/jx-callback/globals/api"
	"github.com/astaxie/beego/server/web"
	"io/ioutil"
	"net/http"
	"net/url"
	"sort"
	"strings"
)

type TaoBaoVegetableController struct {
	web.Controller
}

// GetCode 淘菜菜获取商户授权code,这个code和token是门店层次的
func (c *TaoBaoVegetableController) GetCode() {
	codeData := ""
	if c.Ctx.Input.Method() == http.MethodPost {
		body, err := ioutil.ReadAll(c.Ctx.Request.Body)
		if err != nil {
			c.Data["json"] = tao_vegetable.CallBackResultInfo(err)
			c.ServeJSON()
			return
		}
		codeData = string(body)
	} else {
		codeData = c.Ctx.Input.Query("code")
	}
	tokenInfo, err := api.TaoVegetableApi.GetStoreToken(codeData, "")
	if err != nil {
		c.Data["json"] = tao_vegetable.CallBackResultInfo(err)
		c.ServeJSON()
		return
	}

	// 创建或者更新账号token
	param := &model.VendorOrgCode{
		VendorID:       model.VendorIDTaoVegetable,
		VendorOrgCode:  tokenInfo.UserId,
		Comment:        tokenInfo.UserNick,
		VendorType:     "platform",
		IsJxCat:        1,
		IsOpen:         1,
		EmpowerURL:     "http://oauth.hemaos.com/authorize?\nresponse_type=code&sp=hema&op=topApp&client_id=" + api.TaoVegetableApi.GetVendorOrgCode(),
		StoreBrandName: "自动更新(京西菜市)",
		Token:          utils.Format4Output(tokenInfo, false),
		AppKey:         api.TaoVegetableApi.GetVendorOrgCode(),
		AppSecret:      api.TaoVegetableApi.GetAppSecret(),
	}
	if err := common.AddVendorOrgCode(nil, param); err != nil {
		c.Data["json"] = tiktok_api.CallbackResponse{Code: tiktok_api.CallbackFailCode, Msg: tiktok_api.CallbackFail}
		c.ServeJSON()
		return
	}

	c.Data["json"] = tao_vegetable.CallBackResultInfo(nil)
	c.ServeJSON()
	return
}

// OrderStatus 订单状态变化 [post]
func (c *TaoBaoVegetableController) OrderStatus() {
	urlParam := c.Ctx.Request.URL.RawQuery

	// 获取url参数
	values, err := url.ParseQuery(urlParam)
	if err != nil {
		c.Data["json"] = tao_vegetable.CallBackResultInfo(err)
		c.ServeJSON()
		return
	}

	// 获取body参数
	order, body, err := api.TaoVegetableApi.ReaderOrderInfo(c.Ctx.Request)
	if err != nil {
		c.Data["json"] = tao_vegetable.CallBackResultInfo(err)
		c.ServeJSON()
		return
	}

	// 验签
	sign := Sign(values, body, api.TaoVegetableApi.GetAppSecret())
	switch order.MerchantCode {
	case "CSSJ": // 淘宝回调地址检测
		if sign != values.Get("sign") {
			c.Data["json"] = tao_vegetable.CallBackResultSign(fmt.Errorf("非法签名"))
			c.ServeJSON()
			return
		} else {
			c.Data["json"] = tao_vegetable.CallBackResultSign(nil)
			c.ServeJSON()
			return
		}
	default:
		callbackResponse := taoVegetable.OnCallbackMsg(tao_vegetable.OrderStatusChange, utils.Int64ToStr(order.BizOrderId), order)
		c.Data["json"] = callbackResponse
		c.ServeJSON()
		return
	}
}

// ApplyCancelOrder 用户发起售后申请
func (c *TaoBaoVegetableController) ApplyCancelOrder() {
	urlParam := c.Ctx.Request.URL.RawQuery

	// 获取url参数
	values, err := url.ParseQuery(urlParam)
	if err != nil {
		c.Data["json"] = tao_vegetable.CallBackResultInfo(err)
		c.ServeJSON()
		return
	}

	afsOrder, body, err := api.TaoVegetableApi.UserApplyRefund(c.Ctx.Request)
	if err != nil {
		c.Data["json"] = tao_vegetable.CallBackResultInfo(err)
		c.ServeJSON()
		return
	}

	// 验签 FFF779F16365992BD721C9C1A027F03C
	sign := Sign(values, body, api.TaoVegetableApi.GetAppSecret())
	switch afsOrder.MerchantCode {
	case "CSSJ":
		if sign != values.Get("sign") { // E8C3B7D19ECCB6618CB0F2C30BB086EC
			c.Data["json"] = tao_vegetable.CallBackResultSign(fmt.Errorf("非法签名"))
			c.ServeJSON()
			return
		} else {
			c.Data["json"] = tao_vegetable.CallBackResultSign(nil)
			c.ServeJSON()
			return
		}
	default:
		callbackResponse := taoVegetable.OnCallbackMsg(tao_vegetable.OrderStatusApplyAfs, afsOrder.OutOrderId, afsOrder)
		c.Data["json"] = callbackResponse
		c.ServeJSON()
		return
	}
}

// UserCancelRefund 用户取消售后
func (c *TaoBaoVegetableController) UserCancelRefund() {
	urlParam := c.Ctx.Request.URL.RawQuery

	// 获取url参数
	values, err := url.ParseQuery(urlParam)
	if err != nil {
		c.Data["json"] = tao_vegetable.CallBackResultInfo(err)
		c.ServeJSON()
		return
	}

	afsOrder, body, err := api.TaoVegetableApi.UserCancelRefundApply(c.Ctx.Request)
	if err != nil {
		c.Data["json"] = tao_vegetable.CallBackResultInfo(err)
		c.ServeJSON()
		return
	}

	// 验签
	sign := Sign(values, body, api.TaoVegetableApi.GetAppSecret())
	switch afsOrder.MerchantCode {
	case "CSSJ":
		if sign != values.Get("sign") {
			c.Data["json"] = tao_vegetable.CallBackResultSign(fmt.Errorf("非法签名"))
			c.ServeJSON()
			return
		} else {
			c.Data["json"] = tao_vegetable.CallBackResultSign(nil)
			c.ServeJSON()
			return
		}
	default:
		callbackResponse := taoVegetable.OnCallbackMsg(tao_vegetable.OrderStatusCancelAfs, afsOrder.OutOrderId, afsOrder)
		c.Data["json"] = callbackResponse
		c.ServeJSON()
		return
	}

}

// CancelOnSaleRefundOrder 用户售中取消(走订单取消流程)
func (c *TaoBaoVegetableController) CancelOnSaleRefundOrder() {
	urlParam := c.Ctx.Request.URL.RawQuery

	// 获取url参数
	values, err := url.ParseQuery(urlParam)
	if err != nil {
		c.Data["json"] = tao_vegetable.CallBackResultInfo(err)
		c.ServeJSON()
		return
	}

	afsOrder, body, err := api.TaoVegetableApi.OnSaleRefundOrder(c.Ctx.Request)
	if err != nil {
		c.Data["json"] = tao_vegetable.CallBackResultInfo(err)
		c.ServeJSON()
		return
	}

	// 验签
	sign := Sign(values, body, api.TaoVegetableApi.GetAppSecret())
	switch afsOrder.PartCancelRequest.MerchantCode {
	case "CSSJ":
		if sign != values.Get("sign") {
			c.Data["json"] = tao_vegetable.CallBackResultSign(fmt.Errorf("非法签名"))
			c.ServeJSON()
			return
		} else {
			c.Data["json"] = tao_vegetable.CallBackResultSign(nil)
			c.ServeJSON()
			return
		}
	default:
		order, err := partner.CurOrderManager.LoadOrder(utils.Int64ToStr(afsOrder.PartCancelRequest.BizOrderId), model.VendorIDTaoVegetable)
		if err != nil {
			c.Data["json"] = tao_vegetable.CallBackResultOnSaleCancel(nil)
			c.ServeJSON()
			return
		}

		if order.Status == model.OrderStatusCanceled {
			c.Data["json"] = tao_vegetable.CallBackResultOnSaleCancel(nil)
			c.ServeJSON()
		}
		if order.Status >= model.OrderStatusDelivering {
			c.Data["json"] = tao_vegetable.CallBackResultOnSaleCancel(fmt.Errorf("不支持售中取消"))
			c.ServeJSON()
		} else {
			c.Data["json"] = tao_vegetable.CallBackResultOnSaleCancel(nil)
			c.ServeJSON()
		}
	}
}

// RefundOrderSuccess 用户售后成功通知,只有退款成功了才会通知(商户拒绝退款,不会通知)
func (c *TaoBaoVegetableController) RefundOrderSuccess() {
	urlParam := c.Ctx.Request.URL.RawQuery

	// 获取url参数
	values, err := url.ParseQuery(urlParam)
	if err != nil {
		c.Data["json"] = tao_vegetable.CallBackResultInfo(err)
		c.ServeJSON()
		return
	}

	refundSuccess, body, err := api.TaoVegetableApi.RefundOrderFinish(c.Ctx.Request)
	if err != nil {
		c.Data["json"] = tao_vegetable.CallBackResultInfo(err)
		c.ServeJSON()
		return
	}
	// 验签
	sign := Sign(values, body, api.TaoVegetableApi.GetAppSecret())
	switch refundSuccess.MerchantCode {
	case "CSSJ":
		if sign != values.Get("sign") {
			c.Data["json"] = tao_vegetable.CallBackResultSign(fmt.Errorf("非法签名"))
			c.ServeJSON()
			return
		} else {
			c.Data["json"] = tao_vegetable.CallBackResultSign(nil)
			c.ServeJSON()
			return
		}
	default:
		callbackResponse := taoVegetable.OnCallbackMsg(tao_vegetable.OrderStatusRefundSuccess, refundSuccess.OutMainRefundId, refundSuccess)
		c.Data["json"] = callbackResponse
		c.ServeJSON()
		return
	}
}

func Sign(param url.Values, data, secret string) string {
	var publicParam = make([]string, 0, 0)
	for k, v := range param {
		if k == "sign" {
			continue
		}
		publicParam = append(publicParam, fmt.Sprintf("%s%s", k, v[0]))
	}

	sort.Strings(publicParam)
	resultParam := strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(data, "\n", ""), "\t", ""), " ", ""), "\r", "")
	if strings.Contains(resultParam, `\u0026`) {
		resultParam = strings.ReplaceAll(resultParam, `\u0026`, "&")
	}
	cc := secret + strings.Join(publicParam, "") + resultParam + secret

	return fmt.Sprintf("%X", md5.Sum([]byte(cc)))
}
