package v1

import (
	"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"
	"github.com/xuri/excelize/v2"
	"go.uber.org/zap"
	"strconv"
	"time"
)

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

	if req.OrderType == "1" {
		req.VipLevel = "1,3"
	}
	if req.OrderType == "2" {
		req.VipLevel = "2"
	}

	req.UserType = global.GVA_CONFIG.System.Usertype

	err, list, total := service.GetVipOrderList(req)

	for k, v := range list {
		list[k].OrderType = v.VipLevel
		if v.VipLevel == 3 {
			list[k].OrderType = 1
		}
	}
	reply := request.GetVipOrderListReply{}
	reply.List = list
	reply.Total = total

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

func SetMobileUserVip(c *gin.Context) {
	var req request.OpenVipOwnReq
	_ = c.ShouldBindJSON(&req)
	//用户调用api日志
	apiLog := model.ApiLog{
		UserId: getUserID(c),
		Status: 1,
		Api:    "/adminUser/setMobileUserVip",
		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
		}
	}

	//创建vip订单
	reqVipOrder := model.VipOrder{}
	reqVipOrder.OrderNo = utils.GetOrderNo("V", userId)
	reqVipOrder.UserId = userId
	reqVipOrder.VipLevel = 2
	reqVipOrder.VipMoney = 0
	reqVipOrder.VipDay = req.Day
	reqVipOrder.VipConfId = 2
	reqVipOrder.PayMoney = 0
	reqVipOrder.Status = 2
	reqVipOrder.IsPoints = 0
	reqVipOrder.PointsNum = 0
	reqVipOrder.Remark = req.Remark

	err = service.CreateVipOrder(reqVipOrder)
	if err != nil {
		global.GVA_LOG.Error("支付失败!", zap.Any("err", err))
		response.FailWithMessage("支付失败", c)
		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
}

func ExportVipOrder(c *gin.Context) {
	var req request.GetVipOrderListReq
	_ = c.ShouldBindQuery(&req)

	if req.OrderType == "1" {
		req.VipLevel = "1,3"
	}
	if req.OrderType == "2" {
		req.VipLevel = "2"
	}

	req.PageSize = 99999
	req.UserType = global.GVA_CONFIG.System.Usertype

	_, list, _ := service.GetVipOrderList(req)

	fileName := "谛医会员订单列表" + time.Now().Format("20060102")
	f := excelize.NewFile()
	// Create a new sheet.
	index := f.NewSheet(fileName)

	f.SetCellValue(fileName, "A1", "登录手机号")
	f.SetCellValue(fileName, "B1", "姓名")
	f.SetCellValue(fileName, "C1", "下单时间")
	f.SetCellValue(fileName, "D1", "开通天数")
	f.SetCellValue(fileName, "E1", "订单金额")
	f.SetCellValue(fileName, "F1", "支付金额")
	f.SetCellValue(fileName, "G1", "订单类型")
	f.SetCellValue(fileName, "H1", "备注")

	for k, v := range list {

		orderType := "正常订单"
		if v.VipLevel == 2 {
			orderType = "赠送订单"
		}

		a := strconv.Itoa(k + 2)
		f.SetCellValue(fileName, "A"+a, v.Mobile)
		f.SetCellValue(fileName, "B"+a, v.Name)
		f.SetCellValue(fileName, "C"+a, v.CreateTime)
		f.SetCellValue(fileName, "D"+a, v.VipDay)
		f.SetCellValue(fileName, "E"+a, utils.FeeToString(v.VipMoney))
		f.SetCellValue(fileName, "F"+a, utils.FeeToString(v.PayMoney))
		f.SetCellValue(fileName, "G"+a, orderType)
		f.SetCellValue(fileName, "H"+a, v.Remark)
	}

	// Set active sheet of the workbook.
	f.SetActiveSheet(index)
	// Save xlsx file by the given path.
	if err := f.SaveAs("./" + fileName + ".csv"); err != nil {
		fmt.Println(err)
		return
	}

	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", "./"+fileName+".csv")) //fmt.Sprintf("attachment; filename=%s", filename)对下载的文件重命名
	c.Writer.Header().Add("Content-Type", "application/octet-stream")
	c.File("./" + fileName + ".csv")
	return
}
