package svc

import (
	"context"
	"git.i2edu.net/i2/i2-bill-erp/transform"
	"time"
)

func (svc *ServiceContext) GetErpOrganSchool() ([]*transform.OrganSchool, error) {
	var schools []*transform.OrganSchool
	if err := svc.RdCli.GetCache(cacheErpSchool, schools); err != nil {
		res, err := svc.Transformer.GetErpSchool(context.Background(), &transform.Empty{})
		if err != nil {
			return nil, err
		}
		err = svc.RdCli.SetWithExpire(cacheErpSchool, res.School, time.Hour)
		if err != nil {
			return nil, err
		}
		return res.School, nil
	}
	return schools, nil
}

func (svc *ServiceContext) GetErpOrganSchoolTree() ([]*transform.TreeNode, error) {
	var nodes []*transform.TreeNode
	if err := svc.RdCli.GetCache(cacheErpSchoolTree, nodes); err != nil {
		res, err := svc.Transformer.GetErpOrganSchTree(context.Background(), &transform.Empty{})
		if err != nil {
			return nil, err
		}
		err = svc.RdCli.SetWithExpire(cacheErpSchoolTree, res.Nodes, time.Hour)
		if err != nil {
			return nil, err
		}
		return res.Nodes, nil
	}
	return nodes, nil
}

func (svc *ServiceContext) GetErpNetworkDetailTree() ([]*transform.TreeNode, error) {
	var nodes []*transform.TreeNode
	if err := svc.RdCli.GetCache(cacheErpNetworkDetailTree, nodes); err != nil {
		res, err := svc.Transformer.GetErpMktNetWorkDetailTree(context.Background(), &transform.Empty{})
		if err != nil {
			return nil, err
		}
		err = svc.RdCli.SetWithExpire(cacheErpNetworkDetailTree, res.Nodes, time.Hour)
		if err != nil {
			return nil, err
		}
		return res.Nodes, nil
	}
	return nodes, nil
}

func (svc *ServiceContext) GetErpActivity() ([]*transform.Active, error) {
	var actives []*transform.Active
	if err := svc.RdCli.GetCache(cacheErpActivity, actives); err != nil {
		res, err := svc.Transformer.GetErpActive(context.Background(), &transform.GetErpActiveReq{})
		if err != nil {
			return nil, err
		}
		err = svc.RdCli.SetWithExpire(cacheErpSchool, res.Active, time.Hour)
		if err != nil {
			return nil, err
		}
		return res.Active, nil
	}
	return actives, nil
}

func (svc *ServiceContext) GetErpCity() ([]*transform.TreeNode, error) {
	var nodes []*transform.TreeNode
	if err := svc.RdCli.GetCache(cacheErpCityTree, nodes); err != nil {
		res, err := svc.Transformer.GetErpCityTree(context.Background(), &transform.Empty{})
		if err != nil {
			return nil, err
		}
		err = svc.RdCli.SetWithExpire(cacheErpCityTree, res.Nodes, time.Hour)
		if err != nil {
			return nil, err
		}
		return res.Nodes, nil
	}
	return nodes, nil
}
