package services

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/models/order"
	"hongze/hongze_cygx/utils"
	"time"
)

// CancelCygxOrder 关闭到期个人用户研选权限
func CancelCygxOrder(cont context.Context) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("自动取消十分钟之内没有付款的的订单 CancelCygxOrder ，err：", err.Error()), 2)
		}
	}()
	var condition string
	var pars []interface{}
	endTime := time.Now().Add(-10 * time.Minute)
	condition = ` AND order_status = 1   AND create_time < ?   `
	pars = append(pars, endTime)
	orderList, e := order.GetCygxOrderList(condition, pars, 0, 999)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxOrderList, Err: " + e.Error())
		return
	}
	fmt.Println(len(orderList))
	if len(orderList) == 0 {
		return
	}
	//订单量不大，先这么写吧
	for _, v := range orderList {
		e = order.CancelCygxOrder(v)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("CancelCygxOrder, Err: " + e.Error())
			return
		}
		go ExampleJsapiApiService_CloseOrder(v.OutTradeNo)
	}
	return
}

//func init() {
//	HandleOrderRefundHandleask()
//}

// GetQueryOrderByOutTradeNoTask 定时任务主动获取订单支付状态
func GetQueryOrderByOutTradeNoTask(cont context.Context) (err error) {
	//func GetQueryOrderByOutTradeNoTask() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("自动取消十分钟之内没有付款的的订单 CancelCygxOrder ，err：", err.Error()), 2)
		}
	}()
	var condition string
	var pars []interface{}
	endTime := time.Now().Add(-10 * time.Minute)
	condition = ` AND order_status = 1   AND create_time >  ?   ` //获取十分钟之内待支付的订单
	pars = append(pars, endTime)
	orderList, e := order.GetCygxOrderList(condition, pars, 0, 999)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxOrderList, Err: " + e.Error())
		return
	}

	if len(orderList) == 0 {
		return
	}
	//订单量不大，先这么写吧
	for _, v := range orderList {
		tradeState, statusCode, itemResp := GetQueryOrderByOutTradeNo(v.OutTradeNo)
		if tradeState == "SUCCESS" && statusCode == 200 {
			go HandleOrderByWechatPay(itemResp)
		}
	}
	return
}

// 手动处理支付订单回调
func HandleOrderByWechatPay(itemCallback *Transaction) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("手动处理支付订单回调失败 HandleOrderHandle, err：", err.Error()), 2)
		}
	}()
	outTradeNo := itemCallback.OutTradeNo
	orderDetail, e := order.GetCygxOrderDetailByOutTradeNo(outTradeNo)
	if e != nil {
		err = errors.New("GetCygxOrderDetailByOrderCode, Err: " + e.Error())
		return
	}

	go AddCygxOrderPayment(itemCallback) // 记录支付交易信息

	if itemCallback.TradeState != "SUCCESS" { // 回调显示支付不成功，模版消息推送
		if e != nil {
			err = errors.New("支付失败,  outTradeNo: " + outTradeNo)
			return
		}
	}
	//修改过状态的不再二次处理
	if orderDetail.OrderStatus == 2 {
		return
	}

	itemOrder := new(order.CygxOrder)
	itemOrder.OrderCode = orderDetail.OrderCode
	itemOrder.PayTime = itemCallback.SuccessTime
	itemOrder.PayMoney = float64(float64(itemCallback.Amount.PayerTotal) / 100) // 金额分转换处理
	itemOrder.OrderStatus = 2
	itemOrder.OutTradeCode = itemCallback.TransactionId
	itemOrder.TradeType = itemCallback.TradeType

	//文章处理逻辑  	OrderType        int       `comment:"订单类型，1:畅读卡订单，2：单场付费订单"`
	if orderDetail.OrderType == 1 {
		itemUserCard := new(order.CygxOrderUserCard)
		itemUserCard.OrderCode = orderDetail.OrderCode
		itemUserCard.UserId = orderDetail.UserId
		itemUserCard.Mobile = orderDetail.Mobile
		itemUserCard.Email = orderDetail.Email
		itemUserCard.CompanyId = orderDetail.CompanyId
		itemUserCard.CompanyName = orderDetail.CompanyName
		itemUserCard.RealName = orderDetail.RealName
		itemUserCard.SellerName = orderDetail.SellerName
		itemUserCard.CreateTime = time.Now()
		itemUserCard.ModifyTime = time.Now()
		itemUserCard.RegisterPlatform = orderDetail.RegisterPlatform

		if orderDetail.GoodsId == 1 {
			itemUserCard.StartDate = itemOrder.PayTime
			itemUserCard.EndDate = itemOrder.PayTime.AddDate(0, 0, 1)
			itemUserCard.CardType = "日卡"
		} else {
			now := time.Now()
			itemUserCard.StartDate = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
			itemUserCard.EndDate = itemUserCard.StartDate.AddDate(0, 1, 0)
			itemUserCard.CardType = "月卡"
		}
		e = order.AddCygxOrderUserCard(itemUserCard, itemOrder)
		if e != nil {
			err = errors.New("AddCygxOrderUserCard, Err: " + e.Error())
			return
		}
	} else if orderDetail.OrderType == 2 || orderDetail.OrderType == 3 {
		//如果是活动，把单场付费信息的活动写入 用户虚拟资产表
		itemOrderVirtualAsset := new(order.CygxOrderVirtualAsset)
		itemOrderVirtualAsset.OrderCode = orderDetail.OrderCode
		itemOrderVirtualAsset.UserId = orderDetail.UserId
		itemOrderVirtualAsset.Mobile = orderDetail.Mobile
		itemOrderVirtualAsset.Email = orderDetail.Email
		itemOrderVirtualAsset.CompanyId = orderDetail.CompanyId
		itemOrderVirtualAsset.CompanyName = orderDetail.CompanyName
		itemOrderVirtualAsset.RealName = orderDetail.RealName
		itemOrderVirtualAsset.SellerName = orderDetail.SellerName
		itemOrderVirtualAsset.Source = orderDetail.Source
		itemOrderVirtualAsset.SourceId = orderDetail.SourceId
		itemOrderVirtualAsset.CreateTime = time.Now()
		itemOrderVirtualAsset.ModifyTime = time.Now()
		e = order.AddCygxOrderVirtualAsset(itemOrderVirtualAsset, itemOrder)
		if e != nil {
			err = errors.New("AddCygxOrderVirtualAsset, Err: " + e.Error())
			return
		}
	}
	if orderDetail.Source == utils.CYGX_OBJ_ACTIVITY {
		go AddActivitySignupByWechatPay(orderDetail.SourceId, orderDetail.UserId) //微信付款成功自动添加报名
	}
	go CancelOtherOrder(orderDetail) //付款成功之后自动取消其他相同的订单

	return
}

// 添加操作记录
func AddCygxOrderPayment(itemCallback *Transaction) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("处理订单回调信息失败 HandleOrderHandle, err：", err.Error()), 2)
		}
	}()
	itemPay := new(order.CygxOrderPayment)
	itemPay.OrderCode = itemCallback.OutTradeNo
	itemPay.OutTradeCode = itemCallback.TransactionId
	itemPay.PayBody = itemCallback.TradeStateDesc
	jsonData, _ := json.Marshal(itemCallback)
	itemPay.PayDetail = string(jsonData)
	itemPay.PayMoney = float64(float64(itemCallback.Amount.PayerTotal) / 100) // 金额分转换处理
	itemPay.PayStatus = itemCallback.TradeState
	itemPay.CreateTime = time.Now()
	itemPay.PaymentType = 1
	e := order.AddCygxOrderPayment(itemPay)
	if e != nil {
		err = errors.New("AddCygxOrderPayment, Err: " + e.Error())
		return
	}
	return
}

// 定时任务处理退款回调
func HandleOrderRefundTask(cont context.Context) (err error) {
	//func HandleOrderRefundTask() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("定时任务处理退款回调 HandleOrderRefundTask ，err：", err.Error()), 2)
		}
	}()
	var condition string
	var pars []interface{}
	//endTime := time.Now().Add(-10 * time.Minute)
	condition = ` AND order_status = 4    ` //获取十分钟之内待支付的订单
	//pars = append(pars, endTime)
	orderList, e := order.GetCygxOrderList(condition, pars, 0, 999)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxOrderList, Err: " + e.Error())
		return
	}
	fmt.Println(len(orderList))
	if len(orderList) == 0 {
		return
	}
	//订单量不大，先这么写吧
	for _, v := range orderList {
		tradeState, statusCode, itemResp := GetQueryOrderByOutTradeNo(v.OutTradeNo)
		if tradeState == "REFUND" && statusCode == 200 {
			go HandleOrderRefundByWechatPay(itemResp)
		}
	}
	return
}

// 处理退款订单回调
func HandleOrderRefundByWechatPay(itemCallback *Transaction) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("处理退款订单回调信息失败 HandleOrderRefundByWechatPay, err：", err.Error()), 2)
		}
	}()
	outTradeNo := itemCallback.OutTradeNo
	orderDetail, e := order.GetCygxOrderDetailByOutTradeNo(outTradeNo)
	if e != nil {
		err = errors.New("GetCygxOrderDetailByOrderCode, Err: " + e.Error())
		return
	}

	//go AddCygxOrderPayment(itemCallback) // 记录支付交易信息

	//修改过状态的不再二次处理
	if orderDetail.OrderStatus == 3 {
		return
	}

	itemOrder := new(order.CygxOrder)
	itemOrder.OrderCode = orderDetail.OrderCode
	itemOrder.RefundTime = itemCallback.SuccessTime
	itemOrder.RefundMoney = float64(float64(itemCallback.Amount.PayerTotal) / 100) // 金额分转换处理
	itemOrder.OrderStatus = 3

	//文章处理逻辑  	OrderType        int       `comment:"订单类型，1:畅读卡订单，2：单场付费订单"`
	if orderDetail.OrderType == 1 {
		itemUserCard := new(order.CygxOrderUserCard)
		itemUserCard.OrderCode = orderDetail.OrderCode
		itemUserCard.UserId = orderDetail.UserId
		itemUserCard.Mobile = orderDetail.Mobile
		itemUserCard.Email = orderDetail.Email
		itemUserCard.CompanyId = orderDetail.CompanyId
		itemUserCard.CompanyName = orderDetail.CompanyName
		itemUserCard.RealName = orderDetail.RealName
		itemUserCard.SellerName = orderDetail.SellerName
		itemUserCard.CreateTime = time.Now()
		itemUserCard.ModifyTime = time.Now()
		itemUserCard.RegisterPlatform = orderDetail.RegisterPlatform

		if orderDetail.GoodsId == 1 {
			itemUserCard.CardType = "日卡"
		} else {
			itemUserCard.CardType = "月卡"
		}
		e = order.RemoveCygxOrderUserCard(itemUserCard, itemOrder) // 移除用户
		if e != nil {
			err = errors.New("RemoveCygxOrderUserCard, Err: " + e.Error())
			return
		}
	} else if orderDetail.OrderType == 2 || orderDetail.OrderType == 3 {
		//如果是活动，把单场付费信息的活动写入 用户虚拟资产表
		itemOrderVirtualAsset := new(order.CygxOrderVirtualAsset)
		itemOrderVirtualAsset.OrderCode = orderDetail.OrderCode
		itemOrderVirtualAsset.UserId = orderDetail.UserId
		itemOrderVirtualAsset.Mobile = orderDetail.Mobile
		itemOrderVirtualAsset.Email = orderDetail.Email
		itemOrderVirtualAsset.CompanyId = orderDetail.CompanyId
		itemOrderVirtualAsset.CompanyName = orderDetail.CompanyName
		itemOrderVirtualAsset.RealName = orderDetail.RealName
		itemOrderVirtualAsset.SellerName = orderDetail.SellerName
		itemOrderVirtualAsset.Source = orderDetail.Source
		itemOrderVirtualAsset.SourceId = orderDetail.SourceId
		itemOrderVirtualAsset.CreateTime = time.Now()
		itemOrderVirtualAsset.ModifyTime = time.Now()
		e = order.RemoveCygxOrderVirtualAsset(itemOrderVirtualAsset, itemOrder)
		if e != nil {
			err = errors.New("AddCygxOrderVirtualAsset, Err: " + e.Error())
			return
		}
	}
	//if orderDetail.Source == utils.CYGX_OBJ_ACTIVITY {
	//	go CancelActivitySignupByWechatPay(orderDetail.SourceId, orderDetail.UserId) //微信退款成功自动取消报名
	//}
	return
}

// 微信付款成功自动添加报名
func AddActivitySignupByWechatPay(activityId, userId int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("微信付款成功自动添加报名失败 AddActivitySignupByWechatPay, err：", err.Error(), "activityId:", activityId, "userId:", userId), 2)
		}
	}()
	activityInfo, e := models.GetAddActivityInfoById(activityId)
	if e != nil {
		err = errors.New("GetAddActivityInfoById, Err: " + e.Error())
		return
	}
	var userPointsNum float64
	if activityInfo.IsResearchPoints {
		//获取活动对用户要扣的点
		userPointsNum, e = models.GetCygxActivityPointsSetUserNum(activityInfo.ActivityId)
		if e != nil {
			err = errors.New("GetCygxActivityPointsSetUserNum, Err: " + e.Error())
			return
		}
	}

	//专家线下沙龙与买方线下交流、扣点的公司调研电话会自动报名
	if activityInfo.ActivityTypeId != 5 && activityInfo.ActivityTypeId != 8 && userPointsNum == 0 {
		return
	}

	user, e := models.GetWxUserItemByUserId(userId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId, Err: " + e.Error())
		return
	}
	var sellerName string
	sellerName, e = models.GetCompanySellerName(user.CompanyId)
	if e != nil {
		err = errors.New("GetCompanySellerName, Err: " + e.Error())
		return
	}

	item := new(models.CygxActivitySignup)
	totalMySuccess, e := models.GetActivitySignupCount(userId, activityId)
	if e != nil {
		err = errors.New("AddActivitySignup, Err: " + e.Error())
		return
	}
	if totalMySuccess > 0 { //已报名这个活动
		return
	}
	item.UserId = userId
	item.RealName = user.RealName
	item.SellerName = sellerName
	item.ActivityId = activityId
	item.CreateTime = time.Now()
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.CompanyName = user.CompanyName
	item.SignupType = 3
	item.FailType = 0
	item.DoFailType = 0
	item.OutboundMobile = user.Mobile
	if user.OutboundMobile != "" {
		item.OutboundMobile = user.OutboundMobile
		if user.OutboundCountryCode == "" {
			item.CountryCode = "86"
		} else {
			item.CountryCode = user.OutboundCountryCode
		}
	} else {
		item.OutboundMobile = user.Mobile
		if user.CountryCode == "" {
			item.CountryCode = "86"
		} else {
			item.CountryCode = user.CountryCode
		}
	}
	_, e = models.AddActivitySignup(item)
	if e != nil {
		err = errors.New("AddActivitySignup, Err: " + e.Error())
		return
	}
	fmt.Println("报名成功")
	go ActivityUserRemind(user, activityInfo, 4)

	return
}

// 微信退款成功自动取消报名
func CancelActivitySignupByWechatPay(activityId, userId int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("微信退款成功自动取消报名失败 CancelActivitySignupByWechatPay, err：", err.Error(), "activityId:", activityId, "userId:", userId), 2)
		}
	}()
	activityInfo, e := models.GetAddActivityInfoById(activityId)
	if e != nil {
		err = errors.New("GetAddActivityInfoById, Err: " + e.Error())
		return
	}

	user, e := models.GetWxUserItemByUserId(userId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId, Err: " + e.Error())
		return
	}

	item := new(models.CygxActivitySignup)
	item.UserId = userId
	item.ActivityId = activityId
	item.CreateTime = time.Now()
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.CompanyName = user.CompanyName
	resp := new(models.SignupStatus)
	resp.ActivityId = activityId
	_, e = models.CancelActivitySignup(item)
	if e != nil {
		err = errors.New("CancelActivitySignup, Err: " + e.Error())
		return
	}

	// 如果是买方研选下的专家沙龙，同时推给内容组四人
	if activityInfo.ActivityTypeId == 5 {
		go SendActivitieCancelSignTemplateMsg(user, activityInfo)
	}
	go SendResearchActivitiesTemplateMsg(user, activityInfo, "取消报名") //公司线下调研活动客户报名后给建会人，所属销售推送模板信息

	return
}

// 付款成功之后自动取消其他相同的订单
func CancelOtherOrder(item *order.CygxOrder) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("付款成功之后自动取消其他相同的订单失败 CancelOtherOrder, err：", err.Error(), "order_id:", item.OrderId), 2)
		}
	}()

	var condition string
	var pars []interface{}
	userId := item.UserId

	//判断是日卡月卡还是单场付费活动
	if item.GoodsId == 1 || item.GoodsId == 2 {
		condition += ` AND user_id  = ?  AND  goods_id IN (1,2)  AND  order_id  != ? AND  order_status = 1  `
		pars = append(pars, userId, item.OrderId)
	} else {
		condition += ` AND user_id  = ?  AND  source_id = ?   AND  source = ?  AND  order_id  != ? AND  order_status = 1  `
		pars = append(pars, userId, item.SourceId, item.Source, item.OrderId)
	}

	listOrder, e := order.GetCygxOrderDetailList(condition, pars) // 这里就一条数据
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxOrderDetailList, Err: " + e.Error())
		return
	}
	if len(listOrder) == 0 {
		err = nil
		return
	}
	for _, v := range listOrder {
		e = order.CancelCygxOrder(v)
		if e != nil {
			return
		}
	}
	return
}
