package aliyun

import (
	"fmt"
	cams20200606 "github.com/alibabacloud-go/cams-20200606/v2/client"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/alibabacloud-go/tea/tea"
)

const (
	AccessKeyId     string = "LTAI5tSJwCQyuaxXR3UxfnWw"
	AccessKeySecret string = "0pv4xhSPJv9IPSxrkB52FspJk27W7V"
	RegionId        string = "cams.ap-southeast-1.aliyuncs.com"
)

// Description:
// 使用AK&SK初始化账号Client
// @return Client
// @throws Exception
func CreateCamsClient() (_result *cams20200606.Client, _err error) {
	// 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
	// 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378661.html。
	config := &openapi.Config{
		// 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
		AccessKeyId: tea.String(AccessKeyId),
		// 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
		AccessKeySecret: tea.String(AccessKeySecret),
	}
	// Endpoint 请参考 https://api.aliyun.com/product/cams
	config.Endpoint = tea.String(RegionId)
	_result = &cams20200606.Client{}
	_result, _err = cams20200606.NewClient(config)
	return _result, _err
}

// GetCamsAppId 获取 AppId
// "LTAI5tSJwCQyuaxXR3UxfnWw", "0pv4xhSPJv9IPSxrkB52FspJk27W7V" "cams.ap-southeast-1.aliyuncs.com"
func GetCamsAppId() (string, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return "", _err
	}

	request := &cams20200606.IsvGetAppIdRequest{
		Type: tea.String("WHATSAPP"),
	}

	isvResponse, _err := client.IsvGetAppId(request)
	if _err != nil {
		return "", _err
	}

	return *isvResponse.Body.AppId, nil
}

// GetAutomation 获取号码欢迎消息、开场白和命令
func GetAutomation(custSpaceId, phone string) (*cams20200606.GetConversationalAutomationResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.GetConversationalAutomationRequest{
		CustSpaceId: tea.String(custSpaceId),
		PhoneNumber: tea.String(phone),
	}

	response, _err := client.GetConversationalAutomation(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// SetAutomation 设置号码欢迎消息、开场白和命令
func SetAutomation(custSpaceId, phone string, prompts []string) (*cams20200606.UpdateConversationalAutomationResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	tmpPrompts := make([]*string, 0)
	for _, v := range prompts {
		tmpPrompts = append(tmpPrompts, &v)
	}
	request := &cams20200606.UpdateConversationalAutomationRequest{
		CustSpaceId: tea.String(custSpaceId),
		PhoneNumber: tea.String(phone),
		Prompts:     tmpPrompts,
	}

	response, _err := client.UpdateConversationalAutomation(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// AddCamsPhoneNumber 添加WhatsApp号码
func AddCamsPhoneNumber(phone, cc, custSpaceId, verifiedName string) (*cams20200606.AddChatappPhoneNumberResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.AddChatappPhoneNumberRequest{
		PhoneNumber:  tea.String(phone),
		Cc:           tea.String(cc),
		CustSpaceId:  tea.String(custSpaceId),
		VerifiedName: tea.String(verifiedName),
	}

	response, _err := client.AddChatappPhoneNumber(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// SendCamsCode 发送验证码
func SendCamsCode(phone, custSpaceId, method, locale string) (*cams20200606.GetChatappVerifyCodeResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.GetChatappVerifyCodeRequest{
		PhoneNumber: tea.String(phone),
		CustSpaceId: tea.String(custSpaceId),
		Method:      tea.String(method),
		Locale:      tea.String(locale),
	}

	response, _err := client.GetChatappVerifyCode(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// SubmitCamsCode 提交验证信息
func SubmitCamsCode(phone, code, custSpaceId string) (*cams20200606.ChatappVerifyAndRegisterResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.ChatappVerifyAndRegisterRequest{
		PhoneNumber: tea.String(phone),
		VerifyCode:  tea.String(code),
		CustSpaceId: tea.String(custSpaceId),
	}

	response, _err := client.ChatappVerifyAndRegister(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// GetCamsQrcode 获取二维码列表
func GetCamsQrcode(phone, custSpaceId string) (*cams20200606.ListPhoneMessageQrdlResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.ListPhoneMessageQrdlRequest{
		PhoneNumber: tea.String(phone),
		CustSpaceId: tea.String(custSpaceId),
	}

	response, _err := client.ListPhoneMessageQrdl(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// CreateCamsQrcode 创建二维码
func CreateCamsQrcode(phone, custSpaceId, generateQrImage, prefilledMessage string) (*cams20200606.CreatePhoneMessageQrdlResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.CreatePhoneMessageQrdlRequest{
		PhoneNumber:      tea.String(phone),
		CustSpaceId:      tea.String(custSpaceId),
		GenerateQrImage:  tea.String(generateQrImage),
		PrefilledMessage: tea.String(prefilledMessage),
	}

	response, _err := client.CreatePhoneMessageQrdl(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// UpdateCamsQrcode 修改二维码
func UpdateCamsQrcode(phone, custSpaceId, generateQrImage, prefilledMessag, qrdlCode string) (*cams20200606.UpdatePhoneMessageQrdlResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.UpdatePhoneMessageQrdlRequest{
		PhoneNumber:      tea.String(phone),
		CustSpaceId:      tea.String(custSpaceId),
		GenerateQrImage:  tea.String(generateQrImage),
		PrefilledMessage: tea.String(prefilledMessag),
		QrdlCode:         tea.String(qrdlCode),
	}

	response, _err := client.UpdatePhoneMessageQrdl(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// RemoveCamsQrcode 删除二维码
func RemoveCamsQrcode(phone, custSpaceId, qrdlCode string) (*cams20200606.DeletePhoneMessageQrdlResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.DeletePhoneMessageQrdlRequest{
		PhoneNumber: tea.String(phone),
		CustSpaceId: tea.String(custSpaceId),
		QrdlCode:    tea.String(qrdlCode),
	}

	response, _err := client.DeletePhoneMessageQrdl(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// GetCamsBusiness 获取商业信息
func GetCamsBusiness(phone, custSpaceId string) (*cams20200606.QueryPhoneBusinessProfileResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.QueryPhoneBusinessProfileRequest{
		PhoneNumber: tea.String(phone),
		CustSpaceId: tea.String(custSpaceId),
	}

	response, _err := client.QueryPhoneBusinessProfile(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// SetCamsBusiness 获取商业信息
func SetCamsBusiness(phone, custSpaceId, address, description, vertical, email, profilePicUrl, about string, websites []*string) (*cams20200606.ModifyPhoneBusinessProfileResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.ModifyPhoneBusinessProfileRequest{
		PhoneNumber: tea.String(phone),
		CustSpaceId: tea.String(custSpaceId),
		Vertical:    tea.String(vertical),
	}

	if vertical != "" && vertical != "UNDEFINED" {
		request.Vertical = tea.String(vertical)
	}

	if address != "" {
		request.Address = tea.String(address)
	}

	if description != "" {
		request.Description = tea.String(description)
	}

	if profilePicUrl != "" {
		request.ProfilePictureUrl = tea.String(profilePicUrl)
	}

	if email != "" {
		request.Email = tea.String(email)
	}

	if about != "" {
		request.About = tea.String(about)
	}

	if len(websites) > 0 {
		request.Websites = websites
	}

	fmt.Printf("request=%v\n", request)

	response, _err := client.ModifyPhoneBusinessProfile(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// GetCamsPhoneVerifyStatus 查询号码验证状态
func GetCamsPhoneVerifyStatus(phone, custSpaceId string) (*cams20200606.GetPhoneNumberVerificationStatusResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.GetPhoneNumberVerificationStatusRequest{
		PhoneNumber: tea.String(phone),
		CustSpaceId: tea.String(custSpaceId),
	}

	response, _err := client.GetPhoneNumberVerificationStatus(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// RegisterCamsPhoneNumber 号码注册
func RegisterCamsPhoneNumber(phone, custSpaceId string) (*cams20200606.ChatappPhoneNumberRegisterResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.ChatappPhoneNumberRegisterRequest{
		PhoneNumber: tea.String(phone),
		CustSpaceId: tea.String(custSpaceId),
	}

	response, _err := client.ChatappPhoneNumberRegister(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// DeRegisterCamsPhoneNumber 号码取消注册
func DeRegisterCamsPhoneNumber(phone, custSpaceId string) (*cams20200606.ChatappPhoneNumberDeregisterResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.ChatappPhoneNumberDeregisterRequest{
		PhoneNumber: tea.String(phone),
		CustSpaceId: tea.String(custSpaceId),
	}

	response, _err := client.ChatappPhoneNumberDeregister(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// QueryCamsChatappPhoneNumbers 查询客户下的所有发送号码及号码状态
func QueryCamsChatappPhoneNumbers(custSpaceId string) (*cams20200606.QueryChatappPhoneNumbersResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.QueryChatappPhoneNumbersRequest{
		CustSpaceId: tea.String(custSpaceId),
	}

	response, _err := client.QueryChatappPhoneNumbers(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// ChatappSyncPhoneNumber 同步号码信息
func ChatappSyncPhoneNumber(custSpaceId string) (*cams20200606.ChatappSyncPhoneNumberResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.ChatappSyncPhoneNumberRequest{
		CustSpaceId: tea.String(custSpaceId),
	}

	response, _err := client.ChatappSyncPhoneNumber(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// UpdatePhoneWebhook 修改号码回调
func UpdatePhoneWebhook(phone, custSpaceId, callback string) (*cams20200606.UpdatePhoneWebhookResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.UpdatePhoneWebhookRequest{
		CustSpaceId: tea.String(custSpaceId),
		PhoneNumber: tea.String(phone),
		//StatusCallbackUrl: tea.String(callback),
		UpCallbackUrl: tea.String(callback),
		HttpFlag:      tea.String("Y"),
	}

	response, _err := client.UpdatePhoneWebhook(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// ListChatappTemplate 获取模板列表
func ListChatappTemplate(waId, name, language, auditStatus, templateType, code string, page, size int32) (*cams20200606.ListChatappTemplateResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.ListChatappTemplateRequest{
		CustSpaceId: tea.String(waId),
		Name:        tea.String(name),
		Language:    tea.String(language),
		AuditStatus: tea.String(auditStatus),
		Page: &cams20200606.ListChatappTemplateRequestPage{
			Index: tea.Int32(page),
			Size:  tea.Int32(size),
		},
		TemplateType: tea.String(templateType),
		Code:         tea.String(code),
	}

	response, _err := client.ListChatappTemplate(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// GetChatappTemplateInfo 获取模板详情
func GetChatappTemplateInfo(name, language, templateType, templateCode string) (*cams20200606.GetChatappTemplateDetailResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.GetChatappTemplateDetailRequest{
		TemplateName: tea.String(name),
		Language:     tea.String(language),
		TemplateType: tea.String(templateType),
		TemplateCode: tea.String(templateCode),
	}

	response, _err := client.GetChatappTemplateDetail(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// DeleteChatappTemplate 模板删除
func DeleteChatappTemplate(name, language, templateType, templateCode string) (*cams20200606.DeleteChatappTemplateResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.DeleteChatappTemplateRequest{
		TemplateName: tea.String(name),
		Language:     tea.String(language),
		TemplateType: tea.String(templateType),
		TemplateCode: tea.String(templateCode),
	}

	response, _err := client.DeleteChatappTemplate(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// SendChatappMessage 发送消息
// @see https://help.aliyun.com/zh/chatapp/developer-reference/api-cams-2020-06-06-sendchatappmessage
func SendChatappMessage(stype, templateCode, lang, sfrom, sto string) (*cams20200606.SendChatappMessageResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	request := &cams20200606.SendChatappMessageRequest{
		ChannelType:  tea.String("whatsapp"),
		Type:         tea.String(stype),
		TemplateCode: tea.String(templateCode),
		Language:     tea.String(lang),
		From:         tea.String(sfrom),
		To:           tea.String(sto),
	}

	response, _err := client.SendChatappMessage(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}

// SendBatchChatappMessage 发送批量消息
// @see https://help.aliyun.com/zh/chatapp/developer-reference/api-cams-2020-06-06-sendchatappmassmessage
func SendBatchChatappMessage(templateCode, lang, sfrom string, sto []string) (*cams20200606.SendChatappMassMessageResponse, error) {
	client, _err := CreateCamsClient()
	if _err != nil {
		return nil, _err
	}

	senderList := make([]*cams20200606.SendChatappMassMessageRequestSenderList, len(sto))
	for _, v := range sto {
		senderList = append(senderList, &cams20200606.SendChatappMassMessageRequestSenderList{
			To: &v,
		})
	}
	request := &cams20200606.SendChatappMassMessageRequest{
		ChannelType:  tea.String("whatsapp"),
		TemplateCode: tea.String(templateCode),
		Language:     tea.String(lang),
		From:         tea.String(sfrom),
		SenderList:   senderList,
	}

	response, _err := client.SendChatappMassMessage(request)
	if _err != nil {
		return nil, _err
	}

	return response, nil
}
