package pposRequest

import (
	"PPOSUtils/utils"
	"errors"
	"net/url"
)

//NewAcCompanyListRequest 获取公司列表
func (that *PPOSClient) NewAcCompanyListRequest() *AcCompanyListRequest {
	return &AcCompanyListRequest{
		Request: Request{
			Client:            that,
			publicParamsSlice: []string{},
		},
	}
}

//AcCompanyListRequest ...
type AcCompanyListRequest struct {
	Request
	CompanyIDSlice []int64
}

func (that *AcCompanyListRequest) List() *AcCompanyListRequest {
	that.apiAddress = "/base/company/list"
	return that
}

func (that *AcCompanyListRequest) GetListByCompanyIds() *AcCompanyListRequest {
	that.apiAddress = "/base/company/getListByCompanyIds"
	return that
}

func (that *AcCompanyListRequest) SetKeyWord(keyWord string) *AcCompanyListRequest {
	that.initParams()
	that.params.Set("keyword", utils.ToString(keyWord))
	return that
}

func (that *AcCompanyListRequest) SetPage(page int64) *AcCompanyListRequest {
	that.initParams()
	that.params.Set("page", utils.ToString(page))
	return that
}

func (that *AcCompanyListRequest) SetSize(size int64) *AcCompanyListRequest {
	that.initParams()
	that.params.Set("size", utils.ToString(size))
	return that
}

func (that *AcCompanyListRequest) SetCompanyIds(companyID []int64) *AcCompanyListRequest {
	if len(that.CompanyIDSlice) < 1 {
		that.CompanyIDSlice = companyID
	}
	return that
}

//Params ...
func (that *AcCompanyListRequest) Params() (url.Values, error) {
	that.initParams()
	_params := that.params
	if that.CompanyIDSlice != nil {
		_params.Set("company_ids", utils.NewSliceInt64(that.CompanyIDSlice...).Join(","))
	}

	//
	if that.publicParamsSlice != nil {
		for _, _v := range that.publicParamsSlice {
			if _params.Get(_v) == "" {
				return nil, errors.New(that.apiAddress + "缺少参数:" + _v)
			}
		}
	}
	return _params, nil

}

//Do ...
func (that *AcCompanyListRequest) Do() ([]*AcCompanyListResponse, error) {
	//返回data
	_data, _err := that.Client.GetData(that.apiAddress, that)
	if _err != nil {
		return nil, _err
	}
	var _list interface{}
	if that.CompanyIDSlice == nil {
		//data为 分页结构
		_listData, _err := that.ParseList(_data)
		if _err != nil {
			return nil, _err
		}
		_list = _listData.List
	} else {
		//非分页
		_list = _data
	}
	//返回结果
	_rs := []*AcCompanyListResponse{}
	_sliceData, _ok := _list.([]interface{})
	if !_ok {
		return nil, errors.New(that.apiAddress + "请求响应格式不正确")
	}
	for _, _v := range _sliceData {
		_vData, _ok := _v.(map[string]interface{})
		if !_ok {
			return nil, errors.New(that.apiAddress + "请求响应格式不正确2")
		}
		_tmp := new(AcCompanyListResponse)
		if _err := that.ParseResponeMp(_tmp, _vData); _err != nil {
			return nil, errors.New(that.apiAddress + "请求响应格式化异常:" + _err.Error())
		}
		_rs = append(_rs, _tmp)
	}
	return _rs, nil
}
