package dao

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/fonchain/fonchain-artistinfo/cmd/model/old"
	"github.com/fonchain/fonchain-artistinfo/pb/old/artwork"

	"github.com/fonchain/fonchain-artistinfo/cmd/model"
	db "github.com/fonchain/fonchain-artistinfo/pkg/db"
	"github.com/fonchain/fonchain-artistinfo/pkg/m"
	"go.uber.org/zap"
)

func ArtworkAdd(res *artwork.ArtworkAddRequest) (req *artwork.ArtworkAddRespond, err error) {
	CreataAddByte, err := json.Marshal(res.CreateAddress)
	if err != nil {
		zap.L().Error("marshal createAddress failed", zap.Error(err))
		err = errors.New(m.ERROR_MARSHAL)
		return
	}
	artwork := &old.Artwork{
		ArtistId:      res.ArtistId,
		Name:          res.Name,
		ModelYear:     res.ModelYear,
		Photo:         res.Photo,
		ArtistPhoto:   res.ArtistPhoto,
		CreateAddress: string(CreataAddByte),
		Width:         int32(res.Width),
		AgeOfCreation: res.AgeOfCreation,
		Height:        int32(res.Height),
		Ruler:         int32(res.Ruler),
		Introduct:     res.Introduct,
		NetworkTrace:  res.NetworkTrace,
		Url:           res.Url,
		State:         int32(res.State),
	}

	if err = db.DB.Create(&artwork).Error; err != nil {
		zap.L().Error("create artwork info err", zap.Error(err))
		err = errors.New(m.CREATE_ERROR)
		return
	}

	return
}

func UpdateArtwork(data *artwork.UpdateArtworkRequest) (err error) {
	var artwork old.Artwork
	artwork.ID = int32(data.ID)
	if err = db.DB.First(&artwork).Error; err != nil {
		zap.L().Error("get artwork info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return
	}
	userId, err := GetUserId(data.ArtistId)
	if err != nil {
		zap.L().Error("get artwork info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return
	}
	CreataAddByte, _ := json.Marshal(data.CreateAddress)
	artwork.ID = int32(data.ID)
	artwork.ArtistId = uint64(userId)
	artwork.Name = data.Name
	artwork.ModelYear = data.ModelYear
	artwork.Photo = data.Photo
	artwork.ArtistPhoto = data.ArtistPhoto
	artwork.Width = int32(data.Width)
	artwork.AgeOfCreation = data.AgeOfCreation
	artwork.CreateAddress = string(CreataAddByte)
	artwork.Height = int32(data.Height)
	artwork.Ruler = int32(data.Ruler)
	artwork.Introduct = data.Introduct
	artwork.NetworkTrace = data.NetworkTrace
	artwork.Url = data.Url
	artwork.State = 1

	if err = db.DB.Save(&artwork).Error; err != nil {
		zap.L().Error("save artwork info err", zap.Error(err))
		err = errors.New(m.SAVE_ERROR)
		return
	}

	return
}

func DelArtwork(id int32) (err error) {
	if err = db.DB.Where("id = ?", id).Delete(&old.Artwork{}).Error; err != nil {
		zap.L().Error("delete artwork info err", zap.Error(err))
		err = errors.New(m.ERROR_DELETE)
		return
	}

	return
}
func ApproveArtwork(req *artwork.ApproveArtworkRequest) (rep *artwork.ApproveArtworkRespond, err error) {

	var artwork old.Artwork
	artwork.ID = req.ArtworkId
	var state int32
	if req.IsApprove {
		state = 5
	} else {
		state = 4
	}
	if err = db.DB.Model(&artwork).Updates(old.Artwork{State: state, Remark: req.Remark, Remark2: req.Remark2, ArtworkId: req.MgmtArtworkId}).Where("id", req.ArtworkId).Error; err != nil {
		zap.L().Error("get artwork info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return
	}
	return
}
func GetArtworkList(req *artwork.GetArtworkListRequest) (rep *artwork.GetArtworkListRespond, err error) {
	rep = &artwork.GetArtworkListRespond{}
	var datas []*artwork.UpdateArtworkRequest
	fmt.Println("111")
	var artworkList []old.Artwork
	//找到用户  p[]
	if err = db.DB.Order("created_at desc").Where("artist_id = ?", req.ID).Find(&artworkList).Error; err != nil {
		fmt.Println("222")
		zap.L().Error("get artwork info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return
	}
	fmt.Println("333")
	for k, v := range artworkList {
		artworkList[k].CreateTime = v.CreatedAt.Format("2006-01-02")
		var data artwork.UpdateArtworkRequest
		var createAddressByte []string
		json.Unmarshal([]byte(artworkList[k].CreateAddress), &createAddressByte)
		data.ID = uint64(artworkList[k].ID)
		// data.ArtistId = uint64(artworkList[k].ArtistId)
		data.Name = artworkList[k].Name
		data.ModelYear = artworkList[k].ModelYear
		data.Photo = artworkList[k].Photo
		data.ArtistPhoto = artworkList[k].ArtistPhoto
		data.Width = uint64(artworkList[k].Width)
		data.CreateAddress = createAddressByte
		data.Height = uint64(artworkList[k].Height)
		data.Ruler = uint64(artworkList[k].Ruler)
		data.Introduct = artworkList[k].Introduct
		data.AgeOfCreation = artworkList[k].AgeOfCreation
		data.CreateAt = artworkList[k].CreateTime
		data.NetworkTrace = artworkList[k].NetworkTrace
		data.Url = artworkList[k].Url
		data.State = uint64(artworkList[k].State)
		datas = append(datas, &data)
	}
	rep.Data = datas
	return
}

func GetArtwork(id int32) (rep *artwork.GetArtworkRespond, err error) {
	rep = &artwork.GetArtworkRespond{}

	var artworkRes old.Artwork
	if err = db.DB.Where("id = ?", id).First(&artworkRes).Error; err != nil {
		zap.L().Error("get artwork info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return
	}

	artworkRes.CreateTime = artworkRes.CreatedAt.Format("2006-01-02")
	//var createAddressByte []string
	//json.Unmarshal([]byte(artworkRes.CreateAddress), &createAddressByte)
	rep.ID = uint64(artworkRes.ID)
	// rep.ArtistId = uint64(artworkRes.ArtistId)
	rep.Name = artworkRes.Name
	rep.ModelYear = artworkRes.ModelYear
	rep.Photo = artworkRes.Photo
	rep.ArtistPhoto = artworkRes.ArtistPhoto
	rep.Width = uint64(artworkRes.Width)
	if artworkRes.CreateAddress == "" {
		artworkRes.CreateAddress = "[]"
	}
	rep.CreateAddress = artworkRes.CreateAddress
	rep.Height = uint64(artworkRes.Height)
	rep.Ruler = uint64(artworkRes.Ruler)
	rep.Introduct = artworkRes.Introduct
	rep.AgeOfCreation = artworkRes.AgeOfCreation
	rep.CreateAt = artworkRes.CreateTime
	rep.NetworkTrace = artworkRes.NetworkTrace
	rep.Url = artworkRes.Url
	rep.State = uint64(artworkRes.State)
	return rep, nil
}

func UploadArtwork(Id uint64) (err error) {
	var artwork old.Artwork
	if err = db.DB.Find(&artwork, "id = ?", Id).Error; err != nil {
		zap.L().Error("get artwork info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return
	}
	artwork.State = 1

	if err = db.DB.Save(&artwork).Error; err != nil {
		zap.L().Error("save artwork info err", zap.Error(err))
		err = errors.New(m.SAVE_ERROR)
		return
	}
	return
}

func GetMgmtArtworkList(req *artwork.GetMgmtArtworkListRequest) (rep *artwork.GetMgmtArtworkListRespond, err error) {
	var datas []*artwork.UpdateArtworkRequest
	//id, err := GetUserId(req.ArtistId)
	//if err != nil {
	//	zap.L().Error("get artwork info err", zap.Error(err))
	//	err = errors.New(m.ERROR_SELECT)
	//	return
	//}
	var args []interface{}
	var sqlWhere = " (state >=1 and state <=3) "
	if req.Name != "" {
		sqlWhere += ` and name like ? `
		args = append(args, "%"+req.Name+"%")
	}
	// if req.BatchId != 0 {
	// 	sqlWhere += `and c.batch_id = ? `
	// 	args = append(args, req.BatchId)
	// }
	if req.ArtistId != 0 {
		sqlWhere += `  artist_id = ? `
		args = append(args, req.ArtistId)
	}
	if req.State != 0 {
		sqlWhere += ` and state = ? `
		args = append(args, req.State)
	}
	//找到用户
	var artworkCount int64

	if db.DB.Where(sqlWhere, args...).Count(&artworkCount).Error != nil {
		zap.L().Error("get artwork info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return
	}
	rep.Count = uint64(artworkCount)
	var artworkList []old.Artwork
	//找到用户
	sqlWhere = sqlWhere + " limit ?,? "
	args = append(args, (req.Page-1)*req.PageSize)
	args = append(args, req.PageSize)
	if err = db.DB.Order("created_at desc").Where(sqlWhere, args...).Find(&artworkList).Error; err != nil {
		zap.L().Error("get artwork info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return
	}
	for k, v := range artworkList {
		artworkList[k].CreateTime = v.CreatedAt.Format("2006-01-02")
		var data artwork.UpdateArtworkRequest
		var createAddressByte []string
		json.Unmarshal([]byte(artworkList[k].CreateAddress), &createAddressByte)
		data.Name = artworkList[k].Name
		data.ModelYear = artworkList[k].ModelYear
		data.Photo = artworkList[k].Photo
		data.ArtistPhoto = artworkList[k].ArtistPhoto
		data.CreateAt = artworkList[k].CreateTime
		data.NetworkTrace = artworkList[k].NetworkTrace
		data.Url = artworkList[k].Url
		data.State = uint64(artworkList[k].State)
		datas = append(datas, &data)
	}
	rep.Data = datas
	return
}

func GetUserId(artistId string) (int64, error) {
	var user model.User
	if err := db.DB.First(&user, "id = ?", artistId).Error; err != nil {

		err = errors.New(m.ERROR_SELECT)
		return 0, err
	}
	return user.ID, nil

}
