// Package dao -----------------------------
// @file      : artwork.go
// @author    : JJXu
// @contact   : wavingbear@163.com
// @time      : 2023/2/24 18:23
// -------------------------------------------
package dao

import (
	"errors"
	"github.com/fonchain/fonchain-artistinfo/cmd/model"
	"github.com/fonchain/fonchain-artistinfo/pb/artistInfoArtwork"
	db "github.com/fonchain/fonchain-artistinfo/pkg/db"
	"github.com/fonchain/fonchain-artistinfo/pkg/util/stime"
	"gorm.io/gorm"
	"time"
)

func CreateArtworkLockRecord(in *model.ArtworkLockRecord) error {
	var data = model.ArtworkLockRecord{
		ArtistUid:  in.ArtistUid,
		ArtworkUid: in.ArtworkUid,
		Status:     in.Status,
		LockTime:   in.LockTime,
	}
	return db.DB.Create(&data).Error
}

func UpdateArtworkLockRecord(in *model.ArtworkLockRecord) error {
	var data = model.ArtworkLockRecord{
		ArtistUid:             in.ArtistUid,
		ArtworkUid:            in.ArtworkUid,
		Status:                in.Status,
		LockTime:              in.LockTime,
		BaseAuditStatus:       in.BaseAuditStatus,
		BaseAuditMark:         in.BaseAuditMark,
		BaseAuditMark2:        in.BaseAuditMark2,
		SupplementAuditStatus: in.SupplementAuditStatus,
		SupplementAuditMark:   in.SupplementAuditMark,
		SupplementAuditMark2:  in.SupplementAuditMark2,
	}
	var thisData model.ArtworkLockRecord
	err := db.DB.Where("artist_uid = ?", in.ArtworkUid).First(&thisData).Error
	if err != nil {
		if err != gorm.ErrRecordNotFound {
			return errors.New("画作数据未找到")
		} else {
			return err
		}
	}
	data.Model = model.Model{
		ID:        thisData.ID,
		CreatedAt: thisData.CreatedAt,
	}
	return db.DB.Updates(&data).Error
}

func DeletedArtworkLockRecord(artworkUid ...string) error {
	if len(artworkUid) == 0 {
		return nil
	} else if len(artworkUid) == 1 {
		return db.DB.Where("artwork_uid = ? AND status != 2 ", artworkUid[0]).Delete(&model.ArtworkLockRecord{}).Error
	} else {
		return db.DB.Where("artwork_uid in ? AND status != 2 ", artworkUid).Delete(&model.ArtworkLockRecord{}).Error
	}
}

func BatchLockArtworks(artistUid string, lockTime string) error {
	var artworkUids []string
	db.DB.Model(model.ArtworkLockRecord{}).
		Where("status = 1 AND lock_time=''").Where(" artist_uid = ?", artistUid).
		Pluck("artwork_uid", &artworkUids)
	if artworkUids == nil {
		return nil
	}
	if lockTime == "" {
		lockTime = stime.TimeToString(time.Now(), stime.Format_Normal_YMDhms)
	}
	var updateMap = map[string]any{
		"status":            2,
		"lock_time":         lockTime,
		"base_audit_status": model.AuditType_Pending, //基本数据审批
		"audit_flow_index":  2,                       //进入基本信息审批流程
	}
	return db.DB.Model(model.ArtworkLockRecord{}).Where("artwork_uid in ?", artworkUids).Updates(&updateMap).Error
}

func BatchUnlockArtworks(artistUid string) error {
	//var artworkUids []string
	// 查询用户当前锁定的时间点
	//var nowLockTime string
	//err := db.DB.Model(model.ArtworkLockRecord{}).Select("MAX(lock_time)").Where("artist_uid = %s AND lock_time !='' AND STATUS =2", artistUid).Scan(&nowLockTime).Error
	//if err != nil {
	//	return err
	//}
	////查询此时间节点内的所有画作
	//db.DB.Model(model.ArtworkLockRecord{}).
	//	//Where("lock_time = (SELECT MAX(lock_time) FROM artwork_lock_record where artist_uid = %s AND lock_time !='' AND STATUS =2)", artistUid).
	//	//Joins("LEFT JOIN (lock_time = (select max(lock_time) form artwork_lock_record WHERE artist_uid = ?) lt", artistUid).
	//	//Where(fmt.Sprintf("lock_time = (select max(lock_time) form artwork_lock_record WHERE artist_uid = %s)", artistUid)).
	//	Where("status = 2").
	//	Pluck("artwork_uid", &artworkUids)
	//if artworkUids == nil {
	//	return nil
	//}
	return db.DB.Model(model.ArtworkLockRecord{}).Where("artist_uid = ? AND status =2 AND lock_time !=''", artistUid).Update("status", 3).Error
}

func GetArtworkLockDetail(artworkUid string) (data model.ArtworkLockRecord, err error) {
	err = db.DB.Where("artwork_uid = ?", artworkUid).First(&data).Error
	return
}

func GetArtworkLockRecords(req *artistInfoArtwork.GetArtworkLockRecordsRequest) (resp *artistInfoArtwork.ArtworkLockList, err error) {
	var (
		datas = []model.ArtworkLockRecord{}
		tx    = db.DB.Model(model.ArtworkLockRecord{}).Order("lock_time desc")
	)
	resp = &artistInfoArtwork.ArtworkLockList{}
	if req.ArtistUid != "" {
		tx = tx.Where("artist_uid = ?", req.ArtistUid)
	}
	switch req.QueryType {
	case artistInfoArtwork.ArtworkQueryMode_NowPreSaveArtwork: //当前暂存的画作
		tx = tx.Where("status = 1")
	case artistInfoArtwork.ArtworkQueryMode_NowLockedArtwork: //当前已锁定的画作
		tx = tx.Where("status = 2")
	case artistInfoArtwork.ArtworkQueryMode_NowPreSaveAndLocked: //当前暂存和已锁定的画作（也就是用户端画作管理中的数据）
		tx = tx.Where("status =1 OR status =2")
	case artistInfoArtwork.ArtworkQueryMode_NowAuditFlowOfBase: //当前处于基本信息审批阶段的画作(包括进入其它流程的画作)
		tx = tx.Where("status = 2") // AND audit_flow_index = 2
	case artistInfoArtwork.ArtworkQueryMode_NowAuditFlowOfSupplementing: //当前处于补充信息审批阶段的画作
		tx = tx.Where("status =2 AND audit_flow_index = 3")
	case artistInfoArtwork.ArtworkQueryMode_AllUnlockArtwork: //所有已解锁的画作(历史画作)
		tx = tx.Where("status = 3 OR status = 2")
		//case artistInfoArtwork.ArtworkQueryMode_AllHistoryArtwork: //所有历史画作
		//	tx = tx.Where("status > 1")
	}
	if req.AuditStatus != 0 {
		tx = tx.Where("audit_status = ?", req.AuditStatus)
	}
	err = tx.Find(&datas).Error
	for _, v := range datas {
		resp.Data = append(resp.Data, &artistInfoArtwork.ArtistLockInfo{
			ArtistUid:             v.ArtistUid,
			ArtworkUid:            v.ArtworkUid,
			Status:                v.Status,
			LockTime:              v.LockTime,
			BaseAuditStatus:       int32(v.BaseAuditStatus),
			BaseAuditMark:         v.BaseAuditMark,
			BaseAuditMark2:        v.BaseAuditMark2,
			SupplementAuditStatus: int32(v.SupplementAuditStatus),
			SupplementAuditMark:   v.SupplementAuditMark,
			SupplementAuditMark2:  v.SupplementAuditMark2,
			AuditFlowIndex:        int32(v.AuditFlowIndex),
			CreatedAt:             v.CreatedAt.Unix(),
			UpdatedAt:             v.UpdatedAt.Unix(),
			DeletedAt:             int64(v.DeletedAt),
		})
	}
	return
}
func HasBeenLocked(artistUid string) bool {
	//检查是否已经被锁定
	var hasLocked int64
	db.DB.Model(model.ArtworkLockRecord{}).Where("artist_uid = ? AND status = 2", artistUid).Count(&hasLocked)
	if hasLocked > 0 {
		return true
	}
	return false
}

// UpdateAuditStatus 更新审批状态
// flowIndex 2=基本信息审批 3=补充信息审批
func UpdateAuditStatus(artworkUid string, auditStatus int64, remark1 string, remark2 string, flowIndex int64) error {
	var thisData model.ArtworkLockRecord
	err := db.DB.Model(model.ArtworkLockRecord{}).Where("artwork_uid = ?", artworkUid).First(&thisData).Error
	if err != nil {
		if err != gorm.ErrRecordNotFound {
			return errors.New("画作数据未找到")
		} else {
			return err
		}
	}
	switch flowIndex {
	case 2:
		thisData.BaseAuditStatus = model.AuditStatus(auditStatus)
		thisData.BaseAuditMark = remark1
		thisData.BaseAuditMark2 = remark2
	case 3:
		thisData.SupplementAuditStatus = model.AuditStatus(auditStatus)
		thisData.SupplementAuditMark = remark1
		thisData.SupplementAuditMark2 = remark2
	}
	return db.DB.Save(&thisData).Error
}

func BatchUpdateAuditStatus(artworkUids []string, auditStatus int64, remark1 string, remark2 string, flowIndex int64) error {
	for _, uid := range artworkUids {
		if err := UpdateAuditStatus(uid, auditStatus, remark1, remark2, flowIndex); err != nil {
			return err
		}
	}
	return nil
}

func GenerateArtworkSupplementInfo(artworkUids []string) error {
	var datas = []model.ArtworkLockRecord{}
	db.DB.Where("artwork_uid in ?", artworkUids).Find(&datas)
	for _, v := range datas {
		if v.BaseAuditStatus != 4 {
			return errors.New("存在基本信息未审批通过的画作,操作取消!")
		}
	}
	var updateData = map[string]any{
		"audit_flow_index":        3,
		"supplement_audit_status": 5,
	}
	return db.DB.Model(model.ArtworkLockRecord{}).Where("artwork_uid in ?", artworkUids).Updates(&updateData).Error
}
