using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using Api.SignToken;
using AutoMapper;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace ThirdPartyApi.Controllers
{
    //[Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class SmsController : BaseController
    {
        private readonly ILogger<SmsController> _logger;
        private readonly ISignTokenService _signTokenService;
        private readonly IConfiguration _configuration;
        private readonly IMapper _mapper;

        public SmsController(ILogger<SmsController> logger, ISignTokenService signTokenService, IConfiguration configuration, IMapper mapper)
        {
            _logger = logger;
            _signTokenService = signTokenService;
            _configuration = configuration;
            _mapper = mapper;
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="signname">签名</param>
        /// <param name="templatecode">模板代码</param>
        /// <param name="phonenumber">手机号码</param>
        /// <param name="json">模板参数赋值json</param>
        /// <returns></returns>
        [HttpPost("sendsms")]
        public IActionResult SendSms(string signname, string templatecode, string phonenumber, string json)
        {
            //string json = "{\"name\":\"张三\",\"code\":\"ZS-123456\"}";

            string product = _configuration["Dysms:product"];
            string domain = _configuration["Dysms:domain"];
            string accesskeyid = _configuration["Dysms:accesskeyid"];
            string accesskeysecret = _configuration["Dysms:accesskeysecret"];

            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accesskeyid, accesskeysecret);
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            SendSmsResponse response = null;
            try
            {

                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = phonenumber;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = signname;
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = templatecode;
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = json;
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                //request.OutId = "yourOutId";
                //请求失败这里会抛ClientException异常
                response = acsClient.GetAcsResponse(request);

            }
            catch (ServerException e)
            {
                _logger.LogError("发送短信异常1，原因：" + e.ToString());
            }
            catch (ClientException e)
            {
                _logger.LogError("发送短信异常2，原因：" + e.ToString());
            }
            if (response != null)
            {
                if (response.Code != "OK")
                {
                    return Error(response.Message);
                }
            }
            else
            {
                return Error("失败");
            }
            return Success("成功", phonenumber);
        }

        /// <summary>
        /// 获取发送短信列表
        /// </summary>
        /// <param name="bizid">流水号</param>
        /// <param name="phonenumber">号码</param>
        /// <param name="senddate">发送日期</param>
        /// <param name="pagesize">页大小</param>
        /// <param name="pageindex">当前页码</param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public IActionResult GetListByPage(string bizid, string phonenumber, string senddate, long? pagesize = 10, long? pageindex = 1)
        {
            string product = _configuration["Dysms:product"];
            string domain = _configuration["Dysms:domain"];
            string accesskeyid = _configuration["Dysms:accesskeyid"];
            string accesskeysecret = _configuration["Dysms:accesskeysecret"];

            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accesskeyid, accesskeysecret);
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象
            QuerySendDetailsRequest request = new QuerySendDetailsRequest();
            //必填-号码
            request.PhoneNumber = phonenumber;
            //可选-流水号
            request.BizId = bizid;
            if (string.IsNullOrEmpty(senddate))
            {
                senddate = DateTime.Now.ToString("yyyyMMdd");
            }
            //必填-发送日期 支持30天内记录查询，格式yyyyMMdd       
            request.SendDate = senddate;
            //必填-页大小
            request.PageSize = pagesize;
            //必填-当前页码从1开始计数
            request.CurrentPage = pageindex;

            QuerySendDetailsResponse querySendDetailsResponse = null;
            try
            {
                querySendDetailsResponse = acsClient.GetAcsResponse(request);
            }
            catch (ServerException e)
            {
                _logger.LogError("查询短信异常1，原因：" + e.ToString());
            }
            catch (ClientException e)
            {
                _logger.LogError("查询短信异常2，原因：" + e.ToString());
            }

            if (querySendDetailsResponse != null)
            {
                if (querySendDetailsResponse.Code != "OK")
                {
                    return Error(querySendDetailsResponse.Message);
                }
                else
                {
                    var obj = new
                    {
                        rows = querySendDetailsResponse.SmsSendDetailDTOs,
                        total = querySendDetailsResponse.TotalCount
                    };
                    return Success("获取成功", obj);
                }
            }
            else
            {
                return Error("失败");
            }
        }
    }
}
