package controllers

import (
	"encoding/json"
	"errors"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/dingdingapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/bidding"
	"git.rosy.net.cn/jx-callback/business/jxcallback/scheduler"
	"git.rosy.net.cn/jx-callback/business/jxstore/cms"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/ddmsg"
	"git.rosy.net.cn/jx-callback/business/jxutils/excel"
	"git.rosy.net.cn/jx-callback/business/jxutils/tasksch"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/globals/api"
	"github.com/astaxie/beego/server/web"
	"strings"
	"time"
)

type BiddingController struct {
	web.Controller
}

// @Title 获取招标信息
// @Description 获取招标信息
// @Param	token			header		string	false	"认证token"
// @Param	title			query		string	false	"标题"
// @Param	city			query		string	false	"标题"
// @Param   startTime       query		string	false	"开始时间"
// @Param   endTime      	query		string	false	"结束时间"
// @Param   pageSize      	query		int		false	"页数"
// @Param   pageNumber      query		int		false	"页码"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetBiddingMsg [get]
func (c *BiddingController) GetBiddingMsg() {
	c.callGetBiddingMsg(func(params *tBindGetBiddingMsgParams) (retVal interface{}, errCode string, err error) {
		retVal, err = bidding.GetBiddingMsg(params.Ctx, params.MapData)
		return retVal, "", err
	})
}

// GetRefundOrderList 获取退货账单
// @Title 获取招标信息
// @Description 获取招标信息
// @Param	token			header		string	true	"认证token"
// @Param	brandId			query		int		true	"品牌"
// @Param	start			query		string	true	"开始时间"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetRefundOrderList [get]
func (c *BiddingController) GetRefundOrderList() {
	c.callGetRefundOrderList(func(params *tBindGetRefundOrderListParams) (interface{}, string, error) {
		data, err := bidding.GetBrandPayOrder(params.BrandId, params.Start)
		return data, "", err
	})
}

// GetStoreBindStatus 查询门店是否绑定成功,成功之后创建本地门店
// 查询门店是否绑定成功,成功之后创建本地门店
// @Title 查询门店是否绑定成功,成功之后创建本地门店
// @Description 查询门店是否绑定成功,成功之后创建本地门店
// @Param	token			header		string	true	"认证token"
// @Param	platformId		query		string	false	"授权成功平台id"
// @Param	platformType	query		int		false	"授权平台id"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetStoreBindStatus [get]
func (c *BiddingController) GetStoreBindStatus() {
	c.callGetStoreBindStatus(func(params *tBindGetStoreBindStatusParams) (interface{}, string, error) {
		switch params.PlatformType {
		case model.VendorIDMTWM:
			data, err := api.Mtwm2API.GetBoundList(params.PlatformId)
			if err != nil {
				return nil, "", err
			}
			for _, v := range data {
				if v.AppID == utils.Str2Int(params.PlatformId) {
					return data, "", nil
				}
			}
			return nil, "", errors.New("未查询到绑定数据,请检查美团门店id是否正确")
		case model.VendorIDEBAI:

		case model.VendorIDJD:
		case model.VendorIDTT:

		}
		return nil, "", nil
	})
}

// NeedDeleteGetStoreBindStatus 查询门店是否绑定成功,成功之后创建本地门店
// 查询门店是否绑定成功,成功之后创建本地门店
// @Title 查询门店是否绑定成功,成功之后创建本地门店
// @Description 查询门店是否绑定成功,成功之后创建本地门店
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /NeedDeleteGetStoreBindStatus [get]
func (c *BiddingController) NeedDeleteGetStoreBindStatus() {
	c.callNeedDeleteGetStoreBindStatus(func(params *tBindNeedDeleteGetStoreBindStatusParams) (interface{}, string, error) {
		dd := bidding.QueryNeedDeleteSku()
		return dd, "", nil
	})
}

// UpdateTiktokOrderPhoneAddress 更新抖音电话归属地
// @Title 更新抖音电话归属地
// @Description 更新抖音电话归属地
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /UpdateTiktokOrderPhoneAddress [get]
func (c *BiddingController) UpdateTiktokOrderPhoneAddress() {
	c.callUpdateTiktokOrderPhoneAddress(func(params *tBindUpdateTiktokOrderPhoneAddressParams) (interface{}, string, error) {
		err := bidding.UpdateTiktokOrderPhoneAddress()
		return nil, "", err
	})
}

// JXPrintAfsOrder 售后单打印
// @Title 售后单打印
// @Description 售后单打印
// @Param	orderId	query		string		true	"订单ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /JXPrintAfsOrder [get]
func (c *BiddingController) JXPrintAfsOrder() {
	c.callJXPrintAfsOrder(func(params *tBindJXPrintAfsOrderParams) (interface{}, string, error) {
		afsOrder2, _ := partner.CurOrderManager.LoadAfsOrder(params.OrderId, model.VendorIDMTWM)
		err := scheduler.CurrentScheduler.OnAfsOrderNew(afsOrder2, false)
		return nil, "", err
	})
}

// CreateSupermarketSign 创建超市签约信息
// @Title 创建超市签约信息
// @Description 创建超市签约信息:记录已经签约的门店信息
// @Param	signObj      	formData	string		true	"model.SupermarketSign"
// @Param	token			header		string	    true	"认证token"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /CreateSupermarketSign [post]
func (c *BiddingController) CreateSupermarketSign() {
	c.callCreateSupermarketSign(func(params *tBindCreateSupermarketSignParams) (retVal interface{}, hint string, err error) {
		supermarket := make([]*model.SupermarketSign, 0, 0)
		if err = json.Unmarshal([]byte(params.SignObj), &supermarket); err != nil {
			return nil, "", err
		}

		retVal = bidding.CreateSupermarketSign(supermarket, params.Ctx.GetUserID())
		return retVal, "", nil
	})
}

// GetSupermarketSign 查询超市签约信息
// @Title 查询超市签约信息
// @Description 查询超市签约信息:记录已经签约的门店信息
// @Param	storeID 		formData		string		false	"美团门店ID"
// @Param	storeName 		formData		string		false	"美团门店名称"
// @Param	startTime 		formData		int64		false	"签约开始时间"
// @Param	endTime 		formData		int64		false	"签约结束时间"
// @Param	expirationStart formData		int64		false	"到期开始时间"
// @Param	expirationEnd 	formData		int64		false	"到期结束时间"
// @Param	cityName 		formData		string		false	"门店城市"
// @Param	storeType 		formData		string		false	"门店类型"
// @Param	signPeople 		formData		string		false	"签约人"
// @Param	page 			formData		int64		true	"页码"
// @Param	size	 		formData		int64		true	"页数"
// @Param	token			header			string	    true	"认证token"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetSupermarketSign [post]
func (c *BiddingController) GetSupermarketSign() {
	c.callGetSupermarketSign(func(params *tBindGetSupermarketSignParams) (retVal interface{}, hint string, err error) {
		retVal, count, err := bidding.QuerySupermarketSign(params.StoreID, params.StoreName, params.CityName, params.StoreType, params.SignPeople, params.StartTime, params.EndTime, params.ExpirationStart, params.ExpirationEnd, params.Page, params.Size)

		return map[string]interface{}{"data": retVal, "page": count}, "", err
	})
}

// DeleteSignData 查询超市签约信息
// @Title 查询超市签约信息
// @Description 查询超市签约信息:记录已经签约的门店信息
// @Param	storeID 		formData		string		true	"美团门店ID"
// @Param	token			header			string	    true	"认证token"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /DeleteSignData [delete]
func (c *BiddingController) DeleteSignData() {
	c.callDeleteSignData(func(params *tBindDeleteSignDataParams) (retVal interface{}, hint string, err error) {
		retVal, err = bidding.DeleteSignData(params.StoreID)
		return retVal, hint, err
	})
}

// DownSupermarketSign 下载超市签约信息
// @Title 下载超市签约信息
// @Description 下载超市签约信息
// @Param	storeID 		formData		string		false	"美团门店ID"
// @Param	storeName 		formData		string		false	"美团门店名称"
// @Param	startTime 		formData		int64		false	"签约开始时间"
// @Param	endTime 		formData		int64		false	"签约结束时间"
// @Param	expirationStart formData		int64		false	"到期开始时间"
// @Param	expirationEnd 	formData		int64		false	"到期结束时间"
// @Param	cityName 		formData		string		false	"门店城市"
// @Param	storeType 		formData		string		false	"门店类型"
// @Param	signPeople 		formData		string		false	"签约人"
// @Param	token			header			string	    true	"认证token"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /DownSupermarketSign [post]
func (c *BiddingController) DownSupermarketSign() {
	c.callDownSupermarketSign(func(params *tBindDownSupermarketSignParams) (retVal interface{}, hint string, err error) {
		var (
			stores   []*model.SupermarketSign
			excelBin []byte
		)
		task := tasksch.NewSeqTask("导出签约门店", params.Ctx,
			func(task *tasksch.SeqTask, step int, params2 ...interface{}) (result interface{}, err error) {
				switch step {
				case 0:
					stores, _, _ = bidding.QuerySupermarketSign(params.StoreID, params.StoreName, params.CityName, params.StoreType, params.SignPeople, params.StartTime, params.EndTime, params.ExpirationStart, params.ExpirationEnd, 1, model.UnlimitedPageSize)
				case 1:
					excelConf := &excel.Obj2ExcelSheetConfig{
						Title: "签约门店导出",
						Data:  stores,
						CaptionList: []string{
							"createdAt",
							"updatedAt",
							"storeID",
							"storeName",
							"codeName",
							"storeType",
							"salesVolume",
							"points",
							"contractFee",
							"signStartTime",
							"signEndTime",
							"signPeople",
							"status",
							"remake",
							"reward",
							"createCrowd",
						},
					}
					excelBin = excel.Obj2Excel([]*excel.Obj2ExcelSheetConfig{excelConf})
				case 2:
					keyPart := []string{
						params.Ctx.GetUserName(),
					}
					keyPart = append(keyPart, time.Now().Format("20060102T150405")+".xlsx")
					key := "export/" + strings.Join(keyPart, "_")
					excelURL, err2 := jxutils.UploadExportContent(excelBin, key)
					if err = err2; err == nil {
						//task.SetNoticeMsg(excelURL)
						if authInfo, err := params.Ctx.GetV2AuthInfo(); err == nil {
							noticeMsg := fmt.Sprintf("path=%s\n", excelURL)
							ddmsg.SendUserMessage(dingdingapi.MsgTyeText, authInfo.UserID, "导出签约门店数据", noticeMsg)
						}
					}
				}
				return nil, err
			}, 3)

		tasksch.ManageTask(task).Run()
		hint = task.GetID()
		return "", hint, err
	})
}

// UpdateStockBySkuID 根据skuId更新商品库存
// @Title 根据skuId更新商品库存
// @Description 批量更新库存
// @Param	storeID 		formData		int			true	"标准门店库存ID"
// @Param	stock	 		formData		string		true	"库存列表"[{"skuId":110,"stock":10},{"skuId":111,"stock":10}]"
// @Param	token			header			string	    true	"认证token"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /UpdateStockBySkuID [post]
func (c *BiddingController) UpdateStockBySkuID() {
	c.callUpdateStockBySkuID(func(params *tBindUpdateStockBySkuIDParams) (retVal interface{}, hint string, err error) {
		var (
			stockList []*bidding.SkuIdAndStock
			db        = dao.GetDB()
		)
		if err = jxutils.Strings2Objs(params.Stock, &stockList); err != nil {
			return nil, "", err
		}

		if err = bidding.UpdateStockBySkuId(db, params.StoreID, stockList); err != nil {
			return nil, "", err
		}

		retVal, err = cms.CurVendorSync.SyncStoresSkus(params.Ctx, nil, 0, db, nil, []int{params.StoreID}, nil, true, true, true)
		return
	})
}

// UpdateMtActivity 更新美团任务数据
// @Title 更新美团任务数据
// @Description 更新美团任务数据
// @Param	token			header			string	    true	"认证token"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /UpdateMtActivity [get]
//func (c *BiddingController) UpdateMtActivity() {
//	c.callUpdateMtActivity(func(params *tBindUpdateMtActivityParams) (retVal interface{}, hint string, err error) {
//		retVal = bidding.GetMTInfo()
//		return retVal, "", err
//	})
//}

// GetActivityList 更新美团任务数据
// @Title 更新美团任务数据
// @Description 更新美团任务数据
// @Param	token			header		string	true	"认证token"
// @Param	startTime		formData	string	true	"开始时间"
// @Param	endTime			formData	string	true	"结束时间"
// @Param	storeIDs		query		string	false	"门店ID"
// @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 /GetActivityList [get]
//func (c *BiddingController) GetActivityList() {
//	c.callGetActivityList(func(params *tBindGetActivityListParams) (retVal interface{}, hint string, err error) {
//		var storeIDs []int
//		if err = jxutils.Strings2Objs(params.StoreIDs, &storeIDs); err != nil {
//			return nil, "", err
//		}
//		retVal, err = bidding.GetStatisticsList(utils.Str2Time(params.StartTime), utils.Str2Time(params.EndTime), storeIDs, params.Offset, params.PageSize)
//		return
//	})
//}

//StoreOrderList 统计相同负责人门店订单量
//@Title 统计门店订单数量
//@Description 统计门店订单数量
//@Param	token			header		string	true	"认证token"
//@Param	startTime		query		string	true	"开始时间"
//@Param	endTime			query		string	true	"结束时间"
//@Param	storeIDs		query		string	false	"门店ID"
//@Param	vendorId		query		string	false	"平台id"
//@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 /StoreOrderList [get]
func (c *BiddingController) StoreOrderList() {
	c.callStoreOrderList(func(params *tBindStoreOrderListParams) (retVal interface{}, hint string, err error) {
		var storeIDs, vendorIds []int
		if err = jxutils.Strings2Objs(params.StoreIDs, &storeIDs, params.VendorId, &vendorIds); err != nil {
			return nil, "", err
		}
		retVal, err = bidding.StatisticsOrderCount(utils.Str2Time(params.StartTime), utils.Str2Time(params.EndTime), storeIDs, vendorIds, params.Offset, params.PageSize)
		return retVal, "", err
	})
}
