package lakala

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/globals"
	"net/http"
	"time"
)

// CreateOrder 创建交易订单
func (a *API) CreateOrder(param *CreateOrderReq) (*CreateOrderResp, error) {
	reqParameter := map[string]interface{}{
		"req_data": utils.Struct2Map(param, "", false),
		"version":  Version2,
		"req_time": utils.Time2TimeStrByFormat(time.Now(), TimeFormat),
	}
	result, err := a.AccessAPISign(OrderProdUrl, CrateOrderActive, http.MethodPost, "", reqParameter)
	if err != nil {
		return nil, err
	}
	globals.SugarLogger.Debugf("--------CreateOrder := %s", utils.Format4Output(result, false))
	if result["code"].(string) != Success {
		return nil, fmt.Errorf(result["msg"].(string))
	}

	bodyResult, err := json.Marshal(result["resp_data"])
	if err != nil {
		return nil, err
	}

	resp := &CreateOrderResp{}
	if err = json.Unmarshal(bodyResult, resp); err != nil {
		return nil, err
	}

	return resp, nil
}

// CloseOrder 订单关单(超时支付订单,主动关闭)
func (a *API) CloseOrder(param *CloseOrderReq) (string, error) {
	if param.OutOrderNo == "" && param.PayOrderNo == "" {
		return "", fmt.Errorf("out_order_no,pay_order_no 不能同时为空")
	}

	reqParameter := map[string]interface{}{
		"req_data": utils.Struct2Map(param, "", false),
		"version":  Version2,
		"req_time": utils.Time2TimeStrByFormat(time.Now(), TimeFormat),
	}
	result, err := a.AccessAPISign(OrderProdUrl, CloseOrderActive, http.MethodPost, "", reqParameter)
	if err != nil {
		return "", err
	}

	if result["code"].(string) != Success {
		return "", fmt.Errorf(result["msg"].(string))
	}

	return result["resp_data"].(map[string]string)["order_status"], err
}

// QueryOrder 收银订单查询
func (a *API) QueryOrder(outOrderNo string, merchantNo string) (*QueryOrderResp, error) {
	reqParameter := map[string]interface{}{
		"req_data": map[string]string{"out_order_no": outOrderNo, "merchant_no": merchantNo},
		"version":  Version2,
		"req_time": utils.Time2TimeStrByFormat(time.Now(), TimeFormat),
	}
	result, err := a.AccessAPISign(OrderProdUrl, QueryOrderActive, http.MethodPost, "", reqParameter)
	if err != nil {
		return nil, err
	}

	if result["code"].(string) != Success {
		return nil, fmt.Errorf(result["msg"].(string))
	}

	bodyResult, err := json.Marshal(result["resp_data"])
	if err != nil {
		return nil, err
	}

	resp := &QueryOrderResp{}
	if err = json.Unmarshal(bodyResult, resp); err != nil {
		return nil, err
	}

	return resp, nil
}

// RefundOrder 订单统一退货
func (a *API) RefundOrder(param *RefundOrderReq) (*RefundOrderResp, error) {
	reqParameter := map[string]interface{}{
		"req_data": utils.Struct2Map(param, "", false),
		"version":  Version2,
		"req_time": utils.Time2TimeStrByFormat(time.Now(), TimeFormat),
	}
	result, err := a.AccessAPISign(OrderProdUrl, OrderRefundActive, http.MethodPost, "", reqParameter)
	if err != nil {
		return nil, err
	}

	if result["code"].(string) != Success {
		return nil, fmt.Errorf(result["msg"].(string))
	}

	bodyResult, err := json.Marshal(result["resp_data"])
	if err != nil {
		return nil, err
	}

	resp := &RefundOrderResp{}
	if err = json.Unmarshal(bodyResult, resp); err != nil {
		return nil, err
	}

	return resp, nil
}

// RefundOrderQuery 订单同一退货查询
func (a *API) RefundOrderQuery(param *RefundOrderQueryReq) ([]*RefundOrderQueryResp, error) {
	if param.OriginOutTradeNo == "" && param.OriginTradeRefNo == "" {
		return nil, fmt.Errorf("退款流水号/系统参考号必传一个")
	}
	reqParameter := map[string]interface{}{
		"req_data": utils.Struct2Map(param, "", false),
		"version":  Version2,
		"req_time": utils.Time2TimeStrByFormat(time.Now(), TimeFormat),
	}
	result, err := a.AccessAPISign(OrderProdUrl, OrderRefundQueryActive, http.MethodPost, "", reqParameter)
	if err != nil {
		return nil, err
	}

	if result["code"].(string) != Success {
		return nil, fmt.Errorf(result["msg"].(string))
	}

	bodyResult, err := json.Marshal(result["resp_data"].(map[string]interface{})["refund_list"])
	if err != nil {
		return nil, err
	}

	resp := make([]*RefundOrderQueryResp, 0, 0)
	if err = json.Unmarshal(bodyResult, &resp); err != nil {
		return nil, err
	}

	return resp, nil
}

// ApplyElectronicContract 电子合同签约
func (a *API) ApplyElectronicContract(param *ApplyContractParam) (*ApplyContract, error) {
	reqParameter := map[string]interface{}{
		"req_data": utils.Struct2Map(param, "", false),
		"version":  Version3,
		"req_time": utils.Time2TimeStrByFormat(time.Now(), TimeFormat),
	}
	result, err := a.AccessAPISign(OrderProdUrl, OrderEcApplyActive, http.MethodPost, "", reqParameter)
	if err != nil {
		return nil, err
	}

	bodyResult, err := json.Marshal(result)
	if err != nil {
		return nil, err
	}

	resp := &ApplyContract{}
	if err = json.Unmarshal(bodyResult, resp); err != nil {
		return nil, err
	}

	return resp, nil
}

// ApplyElectronicContractByPeople 申请人工审核
func (a *API) ApplyElectronicContractByPeople(param *ApplyContractByPeople) error {
	reqParameter := map[string]interface{}{
		"req_data":  utils.Struct2Map(param, "", false),
		"ver":       Version,
		"timestamp": utils.Time2TimeStrByFormat(time.Now(), TimeFormat),
		"req_id":    utils.GetUUID(),
	}
	result, err := a.AccessAPISign(OrderProdUrl, OrderEcApplyByPeopleActive, http.MethodPost, "", reqParameter)
	if err != nil {
		return err
	}

	if result["code"].(string) != Success {
		return fmt.Errorf("%s", result["msg"].(string))
	}

	return err
}

// QueryElectronicContract 人工复合结果查询
func (a *API) QueryElectronicContract(orderNo string, orgId int, ecApplyId string) (*ElectronicContractStatus, error) {
	reqParameter := map[string]interface{}{
		"req_data": map[string]interface{}{
			//"version":     "1.0",
			"order_no":    orderNo,
			"org_id":      orgId,
			"ec_apply_id": ecApplyId,
		},
		"version":  Version2,
		"req_time": utils.Time2TimeStrByFormat(time.Now(), TimeFormat),
		"req_id":   utils.GetUUID(),
	}
	result, err := a.AccessAPISign(OrderProdUrl, OrderEcApplyStatusActive, http.MethodPost, "", reqParameter)
	if err != nil {
		return nil, err
	}

	if result["code"].(string) != Success {
		return nil, fmt.Errorf(result["msg"].(string))
	}

	bodyResult, err := json.Marshal(result["resp_data"].(map[string]interface{}))
	if err != nil {
		return nil, err
	}

	resp := &ElectronicContractStatus{}
	if err = json.Unmarshal(bodyResult, resp); err != nil {
		return nil, err
	}

	return resp, nil
}

type ElectronicContractStatus struct {
	Version        string `json:"version"`
	OrderNo        string `json:"order_no"`
	OrgId          int    `json:"org_id"`
	EcApplyId      int64  `json:"ec_apply_id"`        // ec_apply_id
	AuditStatus    string `json:"audit_status"`       // 人工审核状态
	AuditDesc      string `json:"audit_desc"`         // 人工审核结果说明
	SignH5Url      string `json:"sign_h5_url"`        // 签约H5地址
	SignH5UrlExpTm string `json:"sign_h5_url_exp_tm"` // 签约H5地址过期时间
}

// QueryElectronic 电子合同查询
func (a *API) QueryElectronic(orderNo string, orgId int, ecApplyId string) (*QueryElectronicResp, error) {
	reqParameter := map[string]interface{}{
		"req_data": map[string]interface{}{
			"order_no":    orderNo,
			"org_code":    orgId,
			"ec_apply_id": ecApplyId,
		},
		"version":  Version,
		"req_time": utils.Time2TimeStrByFormat(time.Now(), TimeFormat),
		"req_id":   utils.GetUUID(),
	}
	result, err := a.AccessAPISign(OrderProdUrl, OrderEcQuery, http.MethodPost, "", reqParameter)
	if err != nil {
		return nil, err
	}

	if result["code"].(string) != Success {
		return nil, fmt.Errorf(result["msg"].(string))
	}

	bodyResult, err := json.Marshal(result["resp_data"].(map[string]interface{}))
	if err != nil {
		return nil, err
	}

	resp := &QueryElectronicResp{}
	if err = json.Unmarshal(bodyResult, resp); err != nil {
		return nil, err
	}

	return resp, nil
}

type QueryElectronicResp struct {
	OrderNo   string `json:"order_no"`    // 请求上送的订单号
	EcApplyId int64  `json:"ec_apply_id"` // 电子签约申请受理编号
	EcStatus  string `json:"ec_status"`   // 电子合同签署状态 UNDONE 未完成 COMPLETED 已完成
	EcNo      string `json:"ec_no"`       // 电子合同号
}
