package lakala

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

// MerchantIncoming 商户进件接口
func (a *API) MerchantIncoming(incoming *MerchantIncomingReq) (string, string, error) {
	data := utils.Struct2Map(incoming, "", false)
	result, err := a.AccessAPI2(BaseProdUrl, IncomingAction, http.MethodPost, "", data)
	if err != nil {
		return "", "", err
	}

	return result["merchantNo"].(string), result["status"].(string), nil
}

// GetMerchantInfo 获取商户详细信息
func (a *API) GetMerchantInfo(customerNo string) (*MerchantObj, error) {
	parameters, _ := json.Marshal(map[string]string{"customerNo": customerNo})
	encryptParam, err := EncryptByPrivateKey(parameters, PrivateKeyBegin)
	if err != nil {
		return nil, err
	}
	result, err := a.AccessAPI2(BaseProdChangeUrl, GetMerchantInfo, http.MethodPost, "", map[string]interface{}{"data": encryptParam})
	if err != nil {
		return nil, err
	}

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

	decryptData := result["data"].(string)
	base64DecryData, _ := base64.StdEncoding.DecodeString(decryptData)
	resultData, err := DecryptByPublicKey(base64DecryData, PublicKeyBegin)
	if err != nil {
		return nil, err
	}

	merchant := &MerchantObj{}
	if err = json.Unmarshal(resultData, merchant); err != nil {
		return nil, err
	}

	return merchant, nil
}

// GetTerminalInfo 获取终端信息
func (a *API) GetTerminalInfo(posSn string) (*TerminalInfo, error) {
	parameters, _ := json.Marshal(map[string]string{"posSn": posSn})
	encryptParam, err := EncryptByPrivateKey(parameters, PrivateKeyBegin)
	if err != nil {
		return nil, err
	}
	result, err := a.AccessAPI2(BaseProdChangeUrl, GetTerminalInfo, http.MethodPost, "", map[string]interface{}{"data": encryptParam})
	if err != nil {
		return nil, err
	}

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

	decryptData := result["data"].(string)
	base64DecryData, _ := base64.StdEncoding.DecodeString(decryptData)
	resultData, err := DecryptByPublicKey(base64DecryData, PublicKeyBegin)
	if err != nil {
		return nil, err
	}

	merchant := &TerminalInfo{}
	if err = json.Unmarshal(resultData, merchant); err != nil {
		return nil, err
	}

	return merchant, nil
}

// GetOrganizationCode 获取城市组织代码 parentCode = 1 查所有,城市code看看和我们系统一致不
func (a *API) GetOrganizationCode(parentCode string) ([]*OrganizationList, error) {
	result, err := a.AccessAPI(BaseProdUrl, OrganizationAction, http.MethodGet, parentCode, nil)
	if err != nil {
		return nil, err
	}
	if result[ResultKey] != nil {
		byteBank, err := json.Marshal(result[ResultKey])
		if err != nil {
			return nil, err
		}
		bankList := make([]*OrganizationList, 0, 0)
		if err = json.Unmarshal(byteBank, &bankList); err != nil {
			return nil, err
		}
		return bankList, err
	}

	return nil, fmt.Errorf("接口[%s],未查询到数据", OrganizationAction)
}

// GetBankList 银行列表查询
func (a *API) GetBankList(areaCode, bankName string) ([]*BankListResult, error) {
	param := map[string]interface{}{
		"areaCode": areaCode,
	}
	if bankName != "" {
		param["bankName"] = bankName
	}
	result, err := a.AccessAPI(BaseProdUrl, BankList, http.MethodGet, "", param)
	if err != nil {
		return nil, err
	}

	if result[ResultKey] != nil {
		byteBank, err := json.Marshal(result[ResultKey])
		if err != nil {
			return nil, err
		}
		bankList := make([]*BankListResult, 0, 0)
		if err = json.Unmarshal(byteBank, &bankList); err != nil {
			return nil, err
		}
		return bankList, err
	}

	return nil, fmt.Errorf("接口[%s],未查询到数据", BankList)
}

// GetMerchantMcc 商户类别查询(获取小类)
func (a *API) GetMerchantMcc(businessScene string, parentCode string) (data []*BusinessResult, err error) {
	result := make([]*BusinessResult, 0, 0)
	retVal := map[string]interface{}{}

	if parentCode != "" { // 获取小类
		retVal, err = a.AccessAPI(BaseProdUrl, MerchantMcc, http.MethodGet, parentCode, nil)
		if err != nil {
			return nil, err
		}
	} else {
		retVal, err = a.AccessAPI(BaseProdUrl, MerchantMcc, http.MethodGet, "", map[string]interface{}{"businessScene": businessScene})
		if err != nil {
			return nil, err
		}
	}

	if retVal[ResultKey] != nil {
		byteBank, err := json.Marshal(retVal[ResultKey])
		if err != nil {
			return nil, err
		}
		if err = json.Unmarshal(byteBank, &result); err != nil {
			return nil, err
		}
		return result, err
	}

	return nil, err
}

// MerchantFeeQuery 商户变更-商户费率查询 customerNo内部商户编号
func (a *API) MerchantFeeQuery(customerNo string, productCode string) (*MerchantFeeResp, error) {
	if customerNo == "" {
		return nil, fmt.Errorf("customerNo 不能为空")
	}
	param := map[string]interface{}{}
	if productCode != "" {
		param["productCode"] = productCode
	}
	result, err := a.AccessAPI(BaseProdChangeUrl, UpdateFeeQuery, http.MethodGet, customerNo, param)
	if err != nil {
		return nil, err
	}

	data := &MerchantFeeResp{}
	if err = utils.Map2StructByJson(result, data, false); err != nil {
		return nil, err
	}
	return data, err
}

// MerchantFeeChange 商户费率信息变更
func (a *API) MerchantFeeChange(param *FeeChangeReq, customerNo string) (int64, string, error) {
	if customerNo == "" {
		return 0, "", fmt.Errorf("商户ID不能为空")
	}
	mapParam := utils.Struct2Map(param, "", false)

	result, err := a.AccessAPI2(BaseProdChangeUrl, UpdateFeeQuery, http.MethodPost, customerNo, mapParam)

	if err != nil {
		return 0, "", err
	}

	data := &CahngePublic{}
	if err = utils.Map2StructByJson(result, data, false); err != nil {
		return 0, "", err
	}

	return data.ReviewRelatedId, data.Message, nil
}

// UpdateSettleInfo 修改用户结算信息(当param为空时,是查询,不为空时是变更)
func (a *API) UpdateSettleInfo(customerNo string, param *UpdateSettleInfoReq) (*CahngePublic, *UpdateSettleInfoReq, error) {
	if customerNo == "" {
		return nil, nil, fmt.Errorf("商户ID不能为空")
	}
	var mapParam map[string]interface{}
	if param != nil {
		mapParam = utils.Struct2Map(param, "", false)
	}

	if param != nil { // 变更
		result, err := a.AccessAPI2(BaseProdChangeUrl, UpdateSettleChange, http.MethodPost, customerNo, mapParam)
		if err != nil {
			return nil, nil, err
		}

		data := &CahngePublic{}
		if err = utils.Map2StructByJson(result, data, false); err != nil {
			return nil, nil, err
		}
		return data, nil, err
	} else { // 查询
		result, err := a.AccessAPI2(BaseProdChangeUrl, UpdateSettleChange, http.MethodGet, customerNo, mapParam)
		if err != nil {
			return nil, nil, err
		}

		data := &UpdateSettleInfoReq{}
		if err = utils.Map2StructByJson(result, data, false); err != nil {
			return nil, nil, err
		}
		return nil, data, err
	}
}

// UpdateBaseInfo 商户基本信息变更
func (a *API) UpdateBaseInfo(customerNo string, changeBaseMap *UpdateBaseInfoReq) (*CahngePublic, error) {
	if customerNo == "" {
		return nil, fmt.Errorf("商户ID不能为空")
	}

	newMap := utils.Struct2Map(changeBaseMap, "'", false)
	base := utils.MergeMaps(newMap, map[string]interface{}{"customerNo": customerNo})

	result, err := a.AccessAPI2(BaseProdChangeUrl, UpdateBaseChange, http.MethodPost, "", base)
	if err != nil {
		return nil, err
	}
	data := &CahngePublic{}
	if err = utils.Map2StructByJson(result, data, false); err != nil {
		return nil, err
	}
	return data, err
}

// QueryMerchantReviewStatus 查询变更门店审核状态
func (a *API) QueryMerchantReviewStatus(reviewRelatedId string) (string, string, error) {
	result, err := a.AccessAPI(BaseProdQueryReviewStatus, QueryChangeReviewStatus, http.MethodGet, "", map[string]interface{}{"reviewRelatedId": reviewRelatedId})
	if err != nil {
		return "", "", err
	}
	reviewPass := ""
	reviewResult := ""
	if result["reviewPass"] != nil {
		reviewPass = result["reviewPass"].(string)
	}
	if result["reviewResult"] != nil {
		reviewResult = result["reviewResult"].(string)
	}

	return reviewPass, reviewResult, err
}

// CheckImgIsSupplement 查看是否补充照片
func (a *API) CheckImgIsSupplement(externalCustomerNo string) (*OpenCustomerExtImgVo, error) {
	result, err := a.AccessAPI(BaseProdChangeUrl, CheckImgIsSupplement, http.MethodGet, externalCustomerNo, nil)
	if err != nil {
		return nil, err
	}

	imgSupplementResp := &ImgSupplementResp{}
	if err = utils.Map2StructByJson(result, imgSupplementResp, false); err != nil {
		return nil, err
	}

	if imgSupplementResp.Code != Success {
		return nil, fmt.Errorf(imgSupplementResp.Message)
	}

	base64DecryData, _ := base64.StdEncoding.DecodeString(result["data"].(string))
	resultData, err := DecryptByPublicKey(base64DecryData, PublicKeyBegin)
	if err != nil {
		return nil, err
	}
	openCustomerExtImgVo := &OpenCustomerExtImgVo{}
	if err = json.Unmarshal(resultData, openCustomerExtImgVo); err != nil {
		return nil, err
	}

	return openCustomerExtImgVo, nil
}

// ImgSupplement 照片补充
func (a *API) ImgSupplement(param *ImgSupplementReq) error {
	result, err := a.AccessAPI(BaseProdChangeUrl, ImgIsSupplement, http.MethodPost, "", utils.Struct2Map(param, "", false))
	imgSupplementResp := &ImgSupplementResp{}
	if err = utils.Map2StructByJson(result, imgSupplementResp, false); err != nil {
		return err
	}
	if imgSupplementResp.Code != "200" {
		return fmt.Errorf(imgSupplementResp.Message)
	}

	return nil
}

// GetMerchantReportStatus 查看银联报备状态
func (a *API) GetMerchantReportStatus(orgCode, agentNo, externalCustomerNo string) (*OpenUnionpayMerchantVo, error) {
	param := map[string]interface{}{
		"orgCode":            orgCode,
		"agentNo":            agentNo,
		"externalCustomerNo": externalCustomerNo,
	}
	result, err := a.AccessAPI2(BaseProdChangeUrl, ReportStatus, http.MethodPost, "", param)
	if err != nil {
		return nil, err
	}
	imgSupplementResp := &ImgSupplementResp{}
	if err = utils.Map2StructByJson(result, imgSupplementResp, false); err != nil {
		return nil, err
	}

	if imgSupplementResp.Code != Success {
		return nil, fmt.Errorf(imgSupplementResp.Message)
	}

	base64DecryData, _ := base64.StdEncoding.DecodeString(imgSupplementResp.Data)
	resultData, err := DecryptByPublicKey(base64DecryData, PublicKeyBegin)
	if err != nil {
		return nil, err
	}

	openUnionpayMerchantVo := &OpenUnionpayMerchantVo{}
	if err = json.Unmarshal(resultData, openUnionpayMerchantVo); err != nil {
		return nil, err
	}

	return openUnionpayMerchantVo, err
}

// GetMerchantTerminal 获取终端报备信息
func (a *API) GetMerchantTerminal(orgCode, agentNo, externalCustomerNo, posSn string) (*OpenUnionpayTermVo, error) {
	param := map[string]interface{}{
		"orgCode":            orgCode,
		"agentNo":            agentNo,
		"externalCustomerNo": externalCustomerNo,
		"posSn":              posSn,
	}
	result, err := a.AccessAPI2(BaseProdChangeUrl, TerminalStatus, http.MethodPost, "", param)
	if err != nil {
		return nil, err
	}
	imgSupplementResp := &ImgSupplementResp{}
	if err = utils.Map2StructByJson(result, imgSupplementResp, false); err != nil {
		return nil, err
	}

	if imgSupplementResp.Code != "200" {
		return nil, fmt.Errorf(imgSupplementResp.Message)
	}

	openUnionpayTermVo := &OpenUnionpayTermVo{}
	if err = json.Unmarshal([]byte(imgSupplementResp.Data), openUnionpayTermVo); err != nil {
		return nil, err
	}

	return openUnionpayTermVo, err
}

// SupplementBusinessLicense 变更营业执照
func (a *API) SupplementBusinessLicense(param *BusinessLicenseReq) (string, string, error) {
	req := utils.Struct2Map(param, "", false)
	result, err := a.AccessAPI2(BaseProdChangeUrl, SupplementBusinessLicense, http.MethodPost, "", req)
	if err != nil {
		return "", "", err
	}

	data := &FeeChangeResp{}
	if err = utils.Map2StructByJson(result, data, false); err != nil {
		return "", "", err
	}
	if data.StatusCodeValue != utils.Str2Int(BaseSuccess) {
		return "", "", fmt.Errorf(data.StatusCode)
	}

	return utils.Int2Str(data.Body.ReviewRelatedId), data.Body.Message, err
}

// UnionPayMerInfo 银联商户信息共享联防机制查询
func (a *API) UnionPayMerInfo(larName, larIdcard string) (*DishonestPerson, error) {
	result, err := a.AccessAPI(BaseProdChangeUrl, UnionPayMerInfo, http.MethodPost, "", map[string]interface{}{
		"larName":   larName,
		"larIdcard": larIdcard,
	})
	if err != nil {
		return nil, err
	}

	person := &DishonestPerson{}
	if err = utils.Map2StructByJson(result, person, false); err != nil {
		return nil, err
	}

	return person, nil
}
