using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.Framework.Login;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.IService;
using ASHermed.SinoInterface.Code;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.Exception;
using ASHermed.SinoInterface.IFramework;
using ASHermed.SinoInterface.IFramework.SingleSignOn;
using ASHermed.SinoInterface.Tools;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using PoJun.Util;
using PoJun.Util.Maps;
using Renci.SshNet.Security;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace ASHermed.SinoInterface.Api.Service
{
    /// <summary>
	/// 三方服务
	/// </summary>
	public class SmsSurveyService : BaseService, ISmsSurveyService
    {
        IPubUserInfoRepository _pubUserInfoRepository;
        ILogger<SmsSurveyService> _logger;
        IOutService _outService;
        /// <summary>
        /// 三方服务
        /// </summary>
        public SmsSurveyService(IPubUserInfoRepository pubUserInfoRepository, ILogger<SmsSurveyService> logger, IOutService outService)
        {
            _pubUserInfoRepository = pubUserInfoRepository;
            _logger = logger;
            _outService = outService;
        }

        public void SaveSurvey()
        {
            string result = GetSurvey();
            _logger.LogInformation("回执抓取结果：" + result);
            if (result != null)
            {
                string surveyStr = result.Replace("\\[p\\]", ",");
                if (!string.IsNullOrEmpty(surveyStr))
                {
                    string[] surveyList = surveyStr.Split(',');
                    if (surveyList.Length > 0)
                    {
                        foreach (var survey in surveyList)
                        {
                            if (!string.IsNullOrEmpty(survey))
                            {
                                string surveyInfo = survey.Replace("\\[r\\]", ",");
                                string pid = surveyInfo.Split(',')[2];
                                string content = surveyInfo.Split(',')[1];

                                Pub_Sms_Survey smsSurvey = _pubUserInfoRepository.GetSmsSurvey(pid);
                                if (smsSurvey != null)
                                {
                                    smsSurvey.Content = content;
                                    _pubUserInfoRepository.UpdateSmsSurvey(smsSurvey);
                                }
                            }
                        }
                    }
                }
            }
        }

        public string GetSurvey()
        {
            string pwd = Common.GetMD5("PR8tL4h5+e0nuvHyD89Xka==");
            string url = "http://www.ztsms.cn/batchreplyget.do?username=smsservice"
                    + "&password=" + pwd;
            string rel = _outService.HttpGet(url);
            return rel;
        }

        public string SendSurvey(string phone, string content, string signature)
        {
            
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            //string tkey = sdf.format(new Date());
            string tkey = DateTime.Now.ToString("yyyyMMddHHmmss");
            string pwd = Common.GetMD5("986c80ac02cf541140c08008385bba9b" + tkey).ToLower();
            //pwd = "PR8tL4h5+e0nuvHyD89Xka==";
            content += signature;

            string url = "http://www.ztsms.cn/sendNSms.do?username=smsservice"
                    + "&password=" + pwd
                    + "&tkey=" + tkey
                    + "&mobile=" + phone
                    + "&content=" + HttpUtility.UrlEncode(content)
                    + "&productid=887362"
                    + "&xh=";
            string rel = _outService.HttpGet(url);
            //String rel = HttpUtil.getString(url);

            switch (rel.Split(',')[0])
            {
                case "-1":
                    throw new System.Exception("用户名或者密码不正确或用户禁用或者是管理账户");
                case "0":
                    throw new System.Exception("发送短信失败");
                case "2":
                    throw new System.Exception("余额不够或扣费错误");
                case "3":
                    throw new System.Exception("扣费失败异常（请联系客服）");
                case "6":
                    throw new System.Exception("有效号码为空");
                case "7":
                    throw new System.Exception("短信内容为空");
                case "8":
                    throw new System.Exception("无签名，必须，格式：【签名】");
                case "9":
                    throw new System.Exception("没有Url提交权限");
                case "10":
                    throw new System.Exception("发送号码过多,最多支持2000个号码");
                case "11":
                    throw new System.Exception("产品ID异常或产品禁用");
                case "12":
                    throw new System.Exception("参数异常");
                case "13":
                    throw new System.Exception("tkey参数错误");
                case "15":
                    throw new System.Exception("Ip验证失败");
                case "16":
                    throw new System.Exception("xh参数错误");
                case "19":
                    throw new System.Exception("短信内容过长，最多支持500个,或提交编码异常导致");
                case "1":
                    return rel;
                default:
                    break;
            }
            return null;
        }

        public bool Send(string phone, string content, string signature)
        {
            
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            string tkey = DateTime.Now.ToString("yyyyMMddHHmmss");//sdf.format(new Date());
            string pwd = Common.GetMD5("986c80ac02cf541140c08008385bba9b" + tkey).ToLower();

            content += signature;

            string url = "http://www.ztsms.cn/sendNSms.do?username=smsservice"
                    + "&password=" + pwd
                    + "&tkey=" + tkey
                    + "&mobile=" + phone
                    + "&content=" + HttpUtility.UrlEncode(content)
                    + "&productid=" + 887362
                    + "&xh=";

            string rel = _outService.HttpGet(url);

            switch (rel.Split(',')[0])
            {
                case "-1":
                case "2":
                case "0":
                case "19":
                case "16":
                case "15":
                case "13":
                case "12":
                case "11":
                case "10":
                case "9":
                case "8":
                case "7":
                case "6":
                case "3":
                    return SpareSend(phone, content, signature);
                case "1":
                    return true;
                default:
                    break;
            }
            return false;
        }

        public bool SpareSend(string phone, string content, string signature)
        {
            
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            string tkey = DateTime.Now.ToString("yyyyMMddHHmmss"); //sdf.format(new Date());
            string pwd = Common.GetMD5((Common.GetMD5("a61a683d2dd63d2c06c3fb97f897dab0") + tkey)).ToLower();

            content += signature;

            string url = "http://www.ztsms.cn/sendNSms.do?username=smstest"
                    + "&password=" + pwd
                    + "&tkey=" + tkey
                    + "&mobile=" + phone
                    + "&content=" + HttpUtility.UrlEncode(content)
                    + "&productid=" + 887362
                    + "&xh=";

            string rel = _outService.HttpGet(url);

            switch (rel.Split(',')[0])
            {
                case "-1":
                    throw new System.Exception("用户名或者密码不正确或用户禁用或者是管理账户");
                case "0":
                    throw new System.Exception("发送短信失败");
                case "2":
                    throw new System.Exception("余额不够或扣费错误");
                case "3":
                    throw new System.Exception("扣费失败异常（请联系客服）");
                case "6":
                    throw new System.Exception("有效号码为空");
                case "7":
                    throw new System.Exception("短信内容为空");
                case "8":
                    throw new System.Exception("无签名，必须，格式：【签名】");
                case "9":
                    throw new System.Exception("没有Url提交权限");
                case "10":
                    throw new System.Exception("发送号码过多,最多支持2000个号码");
                case "11":
                    throw new System.Exception("产品ID异常或产品禁用");
                case "12":
                    throw new System.Exception("参数异常");
                case "13":
                    throw new System.Exception("tkey参数错误");
                case "15":
                    throw new System.Exception("Ip验证失败");
                case "16":
                    throw new System.Exception("xh参数错误");
                case "19":
                    throw new System.Exception("短信内容过长，最多支持500个,或提交编码异常导致");
                case "1":
                    return true;
                default:
                    break;
            }
            return false;
        }



    }
}
