package app

import (
	"bwallet/models"
	"bwallet/pkg/errno"
	"bwallet/pkg/handler"
	"bwallet/pkg/util"
	"bwallet/service/live_charge_service"
	"bwallet/service/live_info_service"
	"bwallet/service/live_title_record_service"
	"bwallet/validate_service"
	"github.com/Unknwon/com"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
)

func AddLive(c *gin.Context) {
	info := validate_service.LiveInfo{}
	c.ShouldBindJSON(&info)

	//方法一
	if ok, errors := validate_service.ValidateInputs(info); !ok {
		for _, err := range errors {
			handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
			return
		}
	}

	chargeService := live_charge_service.LiveCharge{
		PlatformId: info.PlatformId,
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}
	charge, err := chargeService.GetAll()
	if err != nil || len(charge) == 0 {
		handler.SendResponse(c, errno.ErrAddLiveInfo, nil)
		return
	}

	infoService := live_info_service.LiveInfo{
		Title:      info.Title,
		Cover:      info.Cover,
		CategoryId: info.CategoryId,
		Duration:   info.Duration,
		ApplyId:    info.ApplyId,
		ApplyName:  info.ApplyName,
		PlatformId: info.PlatformId,
		Unit:       charge[0].Unit,
		Price:      info.Price,
	}

	if err := infoService.Add(); err != nil {
		handler.SendResponse(c, errno.ErrAddLiveInfo, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}

func GetLiveInfos(c *gin.Context) {
	valid := validation.Validation{}

	platform_id, _ := strconv.Atoi(c.Request.Header.Get("FZM-PLATFORM-ID"))
	valid.Min(platform_id, 1, "platform_id").Message("平台Id不能为空")

	apply_id := com.StrTo(c.DefaultQuery("apply_id", "0")).MustInt()
	valid.Required(apply_id, "apply_id").Message("申请者参数不能为空")

	if valid.HasErrors() {
		handler.SendResponse(c, valid.Errors[0], nil)
		return
	}

	status := com.StrTo(c.DefaultQuery("status", "0")).MustUint8()
	live_status := com.StrTo(c.DefaultQuery("live_status", "0")).MustUint8()
	infoService := live_info_service.LiveInfo{
		Status:     status,
		LiveStatus: live_status,
		ApplyId:    uint32(apply_id),
		PlatformId: int64(platform_id),
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

	total, err := infoService.Count()
	if err != nil {
		handler.SendResponse(c, errno.ErrCountLiveInfo, nil)
		return
	}

	info, err := infoService.GetAllForClient()
	if err != nil {
		handler.SendResponse(c, errno.InternalServerError, nil)
		return
	}

	data := make(map[string]interface{})
	data["items"] = info
	data["total"] = total

	handler.SendResponse(c, nil, data)
}

func ModifyTitle(c *gin.Context) {
	platform_id, _ := strconv.Atoi(c.Request.Header.Get("FZM-PLATFORM-ID"))
	valid := validation.Validation{}
	valid.Min(platform_id, 1, "platform_id").Message("平台Id不能为空")
	if valid.HasErrors() {
		handler.SendResponse(c, valid.Errors[0], nil)
		return
	}

	info := validate_service.ModifyLiveTitle{}
	c.ShouldBindJSON(&info)

	if ok, errors := validate_service.ValidateInputs(info); !ok {
		for _, err := range errors {
			handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
			return
		}
	}

	infoService := live_info_service.LiveInfo{
		Id:      info.Id,
		ApplyId: info.ApplyId,
	}

	count, err := infoService.Count()
	if 0 == count || err != nil {
		handler.SendResponse(c, errno.ErrLiveInfoNotFound, nil)
		return
	}

	model, err := infoService.GetOneLiveInfo()
	if err != nil {
		handler.SendResponse(c, errno.ErrLiveInfoNotFound, nil)
		return
	}

	recordService := live_title_record_service.LiveTitleRecord{
		LiveId:       info.Id,
		CurrentTitle: model.Title,
		Status:       0,
		NewTitle:     info.Title,
		PlatformId:   int64(platform_id),
	}

	if err := recordService.Add(); err != nil {
		handler.SendResponse(c, errno.ErrUpdateLiveInfo, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}

func LiveStatus(c *gin.Context) {
	valid := validation.Validation{}

	apply_id := com.StrTo(c.DefaultQuery("apply_id", "0")).MustInt()
	valid.Required(apply_id, "apply_id").Message("申请者参数不能为空")

	order_sn := com.StrTo(c.DefaultQuery("order_sn", "")).MustInt64()
	valid.Required(order_sn, "order_sn").Message("订单号参数不能为空")

	if valid.HasErrors() {
		handler.SendResponse(c, valid.Errors[0], nil)
		return
	}

	live_service := live_info_service.LiveInfo{
		ApplyId:  uint32(apply_id),
		OrderSn:  order_sn,
		Status:   models.PEDDING_PAYMENT,
		PageNum:  util.GetPage(c),
		PageSize: util.GetLimit(c),
	}
	live, err := live_service.LiveCharge()
	if err != nil {
		handler.SendResponse(c, errno.InternalServerError, nil)
		return
	}

	if 0 == len(live) {
		handler.SendResponse(c, errno.ErrLiveChargeNotFound, nil)
		return
	}

	handler.SendResponse(c, nil, live[0])
}

func VerifyStatus(c *gin.Context) {
	info := validate_service.VerifyStatus{}
	c.ShouldBindJSON(&info)

	if ok, errors := validate_service.ValidateInputs(info); !ok {
		for _, err := range errors {
			handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
			return
		}
	}

	live_service := live_info_service.LiveInfo{
		OrderSn:  info.OrderSn,
		Status:   models.PEDDING_PAYMENT,
		PageNum:  util.GetPage(c),
		PageSize: util.GetLimit(c),
	}
	live, err := live_service.LiveCharge()
	if err != nil {
		handler.SendResponse(c, errno.InternalServerError, nil)
		return
	}

	if 0 == len(live) {
		handler.SendResponse(c, errno.ErrLiveChargeNotFound, nil)
		return
	}

	if live[0].Status != uint8(models.PEDDING_PAYMENT) {
		handler.SendResponse(c, errno.ErrUpdateLiveInfo, nil)
		return
	}

	if info.LiveStatus != uint8(models.LIVEED) {
		handler.SendResponse(c, errno.ErrUpdateLiveInfo, nil)
		return
	}

	modify_service := live_info_service.LiveInfo{
		Id:         live[0].Id,
		LiveStatus: info.LiveStatus,
	}

	if err := modify_service.UpdateStatus(); err != nil {
		handler.SendResponse(c, errno.ErrUpdateLiveInfo, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}

func NotifyUrl(c *gin.Context) {
	info := validate_service.NotifyUrl{}
	c.ShouldBindJSON(&info)

	if ok, errors := validate_service.ValidateInputs(info); !ok {
		for _, err := range errors {
			handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
			return
		}
	}

	live_service := live_info_service.LiveInfo{
		OrderSn:  info.OrderSn,
		Status:   models.PEDDING_PAYMENT,
		PageNum:  util.GetPage(c),
		PageSize: util.GetLimit(c),
	}
	live, err := live_service.LiveCharge()
	if err != nil {
		handler.SendResponse(c, errno.InternalServerError, nil)
		return
	}

	if 0 == len(live) {
		handler.SendResponse(c, errno.ErrLiveChargeNotFound, nil)
		return
	}

	if live[0].Price != info.Price {
		handler.SendResponse(c, errno.ErrPrice, nil)
		return
	}

	modify_service := live_info_service.LiveInfo{
		Id:         live[0].Id,
		LiveStatus: models.PEDDING_LIVE,
	}

	if err := modify_service.UpdateStatus(); err != nil {
		handler.SendResponse(c, errno.ErrUpdateLiveInfo, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}

func GetLiveCharge(c *gin.Context) {
	platform_id, _ := strconv.Atoi(c.Request.Header.Get("FZM-PLATFORM-ID"))
	valid := validation.Validation{}
	valid.Min(platform_id, 1, "platform_id").Message("平台Id不能为空")
	if valid.HasErrors() {
		handler.SendResponse(c, valid.Errors[0], nil)
		return
	}

	live_charge_service := live_charge_service.LiveCharge{
		PlatformId: int64(platform_id),
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

	charge, err := live_charge_service.GetAll()
	if err != nil {
		handler.SendResponse(c, errno.InternalServerError, nil)
		return
	}

	if len(charge) == 0 {
		handler.SendResponse(c, errno.ErrLiveChargeNotFound, nil)
		return
	}

	data := make(map[string]interface{})
	data["uint"] = charge[0].Unit
	data["uint_price"] = charge[0].UnitPrice

	handler.SendResponse(c, nil, data)
}
