using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using WorkOrderApi.IRepositories;
using MadRunFabric.Model.WorkOrderApi.Areas_FW;

namespace WorkOrderApi.Controllers.ApointRegistration
{
    /// <summary>
    /// 预约挂号
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Route("api/[controller]")]
    [Produces("application/json")]
    public class ApointRegistrationController : BaseController
    {
        public IActionResult Index()
        {
            return View();
        }

        private readonly IConfiguration _configuration;
        private readonly ILogger<ApointRegistrationController> _logger;
        private readonly IHis_OpeRecordsRepository _his_operecordsRepository;

        public ApointRegistrationController(ILogger<ApointRegistrationController> logger,
            IHis_OpeRecordsRepository his_operecordsRepository,
           IConfiguration configuration
           )
        {
            _logger = logger;
            _his_operecordsRepository = his_operecordsRepository;
            _configuration = configuration;
        }

        //获取签名sign
        [HttpGet("getsign")]
        public async Task<IActionResult> GetSign(List<string> keyvalue)
        {
            //model.timestamp = DateTimeConvert.ToTimespan(DateTime.Now);//保存导入时间时间戳
            var input = keyvalue;

            var keys = new List<string>();
            var values = new List<string>();

            for (int index = 0; index < input.Count; index++)
            {
                if (index % 2 == 0) keys.Add(input[index]);
                else values.Add(input[index]);
            }
            //添加时间戳
            keys.Add("timestamp");
            values.Add(DateTimeConvert.ToTimespan(DateTime.Now).ToString());
            var result = keys.Zip(values, (key, value) =>
                                    new KeyValuePair<string, string>(key, value)).ToList ();
            var sign = GenerateSign(result ,"");

            
            //var obj = new
            //{
            //    tasktel = model,
            //    task = modelTask
            //};
            return Success("获取成功", sign);
        }

        #region 计算签名
        /// <summary>
        /// 生成签名
        /// </summary>
        /// <param name="paramlst">参数列表</param>
        /// <param name="IsToUpper">是否转大写</param>
        /// <param name="IsDirect">是否直接加上签名Key</param>
        /// <returns></returns>
        public static string GenerateSign(List<KeyValuePair<string, string>> lst, string privateKey)
        {            
            Comparison<KeyValuePair<string, string>> Comparer = new Comparison<KeyValuePair<string, string>>(CompareKeyValuepair);
            lst.Sort(Comparer);
            var paramlst = lst.Where(p => !string.IsNullOrEmpty(p.Value)).ToList();
            string signstr = string.Join("&", paramlst.Select(p => p.Key + "=" + p.Value)) + privateKey;
            return Sign(signstr, "UTF-8");
        }

        /// <summary>
        /// 根据Key比较排序位置
        /// </summary>
        private static int CompareKeyValuepair(KeyValuePair<string, string> p1, KeyValuePair<string, string> p2)
        {
            return string.Compare(p1.Key, p2.Key);
        }

        /// <summary>
        /// 签名字符串
        /// </summary>
        /// <param name="prestr">需要签名的字符串</param>
        /// <param name="key">密钥</param>
        /// <param name="inputCharset">编码格式</param>
        /// <returns>签名结果</returns>
        public static string Sign(string prestr, string inputCharset)
        {
            StringBuilder sb = new StringBuilder();
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(Encoding.GetEncoding(inputCharset).GetBytes(prestr));
            foreach (byte t1 in t)
            {
                sb.Append(t1.ToString("x2"));
            }
            return sb.ToString();
        }
        #endregion

        //获取AccessToken
        [HttpGet("gettokennew")]
        public async Task<IActionResult> GetAccessTokenNEW()//(List<string> keyvalue)
        {
            var keyvalue = new List<string>();
            #region 获取签名
            keyvalue.Add("appid");
            keyvalue.Add("appidvalue");
            keyvalue.Add("secret");
            keyvalue.Add("secretvalue");
            keyvalue.Add("timestamp");
            keyvalue.Add(DateTimeConvert.ToTimespan(DateTime.Now).ToString());
            //keyvalue.Add("sign");
                             
            #endregion
           
            #region 获取路径
            string ha = _configuration["his:hisaddress"].ToString();
            #endregion
            string strURL = "http://" + ha + "/Token";
            var m = new
            {
                appid = "appidvalue",
                secret = "secretvalue",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign= GetSign(keyvalue).Result.ToString()
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            if (jo1 != null && jo1["result"].ToString() == "0")
            {
                #region 添加访问记录
                /*var model = new His_OpeRecords();                
                model.requesttype = "获取token";
                model.requestaddress = strURL;
                model.requestparameter = json1;               
                model.backcontent = jo1.ToString ();                
                bool bl = await _his_operecordsRepository.Add(model);*/
                #endregion
                AddRecords("获取token", strURL, json1, jo1.ToString(),"成功");
                return Success("获取token成功", jo1);
            }
            else
            {
                if (jo1 != null)
                {
                    AddRecords("获取token", strURL, json1, jo1.ToString(), "失败");
                }
                else
                {
                    AddRecords("获取token", strURL, json1, "", "失败");
                }
                return Error("获取token失败");
            }
        }

        #region 获取出诊科室列表
        /// <summary>
        /// 获取出诊科室列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("divisionnew")]
        public async Task<IActionResult> DivisionAsyncNEW()
        {
            var keyvalue = new List<string>();
            #region 获取签名
            keyvalue.Add("access_token");
            keyvalue.Add("tokenvalue");
            keyvalue.Add("timestamp");
            keyvalue.Add(DateTimeConvert.ToTimespan(DateTime.Now).ToString());
            //keyvalue.Add("sign");
                        
            #endregion

            #region 获取路径
            string ha = _configuration["his:hisaddress"].ToString();
            #endregion
            string strURL = "http://" + ha + "/Appt/Division";
            var m = new
            {
                access_token = "access_token",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = GetSign(keyvalue).Result.ToString()
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            if (jo1 != null && jo1["result"].ToString() == "0")
            {
                AddRecords("获取出诊科室列表", strURL, json1, jo1.ToString(), "成功");
                return Success("获取出诊科室列表成功", jo1);
            }
            else
            {
                if (jo1 != null)
                {
                    AddRecords("获取出诊科室列表", strURL, json1, jo1.ToString(), "失败");
                }
                else
                {
                    AddRecords("获取出诊科室列表", strURL, json1, "", "失败");
                }
                return Error("获取出诊科室列表失败");
            }
        }
        #endregion

        #region 获取出诊排班
        /// <summary>
        /// 获取出诊排班
        /// </summary>
        /// <returns></returns>
        [HttpGet("schedulingnew")]
        public async Task<IActionResult> SchedulingAsyncNEW(string startdate,string enddate,string divisioncode)
        {
            var keyvalue = new List<string>();
            #region 获取签名
            keyvalue.Add("start_date");
            keyvalue.Add("startdate");
            keyvalue.Add("end_date");
            keyvalue.Add("enddate");
            keyvalue.Add("division_code");
            keyvalue.Add("divisioncode");
            keyvalue.Add("access_token");
            keyvalue.Add("tokenvalue");
            keyvalue.Add("timestamp");
            keyvalue.Add(DateTimeConvert.ToTimespan(DateTime.Now).ToString());
            //keyvalue.Add("sign");
            
            #endregion

            #region 获取路径
            string ha = _configuration["his:hisaddress"].ToString();
            #endregion
            string strURL = "http://" + ha + "/Appt/Scheduling";
            var m = new
            {
                start_date=startdate ,
                end_date=enddate,
                division_code=divisioncode ,
                access_token = "access_token",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = GetSign(keyvalue).Result.ToString()
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            if (jo1 != null && jo1["result"].ToString() == "0")
            {
                AddRecords("获取出诊排班", strURL, json1, jo1.ToString(), "成功");
                return Success("获取出诊排班成功", jo1);
            }
            else
            {
                if (jo1 != null)
                {
                    AddRecords("获取出诊排班", strURL, json1, jo1.ToString(), "失败");
                }
                else
                {
                    AddRecords("获取出诊排班", strURL, json1, "", "失败");
                }
                return Error("获取出诊排班失败");
            }
        }
        #endregion

        #region 获取出诊排班--按医生
        /// <summary>
        /// 获取出诊排班
        /// </summary>
        /// <returns></returns>
        [HttpGet("doctorschedulingnew")]
        public async Task<IActionResult> DoctorSchedulingAsyncNEW(string startdate, string enddate, string doctorcode)
        {
            var keyvalue = new List<string>();
            #region 获取签名
            keyvalue.Add("start_date");
            keyvalue.Add("startdate");
            keyvalue.Add("end_date");
            keyvalue.Add("enddate");
            keyvalue.Add("doctor_code");
            keyvalue.Add("doctorcode");
            keyvalue.Add("access_token");
            keyvalue.Add("tokenvalue");
            keyvalue.Add("timestamp");
            keyvalue.Add(DateTimeConvert.ToTimespan(DateTime.Now).ToString());
            //keyvalue.Add("sign");

            #endregion

            #region 获取路径
            string ha = _configuration["his:hisaddress"].ToString();
            #endregion
            string strURL = "http://" + ha + "/Appt/DoctorScheduling";
            var m = new
            {
                start_date = startdate,
                end_date = enddate,
                doctor_code = doctorcode,
                access_token = "access_token",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = GetSign(keyvalue).Result.ToString()
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            if (jo1 != null && jo1["result"].ToString() == "0")
            {
                AddRecords("按医生获取出诊排班", strURL, json1, jo1.ToString(), "成功");
                return Success("按医生获取出诊排班成功", jo1);
            }
            else
            {
                if (jo1 != null)
                {
                    AddRecords("按医生获取出诊排班", strURL, json1, jo1.ToString(), "失败");
                }
                else
                {
                    AddRecords("按医生获取出诊排班", strURL, json1, "", "失败");
                }
                return Error("按医生获取出诊排班失败");
            }
        }
        #endregion

        #region 获取分时出诊信息
        /// <summary>
        /// 获取出诊排班
        /// </summary>
        /// <returns></returns>
        [HttpGet("getperiodnew")]
        public async Task<IActionResult> GetPeriodAsyncNEW(string sched_id)
        {
            var keyvalue = new List<string>();
            #region 获取签名
            keyvalue.Add("sched_id");
            keyvalue.Add(sched_id);
            keyvalue.Add("access_token");
            keyvalue.Add("tokenvalue");
            keyvalue.Add("timestamp");
            keyvalue.Add(DateTimeConvert.ToTimespan(DateTime.Now).ToString());
            //keyvalue.Add("sign");

            #endregion

            #region 获取路径
            string ha = _configuration["his:hisaddress"].ToString();
            #endregion
            string strURL = "http://" + ha + "/Appt/GetPeriod";
            var m = new
            {
                
                sched_id ,
                access_token = "access_token",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = GetSign(keyvalue).Result.ToString()
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            if (jo1 != null && jo1["result"].ToString() == "0")
            {
                AddRecords("获取分时出诊信息", strURL, json1, jo1.ToString(), "成功");
                return Success("获取分时出诊信息成功", jo1);
            }
            else
            {
                if (jo1 != null)
                {
                    AddRecords("获取分时出诊信息", strURL, json1, jo1.ToString(), "失败");
                }
                else
                {
                    AddRecords("获取分时出诊信息", strURL, json1, "", "失败");
                }
                return Error("获取分时出诊信息失败");
            }
        }
        #endregion

        #region 添加预约申请
        /// <summary>
        /// 添加预约申请
        /// </summary>
        /// <returns></returns>
        [HttpGet("submitapptnew")]
        public async Task<IActionResult> SubmitApptAsyncNEW(string opinfo_id, string patient_name, string idcard_code,string phone)
        {
            var keyvalue = new List<string>();
            #region 获取签名
            keyvalue.Add("opinfo_id");
            keyvalue.Add(opinfo_id);
            keyvalue.Add("patient_name");
            keyvalue.Add(patient_name);
            keyvalue.Add("idcard_code");
            keyvalue.Add(idcard_code);
            keyvalue.Add("phone");
            keyvalue.Add(phone);
            keyvalue.Add("access_token");
            keyvalue.Add("tokenvalue");
            keyvalue.Add("timestamp");
            keyvalue.Add(DateTimeConvert.ToTimespan(DateTime.Now).ToString());
            //keyvalue.Add("sign");

            #endregion

            #region 获取路径
            string ha = _configuration["his:hisaddress"].ToString();
            #endregion
            string strURL = "http://" + ha + "/Appt/SubmitAppt";
            var m = new
            {
                opinfo_id,
                patient_name,
                idcard_code,
                phone,
                access_token = "access_token",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = GetSign(keyvalue).Result.ToString()
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            if (jo1 != null && jo1["result"].ToString() == "0")
            {
                AddRecords("添加预约申请", strURL, json1, jo1.ToString(), "成功");
                return Success("添加预约申请成功", jo1);
            }
            else
            {
                if (jo1 != null)
                {
                    AddRecords("添加预约申请", strURL, json1, jo1.ToString(), "失败");
                }
                else
                {
                    AddRecords("添加预约申请", strURL, json1, "", "失败");
                }
                return Error("获取预约申请失败");
            }
        }
        #endregion

        #region 取消预约申请
        /// <summary>
        /// 取消预约申请
        /// </summary>
        /// <returns></returns>
        [HttpGet("cancelapptnew")]
        public async Task<IActionResult> CancelApptAsyncNEW(string appt_id, string vericode)
        {
            var keyvalue = new List<string>();
            #region 获取签名
            keyvalue.Add("appt_id");
            keyvalue.Add(appt_id);
            keyvalue.Add("vericode");
            keyvalue.Add(vericode);
            
            keyvalue.Add("access_token");
            keyvalue.Add("tokenvalue");
            keyvalue.Add("timestamp");
            keyvalue.Add(DateTimeConvert.ToTimespan(DateTime.Now).ToString());
            //keyvalue.Add("sign");

            #endregion

            #region 获取路径
            string ha = _configuration["his:hisaddress"].ToString();
            #endregion
            string strURL = "http://" + ha + "/Appt/CancelAppt";
            var m = new
            {
                appt_id,
                vericode,
                access_token = "access_token",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = GetSign(keyvalue).Result.ToString()
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            if (jo1 != null && jo1["result"].ToString() == "0")
            {
                AddRecords("取消预约申请", strURL, json1, jo1.ToString(), "成功");
                return Success("取消预约申请成功", jo1);
            }
            else
            {
                if (jo1 != null)
                {
                    AddRecords("取消预约申请", strURL, json1, jo1.ToString(), "失败");
                }
                else
                {
                    AddRecords("取消预约申请", strURL, json1, "", "失败");
                }
                return Error("取消预约申请失败");
            }
        }
        #endregion

        #region 接口访问测试
        /// <summary>
        /// 接口访问测试
        /// </summary>
        /// <returns></returns>
        [HttpGet("apiconnectiontest")]
        public async Task<IActionResult> ApiConnectionTest()
        {
            var keyvalue = new List<string>();
            #region 获取签名
            keyvalue.Add("access_token");
            keyvalue.Add("tokenvalue");
            keyvalue.Add("timestamp");
            keyvalue.Add(DateTimeConvert.ToTimespan(DateTime.Now).ToString());
            //keyvalue.Add("sign");

            #endregion

            #region 获取路径
            string ha = _configuration["his:hisaddress"].ToString();
            #endregion
            string strURL = "http://" + ha + "/Appt/ApiConnectionTest";
            var m = new
            {
                access_token = "access_token",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = GetSign(keyvalue).Result.ToString()
            };
            //实体序列化和反序列化
            string json1 = JsonConvert.SerializeObject(m);
            string strHTML = MadRunFabric.Common.HttpMethods.HttpPost(strURL, json1);
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strHTML);
            if (jo1 != null && jo1["result"].ToString() == "0")
            {
                return Success("接口访问测试成功", jo1);
            }
            else
            {
                return Error("接口访问测试失败");
            }
        }
        #endregion

        #region 添加请求访问记录
        public bool AddRecords(string type,string address,string paras,string backcontent,string issuccess)
        {
            #region 添加访问记录
            var model = new His_OpeRecords();
            model.requesttype = type;
            model.requestaddress = address;
            model.requestparameter = paras;
            model.backcontent = backcontent;
            model.issuccess = issuccess;
            bool bl =  _his_operecordsRepository.Add(model).Result ;
            return bl;
            #endregion
            
        }
        #endregion


        #region 测试
        //获取AccessToken
        [HttpGet("gettoken")]
        public async Task<IActionResult> GetAccessToken()
        {
            var m = new
            {
                appid = "appidvalue",
                secret = "secretvalue",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = "sign"
            };
            return Success("获取token成功", m);
        }

        /// <summary>
        /// 获取出诊科室列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("division")]
        public async Task<IActionResult> DivisionAsync()
        {
            var m = new
            {
                access_token = "access_token",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = "SIGN"
            };
            return Success("获取token成功", m);
        }

        /// <summary>
        /// 获取出诊排班
        /// </summary>
        /// <returns></returns>
        [HttpGet("scheduling")]
        public async Task<IActionResult> SchedulingAsync(string startdate, string enddate, string divisioncode)
        {
            var m = new
            {
                start_date = startdate,
                end_date = enddate,
                division_code = divisioncode,
                access_token = "access_token",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = "sign"
            };
            return Success("获取出诊排班成功", m);
        }

        [HttpGet("doctorscheduling")]
        public async Task<IActionResult> DoctorSchedulingAsync(string startdate, string enddate, string doctorcode)
        {
            var m = new
            {
                start_date = startdate,
                end_date = enddate,
                doctor_code = doctorcode,
                access_token = "access_token",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = "sign"
            };
            return Success("按医生获取出诊排班成功", m);
        }

        /// <summary>
        /// 获取分时出诊信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("getperiod")]
        public async Task<IActionResult> GetPeriodAsync(string sched_id)
        {
            var m = new
            {

                sched_id,
                access_token = "access_token",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = "sign"
            };
            return Success("获取分时出诊信息成功", m);
        }

        /// <summary>
        /// 添加预约申请
        /// </summary>
        /// <returns></returns>
        [HttpGet("submitappt")]
        public async Task<IActionResult> SubmitApptAsync(string opinfo_id, string patient_name, string idcard_code, string phone)
        {
            var m = new
            {
                opinfo_id,
                patient_name,
                idcard_code,
                phone,
                access_token = "access_token",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = "sign"
            };
            return Success("添加预约申请成功", m);
        }

        /// <summary>
        /// 取消预约申请
        /// </summary>
        /// <returns></returns>
        [HttpGet("cancelappt")]
        public async Task<IActionResult> CancelApptAsync(string appt_id, string vericode)
        {
            var m = new
            {
                appt_id,
                vericode,
                access_token = "access_token",
                timestamp = DateTimeConvert.ToTimespan(DateTime.Now).ToString(),
                sign = "sign"
            };
            return Success("取消预约申请成功", m);
        }
            #endregion
    }
}