package dao

import (
	"fonchain-artshow/cmd/model"
	"fonchain-artshow/pb/artShow"
	"fonchain-artshow/pkg/db"
	"fonchain-artshow/pkg/m"
	uuid "github.com/satori/go.uuid"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"strings"
	"time"
)

func SaveShowApply(showApply *model.ShowApply) (err error) {
	uid, err := uuid.NewV4()
	if err != nil {
		return err
	}
	showApply.ApplyUID = uid.String()
	showApply.ApplySeq = strings.Join([]string{m.ARTSHOWAPPLY_PREFIX, time.Now().Format("20060102150405")}, "")
	showApply.Status = m.SHOWAPPLYStatusDoing
	err = db.DbArtShow.Model(&model.ShowApply{}).Create(&showApply).Error
	if err != nil {
		zap.L().Error("ShowApply err", zap.Error(err))
		return
	}
	return
}

func UpdateShowApply(showApply *model.ShowApply) (tx *gorm.DB, err error) {
	tx = db.DbArtShow.Begin()
	err = tx.Model(&model.ShowApply{}).Omit("apply_uid").Where("apply_uid = ?", showApply.ApplyUID).Updates(showApply).Error
	if err != nil {
		zap.L().Error("ShowApply err", zap.Error(err))
		return
	}
	return
}

func ShowApplyList(in *artShow.ApplyListReq) (err error, total int64, out []*model.ShowApply) {
	out = make([]*model.ShowApply, 0)
	queryDB := db.DbArtShow.Model(&model.ShowApply{})
	if in.Status == 0 {
		in.Status = m.SHOWAPPLYStatusOk
	}
	queryDB.Where("status = ?", in.Status)

	err = queryDB.Count(&total).Error
	if err != nil {
		zap.L().Error("ShowApplyList count err", zap.Error(err))
		return
	}

	if in.PageSize != 0 {
		queryDB = queryDB.Offset(int((in.Page - 1) * in.PageSize)).
			Limit(int(in.PageSize))
	}
	err = queryDB.Find(&out).Error
	if err != nil {
		zap.L().Error("ShowApplyList err", zap.Error(err))
		return
	}
	return
}

func ShowApplyDetail(applyUID string) (err error, out *model.ShowApply) {
	out = new(model.ShowApply)
	err = db.DbArtShow.Model(&model.ShowApply{}).Where("apply_uid = ?", applyUID).Find(&out).Error
	if err != nil {
		zap.L().Error("ShowApplyDetail err", zap.Error(err))
		return
	}
	return
}

func DelShowApply(in *artShow.DelApplyReq) (tx *gorm.DB, err error) {
	tx = db.DbArtShow.Begin()
	err = tx.Where("apply_uid = ?", in.ApplyUID).Delete(&model.ShowApply{}).Error
	if err != nil {
		zap.L().Error("ShowApply delete   err", zap.Error(err))
		return
	}
	return
}
