# -*- coding: utf-8 -*-
import uuid

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.profile import region_provider
from aliyunsdkdysmsapi.request.v20170525 import SendSmsRequest
import json
"""
短信业务调用接口示例，版本号：v20170525
Created on 2017-06-12
"""


class AliSmsObject(object):

    def __init__(self):
        # 注意：不要更改
        REGION = "cn-hangzhou"
        PRODUCT_NAME = "Dysmsapi"
        DOMAIN = "dysmsapi.aliyuncs.com"
        aliSms = {
            'ACCESS_KEY_ID': 'LTAIDFtlwLdttWiX',
            'ACCESS_KEY_SECRET': 'Siu6SolsTN5A3evXUkFLyyr0QZ3iiT',
        }
        # self.ACCESS_KEY_ID = 'LTAIDFtlwLdttWiX'
        # self.ACCESS_KEY_SECRET = 'Siu6SolsTN5A3evXUkFLyyr0QZ3iiT'
        self.acs_client = AcsClient(aliSms['ACCESS_KEY_ID'], aliSms['ACCESS_KEY_SECRET'], REGION)
        region_provider.add_endpoint(PRODUCT_NAME, REGION, DOMAIN)

    def do_send_sms(self, business_id, phone_numbers, sign_name, template_code, template_param=None):
        smsRequest = SendSmsRequest.SendSmsRequest()
        # 申请的短信模板编码,必填
        smsRequest.set_TemplateCode(template_code)

        # 短信模板变量参数
        if template_param is not None:
            smsRequest.set_TemplateParam(template_param)

        # 设置业务请求流水号，必填。
        smsRequest.set_OutId(business_id)

        # 短信签名
        smsRequest.set_SignName(sign_name)

        # 数据提交方式
        # smsRequest.set_method(MT.POST)

        # 数据提交格式
        # smsRequest.set_accept_format(FT.JSON)

        # 短信发送的号码列表，必填。
        smsRequest.set_PhoneNumbers(phone_numbers)

        # 调用短信发送接口，返回json
        smsResponse = self.acs_client.do_action_with_exception(smsRequest)

        # TODO 业务处理

        return smsResponse

    # 发送验证码
    def send_code_sms(self, phone, code, sign_name,temp_msg):
        __business_id = uuid.uuid1()
        # print(__business_id)
        # params = "{\"code\":\"{"+str(code)+"}\"}"
        params = "{\"code\":\"" + str(code) + "\"}"
        # params = u'{"name":"wqb","code":"12345678","address":"bz","phone":"13000000000"}'
        # 签名
        # sign_name = 'Ansjer'
        # 模板信息
        # temp_msg = 'SMS_151600991'
        res = self.do_send_sms(__business_id, phone, sign_name, temp_msg, params)
        # print(send_sms(__business_id, "13119657713", "云通信测试", "SMS_5250008", params))
        res_json = json.loads(res.decode('utf-8'))
        print(res_json)
        # {"Message":"OK","RequestId":"985FA027-C887-4186-A8F5-B6B8F3D123DB","BizId":"973407842937195533^0","Code":"OK"}
        # code = isv.BUSINESS_LIMIT_CONTROL 一分钟只能发一次
        return res_json
#
# aliSms = AliSmsObject()
# aliSms.send_sign_in_sms(phone=13119657713,code=123456)
