package svc

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

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

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

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

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

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