package jdshop

import (
	"fmt"
	"net/http"
	"strings"
	"time"

	"git.rosy.net.cn/jx-callback/business/model/dao"

	"git.rosy.net.cn/baseapi"
	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/platformapi/jdshopapi"
	"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/jxutils/tasksch"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/globals/api"
)

func (p *PurchaseHandler) AcceptOrRefuseFailedGetOrder(ctx *jxcontext.Context, order *model.GoodsOrder, isAcceptIt bool) (err error) {
	return err
}

func (p *PurchaseHandler) Map2Order(orderData map[string]interface{}) (order *model.GoodsOrder) {
	result := &jdshopapi.AllOrdersResult{}
	if err := utils.Map2StructByJson(orderData, &result, false); err != nil {
		return nil
	}

	jdsOrder := result.OrderList[0]
	order = &model.GoodsOrder{
		VendorOrderID:    utils.Int64ToStr(jdsOrder.OrderID),
		VendorID:         model.VendorIDJDShop,
		BaseFreightMoney: jxutils.StandardPrice2Int(jdsOrder.Freight),
		VendorStatus:     utils.Int2Str(jdsOrder.OrderStatus),
		VendorUserID:     jdsOrder.UserPin,
		BuyerComment:     jdsOrder.UserRemark,
		PickDeadline:     utils.DefaultTimeValue,
		OriginalData:     string(utils.MustMarshal(jdsOrder)),
		Status:           status2Jxstatus(jdsOrder.OrderStatus),
	}
	return order
}
func (p *PurchaseHandler) GetOrder(vendorOrgCode, vendorOrderID, vendorStoreID string) (order *model.GoodsOrder, err error) {
	resultOrders, err := api.JdShopAPI.AllOrders(&jdshopapi.AllOrdersParam{
		OrderID:  vendorOrderID,
		Current:  1,
		PageSize: 10,
	})
	if err != nil {
		return nil, err
	}
	return p.Map2Order(utils.Struct2FlatMap(resultOrders)), err
}
func (p *PurchaseHandler) GetOrderStatus(vendorOrgCode, vendorOrderID string) (status int, err error) {
	//jdsOrder, err := GetJdsOrder(vendorOrderID, vendorOrgCode)
	//jdsOrder, err := GetJdsOrder2(vendorOrderID, vendorOrgCode)
	//r := regexp.MustCompile(`"orderState":"(.*)","orderType`)
	//if len(r.FindStringSubmatch(jdsOrder)) > 0 {
	//	return status2Jxstatus(r.FindStringSubmatch(jdsOrder)[1]), err
	//}
	if order, err := p.GetOrder(vendorOrgCode, vendorOrderID, ""); err == nil && order != nil {
		return order.Status, err
	}
	return 0, err
}

func (p *PurchaseHandler) AcceptOrRefuseOrder(order *model.GoodsOrder, isAcceptIt bool, userName string) (err error) {
	var (
		status int
		remark string
	)
	if isAcceptIt {
		status = model.OrderStatusAccepted
		//京东商城第二个号要自动接单
		if order.VendorOrgCode == "2" {
			err = getAPI(order.VendorOrgCode).SetOrderStateToWait(utils.Str2Int64(order.VendorOrderID2))
		}
	} else {
		status = model.OrderStatusCanceled
	}
	return ChangeOrderStatus(order.VendorOrderID, status, remark)
}
func (p *PurchaseHandler) PickupGoods(order *model.GoodsOrder, isSelfDelivery bool, userName string) (err error) {
	status, err := p.GetOrderStatus(order.VendorOrgCode, order.VendorOrderID2)
	if err != nil {
		return err
	}
	//说明此时该订单在平台上已经取消了
	if status == model.OrderStatusCanceled {
		err = ChangeOrderStatus(order.VendorOrderID, model.OrderStatusCanceled, "订单在京东商城已被取消！")
	} else {
		if jxutils.GetSaleStoreIDFromOrder(order) != model.JdShopMainStoreID {
			//可能还没接单？
			if status == model.OrderStatusNew {
				p.AcceptOrRefuseOrder(order, true, "")
			}
			err = ChangeOrderStatus(order.VendorOrderID, model.OrderStatusFinishedPickup, "自动拣货完成")
			//if status == model.OrderStatusAccepted {
			err = p.OrderExport(jxcontext.AdminCtx, order.VendorOrderID, order.VendorOrderID, true)
			//}
		}
	}
	return err
}

func (p *PurchaseHandler) CallCourier(ctx *jxcontext.Context, order *model.GoodsOrder) (err error) {
	return err
} // 取货失败后再次招唤平台配送
func (p *PurchaseHandler) ConfirmReceiveGoods(ctx *jxcontext.Context, order *model.GoodsOrder) (err error) {
	return err
} // 投递失败后确认收到退货
func (p *PurchaseHandler) CanSwitch2SelfDeliver(order *model.GoodsOrder) (isCan bool, err error) {
	return isCan, err
}
func (p *PurchaseHandler) Swtich2SelfDeliver(order *model.GoodsOrder, userName string) (err error) {
	return err
}
func (p *PurchaseHandler) Swtich2SelfDelivered(order *model.GoodsOrder, userName string) (err error) {
	return err
}
func (p *PurchaseHandler) SelfDeliverDelivering(order *model.GoodsOrder, userName string) (err error) {
	ChangeOrderStatus(order.VendorOrderID, model.OrderStatusDelivering, "")
	return err
}
func (p *PurchaseHandler) SelfDeliverDelivered(order *model.GoodsOrder, userName string) (err error) {
	ChangeOrderStatus(order.VendorOrderID, model.OrderStatusFinished, "")
	if order.VendorOrgCode == "2" {
		getAPI(order.VendorOrgCode).SetOrderStateToFinish(utils.Str2Int64(order.VendorOrderID2))
	}
	return err
}
func (p *PurchaseHandler) GetOrderRealMobile(ctx *jxcontext.Context, order *model.GoodsOrder) (mobile string, err error) {
	return mobile, err
}
func (p *PurchaseHandler) ReplyOrderComment(ctx *jxcontext.Context, vendorOrgCode string, orderComment *model.OrderComment, replyComment string) (err error) {
	return err
}
func (p *PurchaseHandler) AgreeOrRefuseCancel(ctx *jxcontext.Context, order *model.GoodsOrder, isAgree bool, reason string,refundParam interface{}) (err error) {
	return err
}
func (p *PurchaseHandler) CancelOrder(ctx *jxcontext.Context, order *model.GoodsOrder, reason string) (err error) {
	ChangeOrderStatus(order.VendorOrderID, model.OrderStatusCanceled, reason)
	if order.EclpOutID != "" {
		_, err = api.JdEclpAPI.CancelOrder(order.EclpOutID)
	}
	return err
}
func (p *PurchaseHandler) AdjustOrder(ctx *jxcontext.Context, order *model.GoodsOrder, removedSkuList []*model.OrderSku, reason string) (err error) {
	var (
		db            = dao.GetDB()
		diffShopPrice int64
		diffSalePrice int64
	)
	if order.Status >= model.OrderStatusDelivering {
		return fmt.Errorf("配送中以后的订单无法进行售前退款！")
	}
	//1、删除原order_sku 中售前调整的商品
	for _, sku := range removedSkuList {
		sql := `DELETE FROM order_sku WHERE vendor_order_id = ? AND vendor_id = ? AND sku_id = ?`
		sqlParams := []interface{}{order.VendorOrderID, order.VendorID, sku.SkuID}
		dao.ExecuteSQL(db, sql, sqlParams)

		diffShopPrice += sku.ShopPrice
		diffSalePrice += sku.SalePrice
	}
	//2、修改goods_order 中的shopprice,若是扣点的订单，还要改new_earning_price和total_shop_money
	order.AdjustCount += 1
	order.ShopPrice = order.ShopPrice - diffShopPrice
	if order.EarningType == model.EarningTypePoints {
		order.TotalShopMoney = utils.Float64TwoInt64(float64(float64(order.TotalShopMoney)/jdshopapi.JdsPayPercentage-float64(diffSalePrice)) * jdshopapi.JdsPayPercentage)
		jxutils.RefreshOrderEarningPrice2(order, order.OrderPayPercentage)
		partner.CurOrderManager.UpdateOrderFields(order, []string{"TotalShopMoney", "NewEarningPrice"})
	}
	partner.CurOrderManager.UpdateOrderFields(order, []string{"AdjustCount", "ShopPrice"})
	return err
}

func (p *PurchaseHandler) GetJdsOrders(ctx *jxcontext.Context, orderCreatedStart, orderCreatedEnd string, current, pageSize int) (orderResult *jdshopapi.AllOrdersResult, err error) {
	jdsapi := getAPI("2")
	orderResult, err = jdsapi.AllOrders(&jdshopapi.AllOrdersParam{
		Current:              current,
		PageSize:             pageSize,
		OrderCreateDateRange: []string{orderCreatedStart, orderCreatedEnd},
	})
	return orderResult, err
}

func ChangeOrderStatus(vendorOrderID string, status int, remark string) (err error) {
	orderStatus := &model.OrderStatus{
		VendorOrderID:    vendorOrderID,
		VendorID:         model.VendorIDJDShop,
		OrderType:        model.OrderTypeOrder,
		RefVendorOrderID: vendorOrderID,
		RefVendorID:      model.VendorIDJDShop,
		VendorStatus:     utils.Int2Str(status),
		Status:           status,
		StatusTime:       time.Now(),
		Remark:           remark,
	}
	jxutils.CallMsgHandlerAsync(func() {
		err = partner.CurOrderManager.OnOrderStatusChanged("", orderStatus)
	}, jxutils.ComposeUniversalOrderID(vendorOrderID, model.VendorIDJDShop))
	return err
}

func (p *PurchaseHandler) OrderExport(ctx *jxcontext.Context, vendorOrderID, vendorWaybillID string, isAuto bool) (err error) {
	companyID := jdshopapi.JdsDeliveryCompany3rd
	//表示是门店手动发京东
	if !isAuto {
		companyID = jdshopapi.JdsDeliveryCompanyJD
	}
	if order, _ := partner.CurOrderManager.LoadOrder(vendorOrderID, model.VendorIDJDShop); order != nil {
		err = getAPI(order.VendorOrgCode).OrderShipment(utils.Str2Int64(order.VendorOrderID2), companyID, vendorWaybillID)
	}
	return err
}

func (p *PurchaseHandler) OrderTransfer(ctx *jxcontext.Context, vendorOrderID, vendorWaybillID string, isAuto bool) (err error) {
	companyID := jdshopapi.JdsDeliveryCompany3rd
	//表示是门店手动发京东
	if !isAuto {
		companyID = jdshopapi.JdsDeliveryCompanyJD
	}
	err = api.JdShopAPI.UpdateWaybill(vendorOrderID[:12], companyID, vendorOrderID)
	return err
}

func status2Jxstatus(status int) (statusJx int) {
	//if status == jdshopapi.OrderStatusPopPause || status == jdshopapi.OrderStatusPause {
	//	statusJx = model.OrderStatusNew
	//} else if status == jdshopapi.OrderStatusWait {
	//	statusJx = model.OrderStatusAccepted
	//} else if status == jdshopapi.OrderStatusCancel {
	//	statusJx = model.OrderStatusCanceled
	//}
	if status == jdshopapi.OrderStatusFinishedPickup {
		statusJx = model.OrderStatusAccepted
	} else if status == jdshopapi.OrderStatusNew {
		statusJx = model.OrderStatusNew
	} else if status == jdshopapi.OrderStatusCancelm2 {
		statusJx = model.OrderStatusCanceled
	}
	return statusJx
}

const (
	ProdURL = "http://116.196.82.188:8080/v2/"
)

func apiToYd(url string, params map[string]interface{}) (retVal map[string]interface{}, err error) {
	cl := &http.Client{}
	err = platformapi.AccessPlatformAPIWithRetry(cl,
		func() *http.Request {
			request, _ := http.NewRequest(http.MethodPost, ProdURL+url, strings.NewReader(utils.Map2URLValues(params).Encode()))
			request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			return request
		},
		nil,
		func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
			if jsonResult1 == nil {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
			}
			if err == nil {
				if jsonResult1["code"] != nil {
					if utils.Interface2Int64WithDefault(jsonResult1["code"], 0) != 0 {
						errLevel = platformapi.ErrLevelGeneralFail
						err = utils.NewErrorCode(jsonResult1["desc"].(string), jsonResult1["code"].(string))
						baseapi.SugarLogger.Debugf("yd AccessAPI failed, jsonResult1:%s", utils.Format4Output(jsonResult1, true))
					}
				}
				retVal = jsonResult1
			}
			return errLevel, err
		})
	return retVal, err
}

func GetJdsOrder(vendorOrderID, vendorOrgCode string) (jdsOrder *jdshopapi.GetEnOrderResult, err error) {
	jdmcshopapi := jdshopapi.New("f9c5ce9a5ce24218936924f7c4864cc9owe1", "E1D746D42474D5F1F1A10CECE75D99F6", "efa7e1d1a22640fa990e6cf164b28608")
	result, err := jdmcshopapi.GetOrderById(utils.Str2Int64(vendorOrderID[0:12]), false)
	if err != nil {
		return nil, err
	}
	return result, err
}

func GetJdsOrder2(vendorOrderID, vendorOrgCode string) (jdsOrder string, err error) {
	params := make(map[string]interface{})
	params["orderID"] = vendorOrderID
	params["token"] = jdshopapi.JdsYdToken
	params["vendorOrgCode"] = vendorOrgCode
	result, err := apiToYd("order/GetJdsOrder", params)
	//jdsOrder2 := &jdshopapi.GetOrderResult{}
	return strings.ReplaceAll(result["data"].(string), "\\", ""), err
}

func (c *PurchaseHandler) GetSelfTakeCode(ctx *jxcontext.Context, order *model.GoodsOrder) (selfTakeCode string, err error) {
	return selfTakeCode, err
}

func (c *PurchaseHandler) ConfirmSelfTake(ctx *jxcontext.Context, order *model.GoodsOrder, selfTakeCode string) (err error) {
	return err
}

func (c *PurchaseHandler) ListOrders(ctx *jxcontext.Context, vendorOrgCode string, parentTask tasksch.ITask, queryDate time.Time, vendorStoreID string) (vendorOrderIDs []string, err error) {
	return vendorOrderIDs, err
}

func (c *PurchaseHandler) ComplaintRider(vendorOrderId string, resonID int, resonContent string) (err error) {
	return err
}

// 转自配送时取消非专送混合送门店取消理由
func (c *PurchaseHandler) GetCancelDeliveryReason(order *model.GoodsOrder) (string, error) {
	return "", nil
}

// 取消美团外卖理由转使用三方配送
func (c *PurchaseHandler) CancelLogisticsByWmOrderId(order *model.GoodsOrder, reasonCode, detailContent, appPoiCode, orderId string) error {
	return nil
}

// 获取订单配送状态
func (c *PurchaseHandler) OrderLogisticsStatus(orderId string) (*utils.RiderInfo, error) {
	return nil, nil
}

// GetOrderSettleAccounts 获取订单结算信息
func (c *PurchaseHandler) GetOrderSettleAccounts(order *model.GoodsOrder) (int64, error) {
	return 0, nil
}

// GetPlatformLogisticsFee 获取自配送订单的配送费
func (c *PurchaseHandler) GetPlatformLogisticsFee(order *model.GoodsOrder) (int64, error) {
	return 0, nil
}

// ApplyCompensationOrder 订单索赔
func (c *PurchaseHandler) ApplyCompensationOrder(order *model.GoodsOrder) (string, error) {
	return "", nil
}

// UploadInvoice 回复用户发票申请
func (c *PurchaseHandler) UploadInvoice(param *model.InvoiceMsg, base64 string) ([]string, []string, error) {
	return nil, nil, nil
}

// UploadPickingImg  上传拣货图片
func (c *PurchaseHandler) UploadPickingImg(order *model.GoodsOrder, imgList interface{}) error {
	return nil
}
