package talent_service

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"reflect"
	"youngmini_server/app/dao"
	"youngmini_server/app/model"
	"youngmini_server/app/model/talent_model"
	"youngmini_server/app/utils"
)

type platformId int

const (
	PlatformIdLittleRedBook platformId = iota + 1
	PlatformIdTiktok
	PlatformIdWeibo
	PlatformIdKuaishou
	PlatformIdBilibili
	PlatformIdDianping
	PlatformIdZhihu
)

var PlatformDataMap = map[platformId]interface{} {
	PlatformIdLittleRedBook: talent_model.PlatformLittleRedBook{},
	PlatformIdTiktok: talent_model.PlatformTiktok{},
	PlatformIdWeibo: talent_model.PlatformWeibo{},
	PlatformIdKuaishou: talent_model.PlatformKuaishou{},
	PlatformIdBilibili: talent_model.PlatformBilibili{},
	PlatformIdDianping: talent_model.PlatformDianping{},
	PlatformIdZhihu: talent_model.PlatformZhihu{},
}

// GetTalentAllPlatformBriefInfo 获取达人所有平台的简略信息
func GetTalentAllPlatformBriefInfo(r *ghttp.Request) *TalentHttpResult {
	tid, err := utils.SessionTalentInfo.GetTalentIdFromSession(r)
	if err != nil {
		return &TalentHttpResult{Code: -1, Msg: "Get talent info failed"}
	}

	res, err := g.DB().Model("r_talent_platform_table").All("tid", tid)
	if err != nil {
		return &TalentHttpResult{Code: -2, Msg: "query database error"}
	}

	if res == nil {
		return &TalentHttpResult{Code: -3, Msg: "未绑定任何平台"}
	}

	var platformBriefInfo talent_model.TalentPlatformBriefInfo
	err = g.DB().Model("talent_info").WithAll().Where("id", tid).Scan(&platformBriefInfo)
	if err != nil {
		return &TalentHttpResult{Code: -4, Msg: "query data failed"}
	}

	return &TalentHttpResult{Code: 0, Msg: "success", Data: platformBriefInfo}

}

// OnGetTalentPlatformDetail 获取达人社媒平台的详细信息
func OnGetTalentPlatformDetail(r *ghttp.Request) *TalentHttpResult {
	tid, err := utils.SessionTalentInfo.GetTalentIdFromSession(r)
	if err != nil {
		return &TalentHttpResult{Code: -1, Msg: "Get talent info failed"}
	}

	pid := r.GetQueryInt("pid", 0)
	if tid == 0 || pid == 0 {
		return &TalentHttpResult{Code: -2, Msg: "request param error"}
	}

	// 通过达人与平台关联表(平台账号审核表)查找达人已有平台
	rtpRec, err := g.DB().Model("r_talent_platform_table").One("tid=? and p_id=?", tid, pid)
	if err != nil {
		return &TalentHttpResult{Code: -3, Msg: "query database failed"}
	}

	// 达人还没有提交过此平台信息
	if rtpRec == nil {
		return &TalentHttpResult{Code: -4, Msg: "talent have no info of platform"}
	}

	// 根据平台id查找平台信息表名
	pRec, err := g.DB().Model(dao.InfoThirdPlatform.Table).Fields(dao.InfoThirdPlatform.Columns.PlatformTableName).
		One("platform_id", rtpRec[dao.RTalentPlatformTable.Columns.PId])
	if err != nil {
		return &TalentHttpResult{Code: -5, Msg: "query database failed"}
	}

	if pRec == nil {
		return &TalentHttpResult{Code: -6, Msg: "platform info not found"}
	}

	// 用得到的信息表名查找平台信息
	infoRec, err := g.DB().Model(pRec[dao.InfoThirdPlatform.Columns.PlatformTableName].String()).One("talent_id", tid)
	if err != nil {
		return &TalentHttpResult{Code: -7, Msg: "query talent platform info failed"}
	}

	if infoRec == nil {
		return &TalentHttpResult{Code: -8, Msg: "not found talent platform info"}
	}

	return &TalentHttpResult{Code: 0, Msg: "success", Data: infoRec}
}

func getPlatformById(pid int32) (interface{}, error) {
	switch pid {
	case 1:
		return &talent_model.PlatformLittleRedBook{}, nil
	case 2:
		return &talent_model.PlatformTiktok{}, nil
	case 3:
		return &talent_model.PlatformWeibo{}, nil
	case 4:
		return &talent_model.PlatformKuaishou{}, nil
	case 5:
		return &talent_model.PlatformBilibili{}, nil
	case 6:
		return &talent_model.PlatformDianping{}, nil
	case 7:
		return &talent_model.PlatformZhihu{}, nil
	}

	return nil, errors.New("id error")
}

// 将三个擅长领域转换为json
func combineSkillsOnToJson(skillsOn1 int32, skillsOn2 int32, skillsOn3 int32) string {
	r := []int32{skillsOn1, skillsOn2, skillsOn3}

	bytes, err := json.Marshal(r)
	if err != nil {
		return "[]"
	}

	return string(bytes)
}

// OnPostPlatformDetailInfo 上传平台信息
func OnPostPlatformDetailInfo(r *ghttp.Request) *TalentHttpResult {
	tid, err := utils.SessionTalentInfo.GetTalentIdFromSession(r)
	if err != nil {
		return &TalentHttpResult{Code: -1, Msg: "Get talent info failed"}
	}

	pid := r.GetRequestInt32("platformId", 0)
	if tid == 0 || pid == 0 {
		return &TalentHttpResult{Code: -2, Msg: "param tid and pid must be provided"}
	}

	platformData, err := getPlatformById(pid)
	if err = r.ParseForm(platformData); err != nil {
		return &TalentHttpResult{Code: -2, Msg: err.Error()}
	}

	// 根据平台id获取平台信息
	platformInfoRec, err := g.DB().Model(dao.InfoThirdPlatform.Table).
		Fields(dao.InfoThirdPlatform.Columns.PlatformTableName, dao.InfoThirdPlatform.Columns.PlatformIcon).One("platform_id", pid)
	if err != nil {
		return &TalentHttpResult{Code: -4, Msg: "get platform table name failed"}
	}

	//_, exist1 := reflect.TypeOf(platformData).Elem().FieldByName("SkilledAt1")
	//_, exist2 := reflect.TypeOf(platformData).Elem().FieldByName("SkilledAt2")
	//_, exist3 := reflect.TypeOf(platformData).Elem().FieldByName("SkilledAt3")
	//_, exist := reflect.TypeOf(platformData).Elem().FieldByName("SkilledAt")
	//
	//if exist1 && exist2 && exist3 &&exist {
	//	// 如果上传的信息中包括SkilledAt1 SkilledAt2 SkilledAt3字段，则将三个字段转换为json，并存入SkilledAt字段
	//	skilledAt1 := reflect.ValueOf(platformData).Elem().FieldByName("SkilledAt1").Int()
	//	skilledAt2 := reflect.ValueOf(platformData).Elem().FieldByName("SkilledAt2").Int()
	//	skilledAt3 := reflect.ValueOf(platformData).Elem().FieldByName("SkilledAt3").Int()
	//
	//	reflect.ValueOf(platformData).Elem().FieldByName("SkilledAt").SetString(
	//		combineSkillsOnToJson(int32(skilledAt1), int32(skilledAt2), int32(skilledAt3)))
	//}

	reflect.ValueOf(platformData).Elem().FieldByName("SkilledAt").SetString("[]")

	// 将达人id存入结构体
	reflect.ValueOf(platformData).Elem().FieldByName("TalentId").SetInt(int64(tid))
	// 平台名称写入结构体
	reflect.ValueOf(platformData).Elem().FieldByName("PlatformName").SetString(platformInfoRec[dao.InfoThirdPlatform.Columns.PlatformName].String())
	// 平台图标url写入结构体
	reflect.ValueOf(platformData).Elem().FieldByName("PlatformIconUrl").SetString(platformInfoRec[dao.InfoThirdPlatform.Columns.PlatformIcon].String())

	err = g.DB().Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
		// 将平台账号信息存入对应的平台表
		_, err1 := tx.Ctx(ctx).Model(platformInfoRec["platform_table_name"].String()).Save(platformData)
		if err1 != nil {
			return err1
		}

		// 将账号审核信息写入r_talent_platform_table表, 无论是新建还是更新都把状态回复为原始状态
		_, err1 = tx.Ctx(ctx).Model(dao.RTalentPlatformTable.Table).
			Save(model.RTalentPlatformTable{
				Tid:            tid,
				PId:            int(pid),
				PName:          platformInfoRec[dao.InfoThirdPlatform.Columns.PlatformName].String(),
				PNickname:      reflect.ValueOf(platformData).Elem().FieldByName("PlatformNickname").String(),
				PAccountId:     reflect.ValueOf(platformData).Elem().FieldByName("PlatformAccountId").String(),
				FansCount:      reflect.ValueOf(platformData).Elem().FieldByName("FansCount").Int(),
				HomePageUrl:    reflect.ValueOf(platformData).Elem().FieldByName("HomePageUrl").String(),
				ExamineState:   1,
				FailReason:     "",
				ExamineAdminId: 0,
				CreateDate:     gtime.Now(),
				ExamineDate:    nil,
				DisableDate:    nil,
				Deleted: 0,
			})

		return err1
	})

	if err != nil {
		return &TalentHttpResult{Code: -5, Msg: "save platformData failed"}
	}

	return &TalentHttpResult{Code: 0, Msg: "success"}
}
