package mobile

import (
	"errors"
	"fmt"
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"
	"gin-vue-admin/model/response"
	"gin-vue-admin/service"
	"gin-vue-admin/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"time"
)

func OpenVip(c *gin.Context) {
	var req request.OpenVipReq
	_ = c.ShouldBindJSON(&req)

	//response.OkWithData(gin.H{"reply": req}, c)
	//return

	err, vipConf := service.GetVipConf(req.VipId)
	if err != nil {
		global.GVA_LOG.Error("支付失败!", zap.Any("err", err))
		response.FailWithMessage("支付失败", c)
		return
	}

	userId := getUserID(c)

	err, userData := service.GetUserInfo(userId)
	if err != nil {
		global.GVA_LOG.Error("支付失败!", zap.Any("err", err))
		response.FailWithMessage("支付失败", c)
		return
	}

	if req.IsPoints == 1 {
		req.Money = req.Money - req.PointsNum
	}

	if req.IsPoints == 1 && req.PointsNum > (userData.PointsNum-userData.PointsNumFreeze) {
		fmt.Println(req.PointsNum, userData.PointsNum)
		response.FailWithMessage("支付失败,积分数量不足", c)
		return
	}

	if req.IsPoints == 1 && vipConf.VipMoney != req.Money+req.PointsNum {
		fmt.Println(vipConf.VipMoney, req.Money, req.PointsNum)
		response.FailWithMessage("支付失败,支付金额有误", c)
		return
	}

	if req.Money < 1 {
		fmt.Println(req.Money)
		response.FailWithMessage("支付失败,支付金额有误", c)
		return
	}

	//创建vip订单
	reqVipOrder := model.VipOrder{}
	reqVipOrder.OrderNo = utils.GetOrderNo("V", int(userId))
	reqVipOrder.UserId = int(userId)
	reqVipOrder.VipLevel = vipConf.VipLevel
	reqVipOrder.VipMoney = vipConf.VipMoney
	reqVipOrder.VipDay = vipConf.VipDay
	reqVipOrder.VipConfId = vipConf.Id
	reqVipOrder.PayMoney = req.Money
	reqVipOrder.Status = 1
	reqVipOrder.IsPoints = req.IsPoints
	reqVipOrder.PointsNum = req.PointsNum

	err = service.CreateVipOrder(reqVipOrder)
	if err != nil {
		global.GVA_LOG.Error("支付失败!", zap.Any("err", err))
		response.FailWithMessage("支付失败", c)
		return
	}

	if req.IsPoints == 1 {
		//创建积分订单
		reqPointsOrder := model.PointsOrder{}
		reqPointsOrder.UserId = int(userId)
		reqPointsOrder.PayType = 1
		reqPointsOrder.PayStatus = 1
		reqPointsOrder.PointsNo = utils.GetOrderNo("P", int(userId))
		reqPointsOrder.PointsNum = req.PointsNum
		reqPointsOrder.OtherNo = reqVipOrder.OrderNo
		reqPointsOrder.Remark = "vip抵扣"

		err = service.CreatePointsOrder(reqPointsOrder)
		if err != nil {
			global.GVA_LOG.Error("支付失败!", zap.Any("err", err))
			response.FailWithMessage("支付失败", c)
			return
		}
	}

	//发起支付
	orderPay := new(request.OrderPayReq)
	orderPay.OrderNo = reqVipOrder.OrderNo
	orderPay.PayMoney = float64(req.Money) / 100
	orderPay.WxCode = req.WxCode
	orderPay.PayCallBack = global.GVA_CONFIG.Pay.PayCallBack
	orderPay.UserType = req.UserType

	if req.Openid == "" {
		//orderPay.Openid = userData.Openid
		global.GVA_LOG.Error("openid为空", zap.Any("err", err))
		//response.FailWithMessage("用户数据有误", c)
		//return
	} else {
		orderPay.Openid = req.Openid
	}

	//req.Openid = ""

	reply, err := goPay(orderPay)
	if err != nil {
		global.GVA_LOG.Error("支付失败!", zap.Any("err", err))
		response.FailWithMessage("支付失败", c)
		return
	}

	//fmt.Println(reply)
	response.OkWithData(gin.H{"reply": reply}, c)
	return
}

func goPay(orderPay *request.OrderPayReq) (interface{}, error) {
	//orderPayLog, _ := json.Marshal(orderPay)

	//收款账户配置
	var err error
	if orderPay.Openid == "" {
		//orderPay.Openid, err = wx.GetOpenId(global.GVA_CONFIG.Bkwx.Appid,
		//	global.GVA_CONFIG.Bkwx.Appsecret, orderPay.WxCode)
		//获取openid
		//if err != nil || orderPay.Openid == "" {
		//fmt.Println(err)
		return nil, errors.New("openid不存在，支付失败")
		//}
	}

	confData := service.GetSysConf("pay_conf")
	confVal := new(request.SysConfPayConf)
	utils.UnserislizeJson(confData, confVal)

	data, err := utils.Pay(orderPay, confVal.PayNum)

	if err != nil || data == nil {
		return "", err
	}
	//data = orderPay.OrderNo
	return data, nil
}

func GetVipList(c *gin.Context) {
	var req request.GetVipConfListReq
	_ = c.ShouldBindJSON(&req)

	req.IsNewUser = 1
	if service.IsNewUser(int(getUserID(c))) > 0 {
		req.IsNewUser = 0
	}
	err, list, total := service.GetVipConfList(req)
	reply := request.GetVipConfListReply{}
	reply.List = list
	reply.Total = total

	if pointsConf := service.GetSysConf("points"); pointsConf != "" {
		confValPoints := new(request.SysConfPoints)
		utils.UnserislizeJson(pointsConf, confValPoints)
		reply.SysConfPoints = *confValPoints
	}

	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Any("err", err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithDetailed(reply, "获取成功", c)
	}
	return
}

func CallBack(c *gin.Context) {
	var req request.CallBackReq
	_ = c.ShouldBindJSON(&req)

	_, logData := service.GetApiLogInfoForReq(string(utils.SerializeJson(req)))
	if logData.Id > 0 {
		return
	}

	//用户调用api日志
	apiLog := model.ApiLog{
		UserId: 1,
		Status: 1,
		Api:    "/vip/callBack",
		Req:    string(utils.SerializeJson(req)),
		Reply:  "",
	}
	service.CreateApiLog(apiLog)

	err, vipOrder := service.GetVipOrder(req.AttachInfo)
	if err != nil {
		fmt.Println("GetVipOrder", err)
	}

	if vipOrder.Status == 2 {
		//return
	}

	//修改订单信息
	err = service.UpdateVipOrder(req)
	if err != nil {
		fmt.Println("UpdateVipOrder", err)
	}

	if req.AttachInfo[0:3] == "WXP" {

	} else {
		err, vipUser := service.GetVipUser(vipOrder.UserId)
		if err != nil {
			fmt.Println("GetVipUser", err)
		}

		if vipOrder.IsPoints == 1 && vipOrder.PointsNum != 0 {
			//修改积分订单，扣减积分
			err = service.UpdatePointsOrderForOtherNo(req.AttachInfo)
			if err != nil {
				fmt.Println("UpdatePointsOrderForOtherNo", err)
			}
			err = service.UpdateUserPoints(vipOrder.UserId, 2, vipOrder.PointsNum)
			if err != nil {
				fmt.Println("UpdateUserPoints", err)
			}

			err, userData := service.GetUserInfo(uint(vipOrder.UserId))
			if err != nil {
				fmt.Println("GetUserInfo", err)
			}

			cTime := time.Now()
			//积分流水
			reqPointsLog := model.PointsLog{}
			reqPointsLog.UserId = vipOrder.UserId
			reqPointsLog.ChangeType = 3
			reqPointsLog.ChangeTime = cTime
			reqPointsLog.ChangeNum = vipOrder.PointsNum
			reqPointsLog.NowPointsNum = userData.PointsNum
			reqPointsLog.Remark = "VIP业务"
			reqPointsLog.OtherNo = req.AttachInfo
			reqPointsLog.Source = 2
			reqPointsLog.CreateTime = cTime

			err = service.CreatePointsLog(reqPointsLog)
			if err != nil {
				global.GVA_LOG.Error("赠送失败!", zap.Any("err", err))
				response.FailWithMessage("赠送失败", c)
				return
			}
		}

		//增加时间
		if vipUser.Id != 0 {
			reqVipUser := model.VipUser{}
			reqVipUser.UserId = vipOrder.UserId
			reqVipUser.VipLevel = vipOrder.VipLevel

			if time.Now().Before(vipUser.MaturityTime) {
				reqVipUser.MaturityTime = vipUser.MaturityTime.AddDate(0, 0, vipOrder.VipDay)
			} else {
				reqVipUser.MaturityTime = time.Now().AddDate(0, 0, vipOrder.VipDay)
			}

			if err := service.UpdateVipUser(reqVipUser, vipOrder.UserId); err != nil {
				global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
				response.FailWithMessage("创建失败", c)
			} else {
				response.OkWithMessage("创建成功", c)
			}
		} else {
			reqVipUser := model.VipUser{}
			reqVipUser.UserId = vipOrder.UserId
			reqVipUser.VipLevel = vipOrder.VipLevel
			reqVipUser.MaturityTime = time.Now().AddDate(0, 0, vipOrder.VipDay)

			if err := service.CreateVipUser(reqVipUser); err != nil {
				global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
				response.FailWithMessage("创建失败", c)
			} else {
				response.OkWithMessage("创建成功", c)
			}
		}
	}

	return
}

func OpenVipOwn(c *gin.Context) {
	var req request.OpenVipOwnReq
	_ = c.ShouldBindJSON(&req)

	//用户调用api日志
	apiLog := model.ApiLog{
		UserId: 1,
		Status: 1,
		Api:    "/vip/openVipOwn",
		Req:    string(utils.SerializeJson(req)),
		Reply:  "",
	}
	service.CreateApiLog(apiLog)

	userInfo := service.FindUserByMobile(req.Mobile)

	if userInfo.ID == 0 {
		response.FailWithMessage("用户未注册", c)
		return
		//user := model.SysUser{
		//	Mobile: req.Mobile,
		//}
		//_, userInfo = service.UserRegister(user)
	}

	userId := int(userInfo.ID)

	var replyVipUser model.VipUser
	var err error

	if service.IsVipUser(userId) == 1 {
		err, replyVipUser = service.GetVipUser(userId)
		if err != nil {
			fmt.Println(err)
			return
		}
	}

	reqVipUser := model.VipUser{}

	reqVipUser.UserId = userId
	reqVipUser.VipLevel = 2

	//增加时间
	if replyVipUser.Id != 0 {

		if time.Now().Before(replyVipUser.MaturityTime) {
			reqVipUser.MaturityTime = replyVipUser.MaturityTime.AddDate(0, 0, req.Day)
		} else {
			reqVipUser.MaturityTime = time.Now().AddDate(0, 0, req.Day)
		}

		if err := service.UpdateVipUser(reqVipUser, userId); err != nil {
			global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
			response.FailWithMessage("创建失败", c)
			return
		}
	} else {
		reqVipUser.MaturityTime = time.Now().AddDate(0, 0, req.Day)

		if err := service.CreateVipUser(reqVipUser); err != nil {
			global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
			response.FailWithMessage("创建失败", c)
			return
		}
	}
	response.OkWithData(reqVipUser, c)
	return
}
