package serializer

import (
	"github.com/fonchain_enterprise/fonchain-approval/api/approval"
	"github.com/fonchain_enterprise/fonchain-approval/pkg/e"
	"github.com/fonchain_enterprise/fonchain-approval/pkg/model"
)

//BuildApproval 处理单个detail返回
func BuildApproval(entity *model.Approval, userId uint64) *approval.CreateRequest {
	var work *approval.Work
	var show *approval.Show
	var exhibition *approval.Exhibition
	var bundle *approval.Bundle
	var workFlows []*approval.WorkFlow
	var financialFrom *approval.FinancialFrom
	canViewed := false
	canApproval := false
	allStatus := uint64(entity.Status)

	copyUsers := model.FormatToResponse(entity.CopyUsers)

	if allStatus != model.StatusDoing {
		for _, cu := range copyUsers {
			if userId != 0 && cu.ID == userId {
				allStatus = model.StatusNeedViewed
				if cu.IsViewed == true {
					canViewed = true
					allStatus = model.StatusViewed
				}
			}
		}
	}

	for _, tt := range entity.ApprovalWorkFlows {
		temp := &approval.WorkFlow{
			ID:     tt.ID,
			UserID: tt.UserId,
			Name:   tt.Name,
			Level:  uint64(tt.Level),
			Status: uint64(tt.Status),
			Reply:  tt.Reply,
		}

		if tt.OperatedAt != nil {
			temp.OperatedAt = tt.OperatedAt.Format("2006-01-02 15:04:05")
		}

		workFlows = append(workFlows, temp)

	}

	if entity.Status == model.StatusDoing && entity.NowUserId == userId {
		canApproval = true
	}

	response := &approval.CreateRequest{
		ID:            entity.ID,
		Domain:        *entity.Domain,
		Status:        uint64(entity.Status),
		Type:          entity.Type,
		CopyUsers:     copyUsers,
		SubmitterID:   entity.SubmitterID,
		SubmitterName: entity.SubmitterName,
		Content:       entity.Content,
		CanView:       canViewed,
		IsCustom:      e.Is_IsCustom_Yes,
		CanApproval:   canApproval,
		WorkFlows:     workFlows,
		Reply:         entity.Reply,
		Work:          work,
		Show:          show,
		Exhibition:    exhibition,
		Bundle:        bundle,
		FinancialFrom: financialFrom,
		CustomizeInfo: BuildKeyInfo(entity.ValueJson),
		CreatedAt:     entity.CreatedAt.Format("2006-01-02 15:04:05"),
		AllStatus:     allStatus, //0-未处理 1-通过 2-拒绝 3-已阅读 4-待阅读
		NowUserId:     entity.NowUserId,
		NowUserName:   entity.NowUserName,
		Level:         uint64(entity.Level),
		NowLevel:      uint64(entity.NowLevel),
	}

	if model.IsSystemType(entity.Type) == true {
		response.IsCustom = e.Is_IsCustom_No
	}

	if entity.ApprovalType != nil {
		response.TypeName = entity.ApprovalType.Title
		if entity.ApprovalType.ApprovalTypeGroup != nil {
			response.GroupName = entity.ApprovalType.ApprovalTypeGroup.Title
		}
	}

	_ = entity.SetResContent(response)
	//fmt.Println("check:", response.BundlePayPrice)

	return response
}

//BuildApprovals 处理单个detail返回
func BuildApprovals(list []*model.Approval, userId uint64) (details []*approval.CreateRequest) {

	for _, item := range list {
		temp := BuildApproval(item, userId)
		details = append(details, temp)
	}

	return details
}