package jdapi

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/utils"
)

// QueryInvoiceDetail 发票申请详情查询
// https://opendj.jd.com/staticnew/widgets/resources.html?groupid=182&apiid=38559b4a4fc34c8b8d3223d43c731d70
func (a *API) QueryInvoiceDetail(orderID string) (invoice *InvoiceDetailResult, err error) {
	jdParams := map[string]interface{}{
		"orderId": orderID,
	}
	result, err := a.AccessAPINoPage("JdInvoiceService/getInvoiceApplyDetail", jdParams, nil, nil, genNoPageResultParser("code", "msg", "result", "0"))
	if err != nil {
		return nil, err
	}
	if err = utils.Map2StructByJson(result, &invoice, false); err != nil {
		return nil, err
	}
	return invoice, err
}

// QueryInvoiceList 查询发票列表
// https://opendj.jd.com/staticnew/widgets/resources.html?groupid=182&apiid=55f36649c0d642d8aa0cd8949729a124
func (a *API) QueryInvoiceList(param *QueryInvoiceListParam) (invoice []*InvoiceListResult, err error) {
	jdParams := utils.Struct2MapByJson(param)
	result, err := a.AccessAPINoPage("JdInvoiceService/pageInvoiceApply", jdParams, nil, nil, genNoPageResultParser("code", "msg", "result", "0"))
	if err != nil {
		return nil, err
	}
	if result.(map[string]interface{})["list"] != nil {
		data := make([]*InvoiceListResult, 0, 0)
		if err = json.Unmarshal(utils.MustMarshal(result.(map[string]interface{})["list"]), &data); err != nil {
			return nil, err
		}
		return data, nil
	}

	return nil, fmt.Errorf("未查询到发票数据")
}

// UploadBlueTicket 上传蓝票
// https://opendj.jd.com/staticnew/widgets/resources.html?groupid=182&apiid=1eb09fa07adf4243b14b2193fdf7154d
func (a *API) UploadBlueTicket(param *BlueTicketParam) (err error) {
	jdParams := utils.Struct2MapByJson(param)
	_, err = a.AccessAPINoPage("JdInvoiceService/applyInvoiceForOwn", jdParams, nil, nil, genNoPageResultParser("code", "msg", "", "0"))
	if err != nil {
		return err
	}
	return nil
}
