package controllers

import (
	"encoding/json"
	"errors"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/ebaiapi"
	"git.rosy.net.cn/jx-callback/business/auth2"
	"git.rosy.net.cn/jx-callback/business/bidding"
	"git.rosy.net.cn/jx-callback/business/jxstore/cms"
	"git.rosy.net.cn/jx-callback/business/jxstore/permission"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/partner/delivery"
	"git.rosy.net.cn/jx-callback/business/partner/printer/jxprint"
	"git.rosy.net.cn/jx-callback/business/partner/purchase/ebai"
	"strings"
	"time"

	"git.rosy.net.cn/jx-callback/business/partner"

	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxcallback/orderman"
	"git.rosy.net.cn/jx-callback/business/jxcallback/scheduler/defsch"
	"git.rosy.net.cn/jx-callback/business/jxstore/misc"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"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"
	"github.com/astaxie/beego/server/web"
)

// 订单相关API
type OrderController struct {
	web.Controller
}

func (c *OrderController) URLMapping() {
	c.Mapping("GetOrderSkuInfo", c.GetOrderSkuInfo)

	c.Mapping("FinishedPickup", c.FinishedPickup)
	c.Mapping("SelfDelivering", c.SelfDelivering)
	c.Mapping("CreateWaybillOnProviders", c.CreateWaybillOnProviders)
	c.Mapping("SelfDelivered", c.SelfDelivered)
}

// @Title 完成拣货
// @Description 完成拣货
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属的厂商ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /FinishedPickup [post]
func (c *OrderController) FinishedPickup() {
	c.callFinishedPickup(func(params *tOrderFinishedPickupParams) (retVal interface{}, errCode string, err error) {
		err = defsch.FixedScheduler.PickupGoodsAndUpdateStatus(params.Ctx, params.VendorOrderID, params.VendorID, params.Ctx.GetUserName())
		return nil, "", err
	})
}

// @Title 转自送
// @Description 转自送，对于配送类型为纯自送的，就是表示自送开始
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属的厂商ID"
// @Param	courierName		formData	string	false	"骑手姓名-制作假配送"
// @Param	courierMobile	formData	string	false	"骑手电话-制作假配送"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /SelfDelivering [post]
func (c *OrderController) SelfDelivering() {
	c.callSelfDelivering(func(params *tOrderSelfDeliveringParams) (retVal interface{}, errCode string, err error) {
		err = defsch.FixedScheduler.SelfDeliveringAndUpdateStatus(params.Ctx, params.VendorOrderID, params.VendorID, params.Ctx.GetUserName(), params.CourierName, params.CourierMobile)
		return nil, "", err
	})
}

// @Title 自送送达
// @Description 自送送达
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属的厂商ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /SelfDelivered [post]
func (c *OrderController) SelfDelivered() {
	c.callSelfDelivered(func(params *tOrderSelfDeliveredParams) (retVal interface{}, errCode string, err error) {
		bills, _ := dao.GetWaybills(dao.GetDB(), params.VendorOrderID, nil)
		for _, b := range bills {
			if b.WaybillVendorID == model.VendorJXFakeWL && b.Status < model.OrderStatusDelivering {
				return nil, "-1", fmt.Errorf("物流单正在同步回传率,请稍后再点击送达")
			}
		}

		err = defsch.FixedScheduler.SelfDeliveredAndUpdateStatus(params.Ctx, params.VendorOrderID, params.VendorID, params.Ctx.GetUserName())
		return nil, "", err
	})
}

// @Title 自送送达
// @Description 自送送达
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属的厂商ID"
// @Param	selfTakeCode	formData	string	true	"自提码"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /ConfirmSelfTake [post]
func (c *OrderController) ConfirmSelfTake() {
	c.callConfirmSelfTake(func(params *tOrderConfirmSelfTakeParams) (retVal interface{}, errCode string, err error) {
		err = defsch.FixedScheduler.ConfirmSelfTake(params.Ctx, params.VendorOrderID, params.VendorID, params.SelfTakeCode)
		return retVal, "", err
	})
}

// @Title 查询三方运单费用信息
// @Description 查询三方运单费用信息
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	query		string	true	"订单ID"
// @Param	vendorID		query		int		true	"订单所属的厂商ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /QueryOrderWaybillFeeInfo [get]
func (c *OrderController) QueryOrderWaybillFeeInfo() {
	c.callQueryOrderWaybillFeeInfo(func(params *tOrderQueryOrderWaybillFeeInfoParams) (retVal interface{}, errCode string, err error) {
		retVal, err = defsch.FixedScheduler.QueryOrderWaybillFeeInfoEx(params.Ctx, params.VendorOrderID, params.VendorID)
		return retVal, "", err
	})
}

// @Title 创建三方运单
// @Description 创建三方运单
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属的厂商ID"
// @Param	courierVendorIDs formData	string	false	"运单厂商ID（缺省全部）"
// @Param	maxAddFee		formData	int		false	"最高限价（为0时为缺省最大值）"
// @Param	forceCreate		formData	bool	false	"是否强制创建（忽略订单状态检查及其它参数）"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /CreateWaybillOnProviders [post]
func (c *OrderController) CreateWaybillOnProviders() {
	c.callCreateWaybillOnProviders(func(params *tOrderCreateWaybillOnProvidersParams) (retVal interface{}, errCode string, err error) {
		var courierVendorIDs []int
		if err = jxutils.Strings2Objs(params.CourierVendorIDs, &courierVendorIDs); err == nil {
			if params.MaxAddFee >= 5000 {
				return nil, "", errors.New("部分运单金额大于50元,请核对")
			}
			retVal, errCode, err = defsch.FixedScheduler.CreateWaybillOnProvidersEx(params.Ctx, params.VendorOrderID, params.VendorID, courierVendorIDs, params.ForceCreate, int64(params.MaxAddFee))
		}
		return retVal, errCode, err
	})
}

// @Title 取消所有三方运单
// @Description 取消所有三方运单
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属的厂商ID"
// @Param	isStopSchedule	formData	bool	false	"是否停止运单调度"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /CancelAll3rdWaybills [post]
func (c *OrderController) CancelAll3rdWaybills() {
	c.callCancelAll3rdWaybills(func(params *tOrderCancelAll3rdWaybillsParams) (retVal interface{}, errCode string, err error) {
		// 取消三方运单时,停止运单调度.不在自动发配送
		//err = defsch.FixedScheduler.CancelAll3rdWaybills(params.Ctx, params.VendorOrderID, params.VendorID, params.IsStopSchedule)
		err = defsch.FixedScheduler.CancelAll3rdWaybills(params.Ctx, params.VendorOrderID, params.VendorID, true)
		return retVal, "", err
	})
}

// @Title 取消三方运单
// @Description 取消三方运单
// @Param	token			header		string	true	"认证token"
// @Param	vendorWaybillID	formData	string	true	"运单ID"
// @Param	waybillVendorID	formData	int		true	"运单所属的厂商ID"
// @Param	reasonID	formData	int		false	"原因ID"
// @Param	reason		formData	string	false	"取消原因"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /CancelWaybill [post]
func (c *OrderController) CancelWaybill() {
	c.callCancelWaybill(func(params *tOrderCancelWaybillParams) (retVal interface{}, errCode string, err error) {
		reasonID := params.ReasonID
		if reasonID == 0 {
			reasonID = partner.CancelWaybillReasonOther
		}
		err = defsch.FixedScheduler.CancelWaybillByID(params.Ctx, params.VendorWaybillID, params.WaybillVendorID, reasonID, params.Reason)
		return retVal, "", err
	})
}

// @Title 得到门店订单信息
// @Description 得到门店订单信息
// @Param	token		header	string	true	"认证token"
// @Param	storeID		query	int		true	"京西门店ID"
// @Param	lastHours	query	int		false	"最近多少小时的信息（缺省为两天）"
// @Param	lastMinutes	query	int		false	"最近多少分钟的信息（缺省为不传）"
// @Param	isIncludeFake	query	bool	false	"是否包括假订单"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetStoreOrderCountInfo [get]
func (c *OrderController) GetStoreOrderCountInfo() {
	c.callGetStoreOrderCountInfo(func(params *tOrderGetStoreOrderCountInfoParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.FixedOrderManager.GetStoreOrderCountInfo(params.Ctx, params.StoreID, params.LastHours, params.LastMinutes, params.IsIncludeFake)
		return retVal, "", err
	})
}

// @Title 得到订单SKU信息
// @Description 得到订单SKU信息
// @Param	token			header	string	true	"认证token"
// @Param	vendorOrderID	query	string	true	"订单ID"
// @Param	vendorID		query	int		true	"订单所属的厂商ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetOrderSkuInfo [get]
func (c *OrderController) GetOrderSkuInfo() {
	c.callGetOrderSkuInfo(func(params *tOrderGetOrderSkuInfoParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.FixedOrderManager.GetOrderSkuInfo(params.Ctx, params.VendorOrderID, params.VendorID)
		return retVal, "", err
	})
}

// @Title 得到订单详情
// @Description 得到订单详情
// @Param	token			header	string	true	"认证token"
// @Param	vendorOrderID	query	string	true	"订单ID"
// @Param	vendorID		query	int		true	"订单所属的厂商ID"
// @Param	refresh			query	bool	false	"是否从购物平台刷新数据"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetOrderInfo [get]
func (c *OrderController) GetOrderInfo() {
	c.callGetOrderInfo(func(params *tOrderGetOrderInfoParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.FixedOrderManager.GetOrderInfo(params.Ctx, params.VendorOrderID, params.VendorID, params.Refresh)
		return retVal, "", err
	})
}

// @Title 得到订单运单信息
// @Description 得到订单运单信息
// @Param	token			header	string	true	"认证token"
// @Param	vendorOrderID	query	string	true	"订单ID"
// @Param	vendorID		query	int		true	"订单所属的厂商ID"
// @Param	isNotEnded		query	bool	false	"是否只是没有结束的运单"
// @Param	isGetPos		query	bool	false	"是否得到骑手位置"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetOrderWaybillInfo [get]
func (c *OrderController) GetOrderWaybillInfo() {
	c.callGetOrderWaybillInfo(func(params *tOrderGetOrderWaybillInfoParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.FixedOrderManager.GetOrderWaybillInfo(params.Ctx, params.VendorOrderID, params.VendorID, params.IsNotEnded, params.IsGetPos)
		return retVal, "", err
	})
}

// @Title 加小费
// @Description 加小费
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属的厂商ID"
// @Param	tipFee			formData	int		true	"小费"
// @Param	isPay			formData	int		false	"是否确认支付[1是]"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /UpdateOrderWaybillTip [post]
func (c *OrderController) UpdateOrderWaybillTip() {
	c.callUpdateOrderWaybillTip(func(params *tOrderUpdateOrderWaybillTipParams) (retVal interface{}, errCode string, err error) {
		errCode, err = defsch.FixedScheduler.SetOrderWaybillTip(params.Ctx, params.VendorOrderID, params.VendorID, int64(params.TipFee), params.IsPay)
		return retVal, "", err
	})
}

// @Title 导出美团运单
// @Description 导出美团运单（excel文件），注意时间跨度不要太长，最多只能是一个月
// @Param	token			header	string	true	"认证token"
// @Param	fromDate		query	string	true	"开始日期（包含），格式（2006-01-02）"
// @Param	toDate			query	string	false	"结束日期（包含），格式（2006-01-02）"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /ExportMTWaybills [get]
func (c *OrderController) ExportMTWaybills() {
	var content []byte
	var fromDate, toDate string
	c.callExportMTWaybills(func(params *tOrderExportMTWaybillsParams) (retVal interface{}, errCode string, err error) {
		fromDate = params.FromDate
		toDate = params.ToDate
		if toDate == "" {
			toDate = fromDate
		}
		content, err = orderman.FixedOrderManager.ExportMTWaybills(params.Ctx, params.FromDate, params.ToDate)
		return retVal, model.ErrorCodeIgnore, err
	})
	if content != nil {
		c.Ctx.ResponseWriter.Header().Set("Content-Type", "application/vnd.ms-excel")
		fileName := strings.Replace(fmt.Sprintf("attachment;filename=美团运单表%s至%sat%s.xlsx", fromDate, toDate, utils.Time2Str(time.Now())), " ", "-", 1)
		c.Ctx.ResponseWriter.Header().Set("content-disposition", fileName)
		c.Ctx.ResponseWriter.Write(content)
	}
}

// @Title 查询订单
// @Description 查询订单
// @Param	token			header	string	true	"认证token"
// @Param	orderID			query	string	false	"订单号，如果此项不为空，忽略其它所有查询条件（此项会废弃，用vendorOderID）"
// @Param	vendorOrderID	query	string	false	"订单号，如果此项不为空，忽略其它所有查询条件"
// @Param	keyword			query	string	false	"查询关键字"
// @Param	fromDate		query	string	false	"开始日期（包含），格式（2006-01-02），如果订单号为空此项必须要求"
// @Param	toDate			query	string	false	"结束日期（包含），格式（2006-01-02），如果订单号为空此项必须要求"
// @Param	isDateFinish	query	bool	false	"是否fromDate与toDate指的是订单结束日期，缺省不是"
// @Param	vendorIDs		query	string	false	"订单所属厂商列表[1,2,3]，缺省不限制"
// @Param	waybillVendorIDs query	string		false	"承运人所属厂商列表[1,2,3]，缺省不限制"
// @Param	storeIDs		query	string	false	"京西门店ID列表[1,2,3]，缺省不限制"
// @Param	fromStoreIDs	query	string	false	"物料京西门店ID列表[1,2,3]，缺省不限制"
// @Param	statuss			query	string	false	"订单状态列表[1,2,3]，缺省不限制"
// @Param	lockStatuss		query	string	false	"订单锁定状态列表[1,2,3]，缺省不限制"
// @Param	cities			query	string	false	"城市code列表[1,2,3]，缺省不限制"
// @Param	isIncludeFake	query	bool	false	"是否包括假订单"
// @Param	skuIDs			query	string	false	"包含的skuID列表，或的关系"
// @Param	isJxFirst		query	bool	false	"排序是否京西订单优先（缺省为否）"
// @Param	adjustCount		query	int		false	"最小调整次数"
// @Param	brandID			query	int		false	"品牌ID"
// @Param	mustInvoice		query	bool	false	"是否必须要求开发票"
// @Param	deliveryTypes	query	string	false	"配送方式"
// @Param	jxIncomeBegin	query	string	false	"预计收入begin"
// @Param	jxIncomeEnd		query	string	false	"预计收入end"
// @Param	marketManPhone	query	string	false	"平台负责人"
// @Param	jdPhone			query	string	false	"京东负责人电话"
// @Param	mtPhone			query	string	false	"美团负责人电话"
// @Param	ebaiPhone		query	string	false	"饿百负责人电话"
// @Param	offset			query	int		false	"结果起始序号（以0开始，缺省为0）"
// @Param	pageSize		query	int		false	"结果页大小（缺省为50，-1表示全部）"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetOrders [get,post]
func (c *OrderController) GetOrders() {
	c.callGetOrders(func(params *tOrderGetOrdersParams) (retVal interface{}, errCode string, err error) {
		var skuIDs []int
		if err = jxutils.Strings2Objs(params.SkuIDs, &skuIDs); err == nil {
			retVal, err = orderman.FixedOrderManager.GetOrders(params.Ctx, params.IsIncludeFake, params.FromDate, params.ToDate, params.IsDateFinish, skuIDs, params.IsJxFirst, params.MapData, params.Offset, params.PageSize)
		}
		return retVal, "", err
	})
}

// @Title 导出订单（包括SKU信息）
// @Description 导出订单（包括SKU信息）
// @Param	token			header	string	true	"认证token"
// @Param	orderID			query	string	false	"订单号，如果此项不为空，忽略其它所有查询条件（此项会废弃，用vendorOderID）"
// @Param	vendorOrderID	query	string	false	"订单号，如果此项不为空，忽略其它所有查询条件"
// @Param	keyword			query	string	false	"查询关键字"
// @Param	fromDate		query	string	false	"开始日期（包含），格式（2006-01-02），如果订单号为空此项必须要求"
// @Param	toDate			query	string	false	"结束日期（包含），格式（2006-01-02），如果订单号为空此项必须要求"
// @Param	vendorIDs		query	string	false	"订单所属厂商列表[1,2,3]，缺省不限制"
// @Param	waybillVendorIDs	query	string		false	"承运人所属厂商列表[1,2,3]，缺省不限制"
// @Param	storeIDs		query	string	false	"京西门店ID列表[1,2,3]，缺省不限制"
// @Param	statuss			query	string	false	"订单状态列表[1,2,3]，缺省不限制"
// @Param	lockStatuss		query	string	false	"订单锁定状态列表[1,2,3]，缺省不限制"
// @Param	cities			query	string	false	"城市code列表[1,2,3]，缺省不限制"
// @Param	isAsync			query	bool	false	"是否异步"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router  /ExportOrders [get]
func (c *OrderController) ExportOrders() {
	c.callExportOrders(func(params *tOrderExportOrdersParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.FixedOrderManager.ExportOrders(params.Ctx, params.FromDate, params.ToDate, params.MapData, params.IsAsync)
		return retVal, "", err
	})
}

// @Title 查询售后单
// @Description 查询售后单
// @Param	token			header	string	true	"认证token"
// @Param	afsOrderID		query	string	false	"售后单号，如果此项不为空，忽略其它所有查询条件"
// @Param	vendorOrderID	query	string	false	"订单号，如果此项不为空，忽略其它所有查询条件"
// @Param	vendorIDs		query	string	false	"订单所属厂商列表[1,2,3]，缺省不限制"
// @Param	appealTypes		query	string	false	"售后处理s方式列表"
// @Param	storeIDs		query	string	false	"京西门店ID列表[1,2,3]，缺省不限制"
// @Param	statuss			query	string	false	"订单状态列表[1,2,3]，缺省不限制"
// @Param	keyword			query	string	false	"查询关键字"
// @Param	fromTime		query	string	false	"开始时间，如果订单号为空此项必须要求"
// @Param	toTime			query	string	false	"结束时间，如果订单号为空此项必须要求"
// @Param	skuIDs			query	string	false	"包含的skuID列表，或的关系"
// @Param	isDetail		query	bool	false	"是否查详情"
// @Param	offset			query	int		false	"结果起始序号（以0开始，缺省为0）"
// @Param	pageSize		query	int		false	"结果页大小（缺省为50，-1表示全部）"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetAfsOrders [get,post]
func (c *OrderController) GetAfsOrders() {
	c.callGetAfsOrders(func(params *tOrderGetAfsOrdersParams) (retVal interface{}, errCode string, err error) {
		timeList, err := jxutils.BatchStr2Time(params.FromTime, params.ToTime)
		if err == nil {
			var vendorIDList, appealTypeList, storeIDList, statusList, skuIDs []int
			if err = jxutils.Strings2Objs(params.VendorIDs, &vendorIDList, params.AppealTypes, &appealTypeList,
				params.StoreIDs, &storeIDList, params.Statuss, &statusList, params.SkuIDs, &skuIDs); err == nil {
				retVal, err = orderman.FixedOrderManager.GetAfsOrders(params.Ctx, params.Keyword, params.AfsOrderID,
					params.VendorOrderID, vendorIDList, appealTypeList, storeIDList, statusList, skuIDs, timeList[0], timeList[1],
					params.IsDetail, params.Offset, params.PageSize)
			}
		}
		return retVal, "", err
	})
}

// @Title 得到售后单SKU信息
// @Description 得到售后单SKU信息（订单与售后单必填一项）
// @Param	token			header	string	true	"认证token"
// @Param	vendorID		query	int		true	"售后单所属的厂商ID"
// @Param	vendorOrderID	query	string	false	"订单ID"
// @Param	afsOrderID		query	string	false	"售后单ID"
// @Param	isNotFaild		query	bool	false	"是否查非失败的"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetAfsOrderSkuInfo [get]
func (c *OrderController) GetAfsOrderSkuInfo() {
	c.callGetAfsOrderSkuInfo(func(params *tOrderGetAfsOrderSkuInfoParams) (retVal interface{}, errCode string, err error) {
		retVal, err = dao.GetAfsOrderSkuInfo(dao.GetDB(), params.VendorOrderID, params.AfsOrderID, params.VendorID, params.IsNotFaild)
		return retVal, "", err
	})
}

// @Title 查询运单
// @Description 查询运单
// @Param	token			header	string	true	"认证token"
// @Param	keyword			query	string	false	"查询关键字"
// @Param	fromDate		query	string	true	"开始日期（包含），格式（2006-01-02）"
// @Param	toDate			query	string	false	"结束日期（包含），格式（2006-01-02）"
// @Param	waybillVendorIDs	query	string		false	"承运人所属厂商列表[1,2,3]，缺省不限制"
// @Param	statuss			query	string	false	"运单状态列表[1,2,3]，缺省不限制"
// @Param	offset			query	int		false	"结果起始序号（以0开始，缺省为0）"
// @Param	pageSize		query	int		false	"结果页大小（缺省为50，-1表示全部）"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetWaybills [get]
func (c *OrderController) GetWaybills() {
	c.callGetWaybills(func(params *tOrderGetWaybillsParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.FixedOrderManager.GetWaybills(params.Ctx, params.FromDate, params.ToDate, params.MapData, params.Offset, params.PageSize)
		return retVal, "", err
	})
}

// @Title 查询订单/运单事件
// @Description 查询订单/运单事件
// @Param	token			header	string	true	"认证token"
// @Param	vendorOrderID	query	string	true	"订单/运单ID"
// @Param	vendorID		query	int		true	"订单/运单所属厂商ID）"
// @Param	orderType		query	int		true	"订单：1；运单：2；订单+运单：-1"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetOrderStatusList [get]
func (c *OrderController) GetOrderStatusList() {
	c.callGetOrderStatusList(func(params *tOrderGetOrderStatusListParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.FixedOrderManager.GetOrderStatusList(params.Ctx, params.VendorOrderID, params.VendorID, params.OrderType)
		return retVal, "", err
	})
}

// @Title 加载物流信息(物料单子加载物流配送流程)
// @Description 加载物流信息(物料单子加载物流配送流程)
// @Param	token			header			string	true	"认证token"
// @Param   data            body  			string 	true 	"物流参数"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /LoadingLogisticsStatus [post]
func (c *OrderController) LoadingLogisticsStatus() {
	c.callLoadingLogisticsStatus(func(params *tOrderLoadingLogisticsStatusParams) (interface{}, string, error) {
		var param = make([]*model.UpdateMaterialLogistic, 0, 0)
		if err := json.Unmarshal([]byte(params.Data), &param); err != nil {
			return nil, "", err
		}
		errList := bidding.LoadingLogistics(param)
		return errList, "", nil
	})
}

// @Title 查询门店营业数据
// @Description 查询门店营业数据
// @Param	token			header	string	true	"认证token"
// @Param	storeIDs		query	string	false	"京西门店ID列表[1,2,3]，缺省不限制"
// @Param	fromTime		query	string	true	"起始时间"
// @Param	toTime			query	string	true	"结束时间"
// @Param	statuss			query	string	false	"订单状态列表[1,2,3]，缺省不限制"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetStoresOrderSaleInfo [get]
func (c *OrderController) GetStoresOrderSaleInfo() {
	c.callGetStoresOrderSaleInfo(func(params *tOrderGetStoresOrderSaleInfoParams) (retVal interface{}, errCode string, err error) {
		timeList, err := jxutils.BatchStr2Time(params.FromTime, params.ToTime)
		if err == nil {
			var storeIDList []int
			var statusList []int
			if err = jxutils.Strings2Objs(params.StoreIDs, &storeIDList, params.Statuss, &statusList); err == nil {
				retVal, err = orderman.FixedOrderManager.GetStoresOrderSaleInfo(params.Ctx, storeIDList, timeList[0], timeList[1], statusList)
			}
		}
		return retVal, "", err
	})
}

// @Title 首页统计信息[(营业门店,休息门店,禁用门店),(订单状态订单数量统计,售后单+时间),(预计收益)]
// @Description 首页统计信息
// @Param	token			header	string	true	"认证token"
// @Param	fromTime		query	string	true	"起始时间"
// @Param	toTime			query	string	true	"结束时间"
// @Param	brandIds		query	string	false	"品牌id"
// @Param	vendorIds		query	string	false	"平台id"
// @Param	storeID			query	int		false	"门店id"
// @Param	operatorNumber	query	string	false	"门店负责人"
// @Param	brandOperator	query	string	false	"美团负责人"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /StaleIndexInfo [get]
func (c *OrderController) StaleIndexInfo() {
	c.callStaleIndexInfo(func(params *tOrderStaleIndexInfoParams) (retVal interface{}, code string, err error) {
		var (
			storeList   []*dao.StoreWithCityName
			dataList    = make([]int, 0, len(storeList))
			mapDataList = make(map[int]int, len(storeList))
			vendors     []int
			brandIds    []int
		)

		timeList, err := jxutils.BatchStr2Time(params.FromTime, params.ToTime)
		if err != nil {
			return nil, "", err
		}
		if len(timeList) == 2 {
			timeList[1].Add((24*60 - 1) * time.Minute)
		}

		ctx := params.Ctx
		if !auth2.IsV2Token(ctx.GetToken()) {
			return nil, model.ErrCodeTokenIsInvalid, model.ErrTokenIsInvalid
		}
		mobile, userID := ctx.GetMobileAndUserID()
		if mobile == "" || userID == "" || userID == "null" || userID == "NULL" {
			return nil, "", fmt.Errorf("不能得到用户手机号,%s,%s", userID, mobile)
		}

		if permission.IsRoled(ctx) {
			if (params.OperatorNumber != "" && params.OperatorNumber != mobile) || (params.BrandOperator != "" && params.BrandOperator != mobile) {
				return nil, "", fmt.Errorf("非超级管理员账户,只能查看自己")
			}
			if storeList, err = cms.GetStoreList4User(ctx, mobile, userID); err == nil && len(storeList) > 0 {
				for _, v := range storeList {
					dataList = append(dataList, v.Store.ID)
					mapDataList[v.Store.ID] = model.YES
				}
			}
			if params.StoreID != 0 && mapDataList[params.StoreID] != model.YES {
				return retVal, "", fmt.Errorf("此门店%d,不归属于该用户%s", params.StoreID, ctx.GetUserName())
			}
		}

		if err := jxutils.Strings2Objs(params.VendorIds, &vendors, params.BrandIds, &brandIds); err != nil {
			return retVal, "", err
		}

		if permission.IsRoled(ctx) && len(dataList) == model.NO {
			return retVal, "", fmt.Errorf("该用户%s,暂无门店信息", ctx.GetUserName())
		}

		retVal, err = orderman.FixedOrderManager.GetStoresOrderSaleInfo2(timeList[0], timeList[1], params.StoreID, brandIds, vendors, dataList, params.OperatorNumber, params.BrandOperator)
		return retVal, "", err
	})
}

// @Title 门店订单排行统计
// @Description 门店订单排行统计
// @Param	token			header	string	true	"认证token"
// @Param	start			query	string	true	"起始时间"
// @Param	end				query	string	true	"结束时间"
// @Param	storeID			query	string	false	"门店id,[1,2,3]"
// @Param	rank			query	string	true	"排序方式,订单中粮,[DESC,ASC]"
// @Param	offset			query	int		false	"门店列表起始序号（以0开始，缺省为0）"
// @Param	pageSize		query	int		false	"门店列表页大小（缺省为50，-1表示全部）"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /StoreOrderRank [get]
func (c *OrderController) StoreOrderRank() {
	c.callStoreOrderRank(func(params *tOrderStoreOrderRankParams) (retVal interface{}, code string, err error) {
		var (
			storeList   []*dao.StoreWithCityName
			dataList    = make([]int, 0, len(storeList))
			mapDataList = make(map[int]int, len(storeList))
		)
		timeList, err := jxutils.BatchStr2Time(params.Start, params.End)
		if err != nil {
			return nil, "", err
		}
		var storeIdList []int
		if err = jxutils.Strings2Objs(params.StoreID, &storeIdList); err != nil {
			return nil, "", err
		}

		ctx := params.Ctx
		if !auth2.IsV2Token(ctx.GetToken()) {
			return nil, model.ErrCodeTokenIsInvalid, model.ErrTokenIsInvalid
		}
		mobile, userID := ctx.GetMobileAndUserID()
		if mobile == "" || userID == "" || userID == "null" || userID == "NULL" {
			return nil, "", fmt.Errorf("不能得到用户手机号,%s,%s", userID, mobile)
		}

		if permission.IsRoled(ctx) {
			if storeList, err = cms.GetStoreList4User(ctx, mobile, userID); err == nil && len(storeList) > 0 {
				for _, v := range storeList {
					dataList = append(dataList, v.Store.ID)
					mapDataList[v.Store.ID] = model.YES
				}
			}
			if len(storeIdList) != model.NO {
				for _, sl := range storeIdList {
					if mapDataList[sl] != model.YES {
						return retVal, "", fmt.Errorf("此门店%d,不归属于该用户%s", sl, ctx.GetUserName())
					}
				}
			}
		}
		if len(storeIdList) == model.NO {
			storeIdList = dataList
		}
		retVal, count, err := dao.StaticStoreOrderChange(dao.GetDB(), storeIdList, timeList[0], timeList[1], params.Rank, params.Offset, params.PageSize)
		return map[string]interface{}{"data": retVal, "count": count}, "", err
	})
}

// @Title 刷新订单真实手机号
// @Description 刷新订单真实手机号
// @Param	token			header		string	true	"认证token"
// @Param	vendorID		formData	int		true	"厂商ID"
// @Param	fromTime		formData	string	true	"起始时间"
// @Param	toTime			formData	string	false	"结束时间"
// @Param	isAsync			formData	bool	true	"是否异步操作"
// @Param	isContinueWhenError	formData	bool	false	"单个同步失败是否继续，缺省false"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /RefreshOrderRealMobile [put]
func (c *OrderController) RefreshOrderRealMobile() {
	c.callRefreshOrderRealMobile(func(params *tOrderRefreshOrderRealMobileParams) (retVal interface{}, errCode string, err error) {
		timeList, err2 := jxutils.BatchStr2Time(params.FromTime, params.ToTime)
		if err = err2; err == nil {
			retVal, err = misc.RefreshRealMobile(params.Ctx, params.VendorID, timeList[0], timeList[1], params.IsAsync, params.IsContinueWhenError)
		}
		return retVal, "", err
	})
}

// @Title 刷新订单平台结算信息
// @Description 刷新订单平台结算信息
// @Param	token			header		string	true	"认证token"
// @Param	fromTime		formData	string	true	"起始时间"
// @Param	toTime			formData	string	false	"结束时间"
// @Param	isAsync			formData	bool	true	"是否异步操作"
// @Param	isContinueWhenError	formData	bool	false	"单个同步失败是否继续，缺省false"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /RefreshOrderFinancial [put]
func (c *OrderController) RefreshOrderFinancial() {
	c.callRefreshOrderFinancial(func(params *tOrderRefreshOrderFinancialParams) (retVal interface{}, errCode string, err error) {
		timeList, err2 := jxutils.BatchStr2Time(params.FromTime, params.ToTime)
		if err = err2; err == nil {
			retVal, err = orderman.FixedOrderManager.RefreshOrderFinancial(params.Ctx, timeList[0], timeList[1], params.IsAsync, params.IsContinueWhenError)
		}
		return retVal, "", err
	})
}

// @Title 设置订单打印状态
// @Description 同步商家SKU类别
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单/运单ID"
// @Param	vendorID		formData	int		true	"订单/运单所属厂商ID）"
// @Param	isPrinted		formData	bool	true	"是否打印"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /SetOrderPrintStatus [put]
func (c *OrderController) SetOrderPrintStatus() {
	c.callSetOrderPrintStatus(func(params *tOrderSetOrderPrintStatusParams) (retVal interface{}, errCode string, err error) {
		err = dao.SetOrderPrintFlag(dao.GetDB(), params.Ctx.GetUserName(), params.VendorOrderID, params.VendorID, params.IsPrinted)
		return retVal, "", err
	})
}

// @Title 网络打印订单
// @Description 网络打印订单
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单/运单ID"
// @Param	vendorID		formData	int		true	"订单/运单所属厂商ID）"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /PrintOrder [put]
func (c *OrderController) PrintOrder() {
	c.callPrintOrder(func(params *tOrderPrintOrderParams) (retVal interface{}, errCode string, err error) {
		retVal, err = netprinter.PrintOrder(params.Ctx, params.VendorOrderID, params.VendorID)
		return retVal, "", err
	})
}

// @Title 网络打印订单
// @Description 网络打印订单
// @Param	vendorOrderID	formData	string	true	"订单/运单ID"
// @Param	printType		formData	int		true	"打印类型[1-取消/0-售后]"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /PrintAfsOrderOrder [post]
func (c *OrderController) PrintAfsOrderOrder() {
	c.callPrintAfsOrderOrder(func(params *tOrderPrintAfsOrderOrderParams) (retVal interface{}, errCode string, err error) {
		order, err := dao.GetSimpleOrder(dao.GetDB(), params.VendorOrderID)
		if err != nil {
			return nil, "", err
		}
		_, err = netprinter.PrintRefundOrCancelOrder(jxcontext.AdminCtx, params.PrintType, order, order.JxStoreID)
		return nil, "", err
	})
}

// @Title 查询网络打印机状态
// @Description 查询网络打印机状态
// @Param	token			header		string	true	"认证token"
// @Param	storeID			query		int		true	"门店ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetPrinterStatus [get]
func (c *OrderController) GetPrinterStatus() {
	c.callGetPrinterStatus(func(params *tOrderGetPrinterStatusParams) (retVal interface{}, errCode string, err error) {
		retVal, err = netprinter.GetNetPrinterStatus(params.Ctx, params.StoreID)
		return retVal, "", err
	})
}

func skuList2Map(skuList []*model.OrderSku) (skuCount int, skuMap map[int64]*model.OrderSku, outSkuList []*model.OrderSku) {
	skuMap = make(map[int64]*model.OrderSku)
	for _, sku := range skuList {
		skuCount += sku.Count
		skuID := jxutils.GetSkuIDFromOrderSku(sku)
		if sku.SkuID > 0 {
			index := jxutils.Combine2Int(skuID, int(sku.StoreSubID))
			if skuMap[index] == nil {
				tmpSku := *sku
				skuMap[index] = &tmpSku
				outSkuList = append(outSkuList, skuMap[index])
			} else {
				skuMap[index].Count += sku.Count
			}
		}
	}
	return skuCount, skuMap, outSkuList
}

func getSkuFromMap(skuMap map[int64]*model.OrderSku, skuID, actID int) (sku *model.OrderSku) {
	if sku = skuMap[jxutils.Combine2Int(skuID, actID)]; sku == nil && actID != 0 {
		sku = skuMap[jxutils.Combine2Int(skuID, 0)]
	}
	return sku
}

// @Title 调整订单
// @Description 调整订单
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属厂商ID"
// @Param	removedSkuInfo	formData	string	true	"要去除的商品信息，只有skuID与Count字段有效"
// @Param	reason			formData	string	true	"调整原因"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /AdjustOrder [put]
func (c *OrderController) AdjustOrder() {
	c.callAdjustOrder(func(params *tOrderAdjustOrderParams) (retVal interface{}, errCode string, err error) {
		var skuList []*model.OrderSku
		err = jxutils.Strings2Objs(params.RemovedSkuInfo, &skuList)
		if err == nil {
			_, _, skuList = skuList2Map(skuList)
			var order *model.GoodsOrder
			order, err = partner.CurOrderManager.LoadOrder(params.VendorOrderID, params.VendorID)
			if err == nil {
				removedAll, err2 := fillSkuList(skuList, order.Skus)
				if err = err2; err == nil {
					if removedAll {
						err = fmt.Errorf("至少要保留一个商品")
					} else {
						err = defsch.FixedScheduler.AdjustOrder(params.Ctx, order, skuList, params.Reason)
					}
				}
			}
		}
		return retVal, "", err
	})
}

// @Title 取消订单
// @Description 取消订单
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属厂商ID"
// @Param	reason			formData	string	false	"取消原因"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /CancelOrder [put]
func (c *OrderController) CancelOrder() {
	c.callCancelOrder(func(params *tOrderCancelOrderParams) (retVal interface{}, errCode string, err error) {
		order, err := partner.CurOrderManager.LoadOrder(params.VendorOrderID, params.VendorID)
		if order.Status >= model.OrderStatusFinished && order.VendorID != model.VendorIDTaoVegetable {
			return nil, "", fmt.Errorf("订单处于完成状态,不支持取消操作!请走售后流程")
		}
		if err == nil {
			err = defsch.FixedScheduler.CancelOrder(params.Ctx, order, params.Reason)
		}
		return retVal, "", err
	})
}

// @Title 审核取货失败
// @Description 审核取货失败
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属厂商ID"
// @Param	acceptIt		formData	bool	true	"是否批准"
// @Param	reason			formData	string	false	"原因"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /AcceptOrRefuseFailedGetOrder [put]
func (c *OrderController) AcceptOrRefuseFailedGetOrder() {
	c.callAcceptOrRefuseFailedGetOrder(func(params *tOrderAcceptOrRefuseFailedGetOrderParams) (retVal interface{}, errCode string, err error) {
		order, err := partner.CurOrderManager.LoadOrder(params.VendorOrderID, params.VendorID)
		if err == nil {
			err = defsch.FixedScheduler.AcceptOrRefuseFailedGetOrder(params.Ctx, order, params.AcceptIt, params.Reason)
		}
		return retVal, "", err
	})
}

// @Title 取货失败后再次招唤平台配送
// @Description 取货失败后再次招唤平台配送
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属厂商ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /CallPMCourier [put]
func (c *OrderController) CallPMCourier() {
	c.callCallPMCourier(func(params *tOrderCallPMCourierParams) (retVal interface{}, errCode string, err error) {
		order, err := partner.CurOrderManager.LoadOrder(params.VendorOrderID, params.VendorID)
		if err == nil {
			err = defsch.FixedScheduler.CallPMCourier(params.Ctx, order)
		}
		return retVal, "", err
	})
}

// @Title 投递失败后确认收到退货
// @Description 投递失败后确认收到退货
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属厂商ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /ConfirmReceiveGoods [put]
func (c *OrderController) ConfirmReceiveGoods() {
	c.callConfirmReceiveGoods(func(params *tOrderConfirmReceiveGoodsParams) (retVal interface{}, errCode string, err error) {
		order, err := partner.CurOrderManager.LoadOrder(params.VendorOrderID, params.VendorID)
		if err == nil {
			err = defsch.FixedScheduler.ConfirmReceiveGoods(params.Ctx, order)
		}
		return retVal, "", err
	})
}

// @Title 同意或拒绝用户取消订单申请 (饿百)
// @Description 同意或拒绝用户取消订单申请
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属厂商ID"
// @Param	acceptIt		formData	bool	true	"是否批准"
// @Param	reason			formData	string	false	"原因"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /AgreeOrRefuseCancel [put]
func (c *OrderController) AgreeOrRefuseCancel() {
	c.callAgreeOrRefuseCancel(func(params *tOrderAgreeOrRefuseCancelParams) (retVal interface{}, errCode string, err error) {
		order, err := partner.CurOrderManager.LoadOrder(params.VendorOrderID, params.VendorID)
		if err == nil {
			if err = defsch.FixedScheduler.AgreeOrRefuseCancel(params.Ctx, order, params.AcceptIt, params.Reason); err == nil /*&& params.AcceptIt*/ {
				order.LockStatus = model.OrderStatusUnknown
				err = partner.CurOrderManager.UpdateOrderFields(order, []string{"LockStatus"})
			}
		}
		return retVal, "", err
	})
}

// @Title 审核售后单申请
// @Description 审核售后单申请
// @Param	token			header		string	true	"认证token"
// @Param	afsOrderID		formData	string	true	"售后ID"
// @Param	vendorID		formData	int		true	"订单所属厂商ID"
// @Param	approveType		formData	int		true	"操作类型"
// @Param	reason			formData	string	false	"原因"
// @Param	mtReview		formData	string	false	"美团必传map[string]interface{}"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /AgreeOrRefuseRefund [put]
func (c *OrderController) AgreeOrRefuseRefund() {
	c.callAgreeOrRefuseRefund(func(params *tOrderAgreeOrRefuseRefundParams) (retVal interface{}, errCode string, err error) {
		var review map[string]interface{}
		if err = json.Unmarshal([]byte(params.MtReview), &review); err != nil {
			return nil, "", err
		}

		err = defsch.FixedScheduler.AgreeOrRefuseRefund(params.Ctx, params.AfsOrderID, params.VendorID, params.ApproveType, params.Reason, review)
		return retVal, "", err
	})
}

// @Title 确认收到售后退货
// @Description 确认收到售后退货
// @Param	token			header		string	true	"认证token"
// @Param	afsOrderID		formData	string	true	"售后ID"
// @Param	vendorID		formData	int		true	"订单所属厂商ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /ConfirmReceivedReturnGoods [put]
func (c *OrderController) ConfirmReceivedReturnGoods() {
	c.callConfirmReceivedReturnGoods(func(params *tOrderConfirmReceivedReturnGoodsParams) (retVal interface{}, errCode string, err error) {
		err = defsch.FixedScheduler.ConfirmReceivedReturnGoods(params.Ctx, params.AfsOrderID, params.VendorID)
		return retVal, "", err
	})
}

// @Title 得到门店售后单信息
// @Description 得到门店售后单信息
// @Param	token		header	string	true	"认证token"
// @Param	storeID		query	int		true	"京西门店ID"
// @Param	lastHours	query	int		false	"最近多少小时的信息（缺省为两天）"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetStoreAfsOrderCountInfo [get]
func (c *OrderController) GetStoreAfsOrderCountInfo() {
	c.callGetStoreAfsOrderCountInfo(func(params *tOrderGetStoreAfsOrderCountInfoParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.FixedOrderManager.GetStoreAfsOrderCountInfo(params.Ctx, params.StoreID, params.LastHours)
		return retVal, "", err
	})
}

// @Title 补全遗漏的订单
// @Description 补全遗漏的订单
// @Param	token			header		string	true	"认证token"
// @Param	fromDate		formData	string	true	"订单起始日期"
// @Param	toDate			formData	string	false	"订单结束日期"
// @Param	vendorIDs		formData	string	false	"订单所属的厂商ID列表"
// @Param	storeID			formData	int		false	"门店ID"
// @Param	isAsync			formData	bool	false	"是否异步操作"
// @Param	isContinueWhenError	formData	bool	false	"单个失败是否继续，缺省true"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /AmendMissingOrders [post]
func (c *OrderController) AmendMissingOrders() {
	c.callAmendMissingOrders(func(params *tOrderAmendMissingOrdersParams) (retVal interface{}, errCode string, err error) {
		timeList, err := jxutils.BatchStr2Time(params.FromDate, params.ToDate)
		if err == nil {
			var vendorIDs []int
			if err = jxutils.Strings2Objs(params.VendorIDs, &vendorIDs); err == nil {
				retVal, err = orderman.FixedOrderManager.AmendMissingOrders(params.Ctx, vendorIDs, params.StoreID, timeList[0], timeList[1], params.IsAsync, params.IsContinueWhenError)
			}
		}
		return retVal, "", err
	})
}

// @Title 同步刷新历史订单的结算价按订单
// @Description 同步刷新历史订单的结算价按订单
// @Param	token			header		string	true	"认证token"
// @Param	fromTime		formData	string	false	"订单起始时间 (yyyy-mm-dd hh:ms:ss)"
// @Param	toTime			formData	string	false	"订单结束时间 (yyyy-mm-dd hh:ms:ss)"
// @Param	vendorOrderID	formData	string	false	"订单号"
// @Param	vendorIDs		formData	string	false	"平台ID列表[0,1,3]"
// @Param	actID		    formData	int	    false	"活动ID"
// @Param	storeID			formData	int		false	"门店ID"
// @Param	isAsync			formData	bool	false	"是否异步操作"
// @Param	isContinueWhenError	formData	bool	false	"单个失败是否继续，缺省true"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /RefreshHistoryOrdersEarningPrice [post]
func (c *OrderController) RefreshHistoryOrdersEarningPrice() {
	c.callRefreshHistoryOrdersEarningPrice(func(params *tOrderRefreshHistoryOrdersEarningPriceParams) (retVal interface{}, errCode string, err error) {
		var vendorIDList []int
		if err = jxutils.Strings2Objs(params.VendorIDs, &vendorIDList); err == nil {
			retVal, errCode, err = orderman.FixedOrderManager.RefreshHistoryOrdersEarningPrice(params.Ctx, params.VendorOrderID, params.ActID, vendorIDList, params.StoreID, params.FromTime, params.ToTime, params.IsAsync, params.IsContinueWhenError)
		}
		return retVal, errCode, err
	})
}

// @Title 商家主动发起部分退款售后
// @Description 商家主动发起部分退款售后
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属厂商ID"
// @Param	refundSkuList	formData	string	true	"要去除的商品信息，只有skuID与Count字段有效"
// @Param	reason			formData	string	true	"原因"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /PartRefundOrder [put]
func (c *OrderController) PartRefundOrder() {
	c.callPartRefundOrder(func(params *tOrderPartRefundOrderParams) (retVal interface{}, errCode string, err error) {
		var skuList []*model.OrderSku
		err = jxutils.Strings2Objs(params.RefundSkuList, &skuList)
		if err == nil {
			if params.VendorID == model.VendorIDJX {
				return nil, "", errors.New("京西小程序暂未开启此功能")
			}
			_, _, skuList = skuList2Map(skuList)
			var order *model.GoodsOrder
			order, err = partner.CurOrderManager.LoadOrder(params.VendorOrderID, params.VendorID)
			if err == nil {
				removedAll, err2 := fillSkuList(skuList, order.Skus)
				if err = err2; err == nil {
					if removedAll {
						err = defsch.FixedScheduler.RefundOrder(params.Ctx, order, params.Reason)
					} else {
						err = defsch.FixedScheduler.PartRefundOrder(params.Ctx, order, skuList, params.Reason)
					}
				}
			}
		}
		return retVal, "", err
	})
}

// @Title 小程序用户申请售后(退款)
// @Description 小程序用户申请售后(退款)
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属厂商ID"
// @Param	refundSkuList	formData	string	true	"要去除的商品信息，只有skuID与Count字段有效"
// @Param	reason			formData	string	true	"原因"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /ApplyRefundOrder [post]
func (c *OrderController) ApplyRefundOrder() {
	c.callApplyRefundOrder(func(params *tOrderApplyRefundOrderParams) (retVal interface{}, errCode string, err error) {
		// 微信,支付宝-通联,(抖音-抖音支付,快手-快手支付) 小程序,下单时不区分平台,支付时区分()

		// 1- 创建afsOrder 售后单
		// 2-
		var skuList []*model.OrderSku
		err = jxutils.Strings2Objs(params.RefundSkuList, &skuList)
		if err == nil {
			_, _, skuList = skuList2Map(skuList)
			var order *model.GoodsOrder
			order, err = partner.CurOrderManager.LoadOrder(params.VendorOrderID, params.VendorID)
			if err == nil {
				removedAll, err2 := fillSkuList(skuList, order.Skus)
				if err = err2; err == nil {
					if removedAll {
						err = defsch.FixedScheduler.RefundOrder(params.Ctx, order, params.Reason)
					} else {
						err = defsch.FixedScheduler.PartRefundOrder(params.Ctx, order, skuList, params.Reason)
					}
				}
			}
		}
		return retVal, "", err
	})
}

func fillSkuList(skuList, orderSkuList []*model.OrderSku) (isSame bool, err error) {
	skuCount, orderSkuMap, _ := skuList2Map(orderSkuList)
	skuCount2 := 0
	for _, sku := range skuList {
		skuCount2 += sku.Count
		skuID := jxutils.GetSkuIDFromOrderSku(sku)
		actID := sku.StoreSubID
		sku2 := getSkuFromMap(orderSkuMap, skuID, int(actID))
		if sku2 == nil {
			err = fmt.Errorf("找不到SKU:%d", skuID)
		} else if sku.Count > sku2.Count {
			err = fmt.Errorf("SKU:%d调整数量:%d大于实际数量:%d", skuID, sku.Count, sku2.Count)
		}
		if err != nil {
			break
		} else {
			count := sku.Count
			*sku = *sku2
			sku.Count = count
		}
	}
	return skuCount == skuCount2, err
}

// @Title 商家主动发起全额退款售后
// @Description 商家主动发起全额退款售后
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单所属厂商ID"
// @Param	reason			formData	string	false	"退款原因"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /RefundOrder [put]
func (c *OrderController) RefundOrder() {
	c.callRefundOrder(func(params *tOrderRefundOrderParams) (retVal interface{}, errCode string, err error) {
		order, err := orderman.FixedOrderManager.LoadOrder(params.VendorOrderID, params.VendorID)
		if err != nil {
			return nil, "", err
		}
		afsSkuList, err := dao.GetAfsOrderSkuInfo(dao.GetDB(), params.VendorOrderID, "", params.VendorID, false)
		if err != nil {
			return nil, "", err
		}
		order = jxutils.RemoveSkuFromOrder(order, afsSkus2OrderSkus(afsSkuList))
		err = defsch.FixedScheduler.RefundOrder(params.Ctx, order, params.Reason)
		return retVal, "", err
	})
}

func afsSkus2OrderSkus(afsSkuList []*model.OrderFinancialSkuExt) (skuList []*model.OrderSku) {
	for _, v := range afsSkuList {
		if v.IsAfsOrder == 1 {
			skuList = append(skuList, &model.OrderSku{
				SkuID:       v.SkuID,
				VendorSkuID: v.VendorSkuID,
				Count:       v.Count,
			})
		}
	}
	return skuList
}

// @Title 订单门店归属补漏
// @Description 订单门店归属补漏
// @Param	token				header		string	true	"认证token"
// @Param	fromDate			formData	string	false	"开始日期"
// @Param	toDate				formData	string	false	"结束日期（缺省不限制）"
// @Param	isAsync				formData	bool	false	"是否异步操作"
// @Param	isContinueWhenError	formData	bool	false	"单个同步失败是否继续，缺省false"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /RefreshOrdersWithoutJxStoreID [post]
func (c *OrderController) RefreshOrdersWithoutJxStoreID() {
	c.callRefreshOrdersWithoutJxStoreID(func(params *tOrderRefreshOrdersWithoutJxStoreIDParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.RefreshOrdersWithoutJxStoreID(params.Ctx, params.FromDate, params.ToDate, params.IsAsync, params.IsContinueWhenError)
		return retVal, "", err
	})
}

// @Title 获取投诉原因
// @Description 获取投诉原因
// @Param	token				header		string	true	"认证token"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetComplaintReasons [get]
func (c *OrderController) GetComplaintReasons() {
	c.callGetComplaintReasons(func(params *tOrderGetComplaintReasonsParams) (retVal interface{}, errCode string, err error) {
		retVal = orderman.GetComplaintReasons()
		return retVal, "", err
	})
}

// @Title 投诉骑手
// @Description 投诉骑手
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	waybillVendorID	formData	string	true	"运单所属厂商ID"
// @Param	waybillID		formData	string	false	"运单ID"
// @Param	complaintID		formData	int		true	"投诉原因ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /ComplaintRider [post]
func (c *OrderController) ComplaintRider() {
	c.callComplaintRider(func(params *tOrderComplaintRiderParams) (retVal interface{}, errCode string, err error) {
		err = orderman.ComplaintRider(params.Ctx, params.VendorOrderID, params.WaybillVendorID, params.ComplaintID, params.WaybillID)
		return retVal, "", err
	})
}

// @Title 获取可投诉骑手列表
// @Description 获取可投诉骑手列表
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /ComplaintRiderList [get]
func (c *OrderController) ComplaintRiderList() {
	c.callComplaintRiderList(func(params *tOrderComplaintRiderListParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.GetComplaintList(params.VendorOrderID)
		return retVal, "", err
	})
}

// @Title 查询门店订单扣款记录
// @Description 查询门店订单扣款记录
// @Param	token			header		string	true	"认证token"
// @Param	storeIDs		query		string	false	"门店ID列表"
// @Param	vendorOrderID	query		string	false	"订单ID"
// @Param	vendorIDs		query		string	false	"订单所属厂商ID列表"
// @Param	fromTime		query		string	false	"开始日期（包含），格式（2006-01-02），如果订单号为空此项必须要求"
// @Param	toTime			query		string	false	"结束日期（包含），格式（2006-01-02），如果订单号为空此项必须要求"
// @Param	statuss			query		string	false	"账单状态列表，0是未结账，1是已结账,-1为作废"
// @Param	type			query		int		false	"扣款类型，1为差评补贴，2为优惠券"
// @Param	isReverse		query		int		false	"只查冲账记录，0为默认都查，1为只查冲账，-1为不查冲账"
// @Param	offset			query		int		false	"结果起始序号（以0开始，缺省为0）"
// @Param	pageSize		query		int		false	"结果页大小（缺省为50，-1表示全部）"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetOrdersSupplement [get]
func (c *OrderController) GetOrdersSupplement() {
	var vendorIDList, storeIDList, statusList []int
	c.callGetOrdersSupplement(func(params *tOrderGetOrdersSupplementParams) (retVal interface{}, errCode string, err error) {
		if err = jxutils.Strings2Objs(params.VendorIDs, &vendorIDList, params.StoreIDs, &storeIDList, params.Statuss, &statusList); err == nil {
			retVal, err = orderman.GetOrdersSupplement(params.Ctx, storeIDList, vendorIDList, statusList, params.VendorOrderID, params.FromTime, params.ToTime, params.Type, params.IsReverse, params.Offset, params.PageSize)
		}
		return retVal, "", err
	})
}

// @Title 新增修改扣款记录
// @Description 新增修改扣款记录
// @Param	token		header		string	true	"认证token"
// @Param	payload		formData	string	true	"json数据,格式为OrdersSupplement"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /AddUpdateOrdersSupplement [post]
func (c *OrderController) AddUpdateOrdersSupplement() {
	c.callAddUpdateOrdersSupplement(func(params *tOrderAddUpdateOrdersSupplementParams) (retVal interface{}, errCode string, err error) {
		ordersSupplement := &model.OrderSupplementFee{}
		if err = utils.UnmarshalUseNumber([]byte(params.Payload), ordersSupplement); err == nil {
			retVal, err = orderman.AddUpdateOrdersSupplement(params.Ctx, ordersSupplement)
		}
		return retVal, "", err
	})
}

// @Title 重新计算订单结算信息
// @Description 重新计算订单结算信息
// @Param	token			header		string	true	"认证token"
// @Param	fromTime		formData	string	true	"订单起始时间"
// @Param	toTime			formData	string	false	"订单结束时间"
// @Param	isAsync				formData	bool	false	"是否异步操作"
// @Param	isContinueWhenError	formData	bool	false	"单个同步失败是否继续，缺省false"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /RefreshOrdersPriceInfo [post]
func (c *OrderController) RefreshOrdersPriceInfo() {
	c.callRefreshOrdersPriceInfo(func(params *tOrderRefreshOrdersPriceInfoParams) (retVal interface{}, errCode string, err error) {
		timeList, err := jxutils.BatchStr2Time(params.FromTime, params.ToTime)
		if err == nil {
			retVal, err = orderman.RefreshOrdersPriceInfo(params.Ctx, timeList[0], timeList[1], params.IsAsync, params.IsContinueWhenError)
		}
		return retVal, "", err
	})
}

// @Title 获取某个门店订单中待拣货商品
// @Description 获取某个门店订单中待拣货商品
// @Param	token			header	string	true	"认证token"
// @Param	storeID			query	int		true	"门店ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetOrdersAccept [get]
func (c *OrderController) GetOrdersAccept() {
	c.callGetOrdersAccept(func(params *tOrderGetOrdersAcceptParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.GetOrdersAccept(params.Ctx, params.StoreID)
		return retVal, "", err
	})
}

// @Title 获取某个门店上次申请物料到现在的销量
// @Description 获取某个门店上次申请物料到现在的销量
// @Param	token			header	string	false	"认证token"
// @Param	storeID			query	int		true	"门店ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetMatterStoreOrderCount [get]
func (c *OrderController) GetMatterStoreOrderCount() {
	c.callGetMatterStoreOrderCount(func(params *tOrderGetMatterStoreOrderCountParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.GetMatterStoreOrderCount(params.Ctx, params.StoreID)
		return retVal, "", err
	})
}

// @Title 刷新京东商城订单结算价
// @Description 刷新京东商城订单结算价
// @Param	token			header		string	true	"认证token"
// @Param	fromTime		formData	string	true	"订单起始时间 格式：20060102"
// @Param	toTime			formData	string	true	"订单结束时间"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /RefreshJdShopOrdersEarningPrice [post]
func (c *OrderController) RefreshJdShopOrdersEarningPrice() {
	c.callRefreshJdShopOrdersEarningPrice(func(params *tOrderRefreshJdShopOrdersEarningPriceParams) (retVal interface{}, errCode string, err error) {
		err = orderman.RefreshJdShopOrdersEarningPrice(params.Ctx, params.FromTime, params.ToTime)
		return retVal, "", err
	})
}

// @Title 根据订单号查询一些信息
// @Description 根据订单号查询一些信息
// @Param	token			header		string	false	"认证token"
// @Param	vendorOrderID	query		string	true	"订单号"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetOrderSimpleInfo [get]
func (c *OrderController) GetOrderSimpleInfo() {
	c.callGetOrderSimpleInfo(func(params *tOrderGetOrderSimpleInfoParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.GetOrderSimpleInfo(params.Ctx, params.VendorOrderID)
		return retVal, "", err
	})
}

// @Title 根据订单号查询用户是否是第一次购买
// @Description 根据订单号查询用户是否是第一次购买
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	query		string	true	"订单号"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetOrderUserBuyFirst [get]
func (c *OrderController) GetOrderUserBuyFirst() {
	c.callGetOrderUserBuyFirst(func(params *tOrderGetOrderUserBuyFirstParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.GetOrderUserBuyFirst(params.Ctx, params.VendorOrderID)
		return retVal, "", err
	})
}

// @Title 京东商城订单转移
// @Description 京东商城订单转移
// @Param	token			header		string	true	"认证token"
// @Param	storeID			formData	int		true	"转移的门店ID"
// @Param	vendorOrderID	formData	string	true	"转移的订单号"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /TransferJdsOrder [post]
func (c *OrderController) TransferJdsOrder() {
	c.callTransferJdsOrder(func(params *tOrderTransferJdsOrderParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.TransferJdsOrder(params.Ctx, params.VendorOrderID, params.StoreID)
		return retVal, "", err
	})
}

// @Title 合并订单（京东商城用）
// @Description  合并订单（京东商城用）
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderIDs	formData	string	true	"订单号s"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /MergeJdsOrders [post]
func (c *OrderController) MergeJdsOrders() {
	c.callMergeJdsOrders(func(params *tOrderMergeJdsOrdersParams) (retVal interface{}, errCode string, err error) {
		var vendorOrderIDs []string
		if err = jxutils.Strings2Objs(params.VendorOrderIDs, &vendorOrderIDs); err == nil {
			retVal, err = orderman.MergeJdsOrders(params.Ctx, vendorOrderIDs)
		}
		return retVal, "", err
	})
}

// @Title 京东商城订单发送京东物流
// @Description 京东商城订单发送京东物流
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单号"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /SendJdwlForJdsOrder [post]
func (c *OrderController) SendJdwlForJdsOrder() {
	c.callSendJdwlForJdsOrder(func(params *tOrderSendJdwlForJdsOrderParams) (retVal interface{}, errCode string, err error) {
		err = orderman.SendJdwlForJdsOrder(params.Ctx, params.VendorOrderID)
		return retVal, "", err
	})
}

// @Title 手动拉取京东商城订单
// @Description 手动拉取京东商城订单
// @Param	token			header		string	true	"认证token"
// @Param	fromTime		formData	string	true	"订单起始时间"
// @Param	toTime			formData	string	true	"订单结束时间"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /SaveJdsOrders [post]
func (c *OrderController) SaveJdsOrders() {
	c.callSaveJdsOrders(func(params *tOrderSaveJdsOrdersParams) (retVal interface{}, errCode string, err error) {
		err = orderman.SaveJdsOrders(params.Ctx, utils.Str2Time(params.FromTime), utils.Str2Time(params.ToTime))
		return retVal, "", err
	})
}

// @Title 针对京东商城进行简单的售前删除操作
// @Description 针对京东商城进行简单的售前删除操作
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单号"
// @Param	skuID			formData	int		true	"商品ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /AdjustJdsOrderSimple [post]
func (c *OrderController) AdjustJdsOrderSimple() {
	c.callAdjustJdsOrderSimple(func(params *tOrderAdjustJdsOrderSimpleParams) (retVal interface{}, errCode string, err error) {
		err = orderman.AdjustJdsOrderSimple(params.Ctx, params.VendorOrderID, params.SkuID)
		return retVal, "", err
	})
}

// @Title 修改订单运费
// @Description 修改订单运费
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单号"
// @Param	desiredFee		formData	int		true	"运费"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /UpdateWaybillDesiredFee [put]
func (c *OrderController) UpdateWaybillDesiredFee() {
	c.callUpdateWaybillDesiredFee(func(params *tOrderUpdateWaybillDesiredFeeParams) (retVal interface{}, errCode string, err error) {
		err = orderman.UpdateWaybillDesiredFee(params.Ctx, params.VendorOrderID, params.DesiredFee)
		return retVal, "", err
	})
}

// @Title 接单或拒单
// @Description 接单或拒单
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"订单平台ID"
// @Param	isAccept		formData	bool	true	"接单或者拒单"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /AcceptOrRefuseOrder [post]
func (c *OrderController) AcceptOrRefuseOrder() {
	c.callAcceptOrRefuseOrder(func(params *tOrderAcceptOrRefuseOrderParams) (retVal interface{}, errCode string, err error) {
		err = orderman.AcceptOrRefuseOrder(params.Ctx, params.VendorOrderID, params.VendorID, params.IsAccept)
		return retVal, "", err
	})
}

// @Title 刷新京东商城订单收货人信息
// @Description 刷新京东商城订单收货人信息
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /RefreshJdsOrderConsigneeInfo [put]
func (c *OrderController) RefreshJdsOrderConsigneeInfo() {
	c.callRefreshJdsOrderConsigneeInfo(func(params *tOrderRefreshJdsOrderConsigneeInfoParams) (retVal interface{}, errCode string, err error) {
		err = orderman.RefreshJdsOrderConsigneeInfo(params.Ctx, params.VendorOrderID)
		return retVal, "", err
	})
}

// @Title 修改订单信息
// @Description 修改订单信息
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单号"
// @Param	vendorID		formData	int		true	"平台ID"
// @Param	payload			formData	string	true	"json数据,格式为goodsOrder"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /UpdateOrderInfo [put]
func (c *OrderController) UpdateOrderInfo() {
	c.callUpdateOrderInfo(func(params *tOrderUpdateOrderInfoParams) (retVal interface{}, errCode string, err error) {
		payload := make(map[string]interface{})
		if err = utils.UnmarshalUseNumber([]byte(params.Payload), &payload); err == nil {
			retVal, err = orderman.UpdateOrderInfo(params.Ctx, params.VendorOrderID, params.VendorID, payload)
		}
		return retVal, "", err
	})
}

// @Title 刷新报价订单的订单商品价
// @Description 刷新报价订单的订单商品价
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"平台ID"
// @Param	skuID			formData	int		true	"商品ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /RefreshOrderSkuInfo [put]
func (c *OrderController) RefreshOrderSkuInfo() {
	c.callRefreshOrderSkuInfo(func(params *tOrderRefreshOrderSkuInfoParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.RefreshOrderSkuInfo(params.Ctx, params.VendorOrderID, params.VendorID, params.SkuID)
		return retVal, "", err
	})
}

// @Title 删除报价订单的订单商品
// @Description 删除报价订单的订单商品
// @Param	token			header		string	true	"认证token"
// @Param	vendorOrderID	formData	string	true	"订单ID"
// @Param	vendorID		formData	int		true	"平台ID"
// @Param	ID				formData	int		true	"id"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /DelOrderSkuInfo [post]
func (c *OrderController) DelOrderSkuInfo() {
	c.callDelOrderSkuInfo(func(params *tOrderDelOrderSkuInfoParams) (retVal interface{}, errCode string, err error) {
		retVal, err = orderman.DelOrderSkuInfo(params.Ctx, params.VendorOrderID, params.VendorID, params.ID)
		return retVal, "", err
	})
}

// @Title 导出订单
// @Description 导出订单
// @Param	token			header	string	true	"认证token"
// @Param	orderID			query	string	false	"订单号，如果此项不为空，忽略其它所有查询条件（此项会废弃，用vendorOderID）"
// @Param	vendorOrderID	query	string	false	"订单号，如果此项不为空，忽略其它所有查询条件"
// @Param	keyword			query	string	false	"查询关键字"
// @Param	fromDate		query	string	false	"开始日期（包含），格式（2006-01-02），如果订单号为空此项必须要求"
// @Param	toDate			query	string	false	"结束日期（包含），格式（2006-01-02），如果订单号为空此项必须要求"
// @Param	isDateFinish	query	bool	false	"是否fromDate与toDate指的是订单结束日期，缺省不是"
// @Param	vendorIDs		query	string	false	"订单所属厂商列表[1,2,3]，缺省不限制"
// @Param	waybillVendorIDs	query	string		false	"承运人所属厂商列表[1,2,3]，缺省不限制"
// @Param	storeIDs		query	string	false	"京西门店ID列表[1,2,3]，缺省不限制"
// @Param	statuss			query	string	false	"订单状态列表[1,2,3]，缺省不限制"
// @Param	lockStatuss		query	string	false	"订单锁定状态列表[1,2,3]，缺省不限制"
// @Param	cities			query	string	false	"城市code列表[1,2,3]，缺省不限制"
// @Param	isIncludeFake	query	bool	false	"是否包括假订单"
// @Param	skuIDs			query	string	false	"包含的skuID列表，或的关系"
// @Param	isJxFirst		query	bool	false	"排序是否京西订单优先（缺省为否）"
// @Param	adjustCount		query	int		false	"最小调整次数"
// @Param	brandID			query	int		false	"品牌ID"
// @Param	mustInvoice		query	bool	false	"是否必须要求开发票"
// @Param	deliveryTypes	query	string	false	"配送方式"
// @Param	jxIncomeBegin	query	string	false	"预计收入begin"
// @Param	jxIncomeEnd		query	string	false	"预计收入end"
// @Param	marketManPhone	query	string	false	"平台负责人"
// @Param	jdPhone			query	string	false	"京东负责人电话"
// @Param	mtPhone			query	string	false	"美团负责人电话"
// @Param	ebaiPhone		query	string	false	"饿百负责人电话"
// @Param	offset			query	int		false	"结果起始序号（以0开始，缺省为0）"
// @Param	pageSize		query	int		false	"结果页大小（缺省为50，-1表示全部）"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /ExportOrderWithSku [get]
func (c *OrderController) ExportOrderWithSku() {
	c.callExportOrderWithSku(func(params *tOrderExportOrderWithSkuParams) (retVal interface{}, errCode string, err error) {
		var skuIDs []int
		jxutils.Strings2Objs(params.SkuIDs, &skuIDs)
		page, err := orderman.FixedOrderManager.GetOrders(params.Ctx, params.IsIncludeFake, params.FromDate, params.ToDate, params.IsDateFinish, skuIDs, params.IsJxFirst, params.MapData, params.Offset, model.UnlimitedPageSize)
		if page != nil && page.Data != nil {
			retVal, err = orderman.ExportOrderWithSku(params.Ctx, page.Data.([]*model.GoodsOrderExt))
		}
		return retVal, "", err
	})
}

// @Title 更新美团订单结算信息
// @Description 更新美团订单结算信息
// @Param	token			header		string	true	"认证token"
// @Param	startTime		formData	int64	true	"开始时间"
// @Param	endTime			formData	int64	true	"结束时间"
// @Param	storeId			formData	int		true	"京西门店id"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /UpdateMTOrderSettle [post]
func (c *OrderController) UpdateMTOrderSettle() {
	c.callUpdateMTOrderSettle(func(params *tOrderUpdateMTOrderSettleParams) (interface{}, string, error) {
		err := delivery.LoadingStoreOrderSettleAmount(int64(params.StartTime), int64(params.EndTime), []int{params.StoreId})
		return nil, "", err
	})
}

// @Title 获取三方配送的骑手坐标
// @Description 获取三方配送的骑手坐标
// @Param	orderId			formData	string	true	"订单id"
// @Param	deliveryId		formData	string	true	"运单id"
// @Param	waybillVendorId	formData	int		true	"运单平台id"
// @Param	orderVendorId	formData	int		true	"运单平台id"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetRiderLng [post]
func (c *OrderController) GetRiderLng() {
	c.callGetRiderLng(func(params *tOrderGetRiderLngParams) (interface{}, string, error) {
		rider, err := delivery.GetVendorRiderInfo(params.WaybillVendorId, params.OrderVendorId, params.OrderId, params.DeliveryId)
		return rider, "", err
	})
}

// @Title 手动更新抖音门店结算信息
// @Description 手动更新抖音门店结算信息
// @Param	token			header		string	true	"认证token"
// @Param	storeId			formData	int		false	"门店id"
// @Param	startTime		formData	string	true	"开始时间"
// @Param	endTime			formData	string	true	"结束时间"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /UpdateTiktokSettlement [post]
func (c *OrderController) UpdateTiktokSettlement() {
	c.callUpdateTiktokSettlement(func(params *tOrderUpdateTiktokSettlementParams) (retVal interface{}, errCode string, err error) {
		err = orderman.UpdateTiktokShopTotalMoney(int64(params.StoreId), utils.Str2Time(params.StartTime), utils.Str2Time(params.EndTime))
		return retVal, errCode, err
	})
}

// @Title 获取门店的发票申请
// @Description 获取门店的发票申请
// @Param	token			header		string	true	"认证token"
// @Param	storeId			formData	int		false	"门店id"
// @Param	startTime		formData	string	true	"开始时间"
// @Param	endTime			formData	string	true	"结束时间"
// @Param	status			formData	string	false	"发票回复状态[1未回复/2回复]"
// @Param	offset			formData	int		false	"结果起始序号（以0开始，缺省为0）"
// @Param	pageSize		formData	int		false	"结果页大小（缺省为50，-1表示全部）"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetInvoiceRecord [post]
func (c *OrderController) GetInvoiceRecord() {
	c.callGetInvoiceRecord(func(params *tOrderGetInvoiceRecordParams) (retVal interface{}, errCode string, err error) {
		retVal, err = dao.GetStoreInvoiceList(params.StoreId, 0, utils.Str2Time(params.StartTime), utils.Str2Time(params.EndTime), params.Status, params.Offset, params.PageSize)
		return retVal, errCode, err
	})
}

// @Title 上传订单发票
// @Description 上传订单发票
// @Param	token			header		string	true	"认证token"
// @Param	orderId			formData	string	true	"订单ID"
// @Param	invoiceUrl		formData	string	true	"发票地址[10M内pdf/png/jpeg/jpg]"
// @Param	invoiceId		formData	string	true	"发票号码"
// @Param	imgBase64		formData	string	false	"京东发票pdf二进制文件流"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /UploadOrderInvoice [post]
func (c *OrderController) UploadOrderInvoice() {
	c.callUploadOrderInvoice(func(params *tOrderUploadOrderInvoiceParams) (retVal interface{}, errCode string, err error) {
		var (
			db = dao.GetDB()
		)
		invoice, err := dao.GetInvoiceInfo(db, params.OrderId)
		if err != nil {
			return retVal, errCode, err
		}
		invoice.InvoiceUrl = params.InvoiceUrl
		invoice.InvoiceId = params.InvoiceId
		handler, _ := partner.GetPurchasePlatformFromVendorID(invoice.VendorID).(partner.IPurchasePlatformStoreSkuHandler)
		success, _, err := handler.UploadInvoice(invoice, params.ImgBase64)
		if err != nil {
			return nil, "", err
		}
		switch invoice.VendorID {
		case model.VendorIDMTWM:
			invoice.Status = model.InvoiceStatusBillingSuccess
		case model.VendorIDEBAI:
			for _, v := range success {
				if v == invoice.InvoiceTaskId {
					invoice.Status = model.InvoiceStatusBillingSuccess
				}
			}
		case model.VendorIDJD:

		}
		dao.UpdateEntity(db, invoice, "InvoiceUrl", "InvoiceId", "Status")
		return retVal, errCode, err
	})
}

// @Title 查询门店发票设置
// @Description 查询门店发票设置
// @Param	token			header		string	true	"认证token"
// @Param	vendorId		formData	string	true	"平台ID"
// @Param	vendorStoreID	formData	string	true	"平台门店ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /QueryInvoiceSetting [get]
func (c *OrderController) QueryInvoiceSetting() {
	c.callQueryInvoiceSetting(func(params *tOrderQueryInvoiceSettingParams) (retVal interface{}, errCode string, err error) {
		retVal, err = ebai.QueryInvoiceSetting(params.VendorStoreID)
		return
	})
}

// @Title 批量更新门店发票设置
// @Description 批量更新门店发票设置
// @Param	token			header		string	true	"认证token"
// @Param	vendorId		formData	string	true	"平台ID"
// @Param	vendorStoreID	formData	string	true	"平台门店ID"
// @Param	payload			formData	string	true	"json数据,格式为 ebaiapi.StoreInvoiceSetting"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /BathUpdateInvoiceSetting [post]
func (c *OrderController) BathUpdateInvoiceSetting() {
	c.callBathUpdateInvoiceSetting(func(params *tOrderBathUpdateInvoiceSettingParams) (retVal interface{}, errCode string, err error) {
		setting := &ebaiapi.StoreInvoiceSetting{}
		if err = utils.UnmarshalUseNumber([]byte(params.Payload), setting); err == nil {
			success, fail, err := ebai.BathUpdateInvoiceSetting(params.VendorStoreID, setting)

			return map[string]interface{}{
				"success": success,
				"fail":    fail,
			}, "", err
		}
		return
	})
}

// @Title 批量更新店铺开票申请
// @Description 批量更新店铺开票申请
// @Param	token			header		string	true	"认证token"
// @Param	vendorId		formData	string	true	"平台ID"
// @Param	vendorStoreID	formData	string	true	"平台门店ID"
// @Param	storeID			formData	int		true	"京西门店ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /QueryUnansweredInvoice [get]
func (c *OrderController) QueryUnansweredInvoice() {
	c.callQueryUnansweredInvoice(func(params *tOrderQueryUnansweredInvoiceParams) (retVal interface{}, errCode string, err error) {
		retVal, err = ebai.QueryUnansweredInvoice(params.VendorStoreID, params.StoreID)
		return
	})
}

// @Title 查询打印机列表
// @Description 查询打印机列表
// @Param	token			header		string	true	"认证token"
// @Param	printNo			formData	string	false	"打印机编号"
// @Param	printKey		formData	string	false	"打印机秘钥"
// @Param	status			formData	int		false	"激活状态[-1关机/0未连接/1开机]"
// @Param	isOnline		formData	int		false	"在线装填[-1掉线/0未连接/1链接]"
// @Param	page			formData	int		true	"跳过数据条数"
// @Param	size			formData	int		true	"每页展示条数"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /QueryJxPrintList [get]
func (c *OrderController) QueryJxPrintList() {
	c.callQueryJxPrintList(func(params *tOrderQueryJxPrintListParams) (retVal interface{}, errCode string, err error) {
		list, count, err := jxprint.GetPrintList(params.PrintNo, params.PrintKey, params.Status, params.IsOnline, params.Page, params.Size)
		retVal = map[string]interface{}{
			"list":  list,
			"count": count,
		}
		return
	})
}
