using MadRunFabric.Common;
using MadRunFabric.Common.Enums;
using MadRunFabric.Model.TestUserTypeApi;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Common;
using System.Linq;
using System.Threading.Tasks;
using TestUserTypeApi.IRepositories;
using Microsoft.Extensions.Configuration;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Authorization;

namespace TestUserTypeApi.Controllers
{
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class TestController: BaseController
    {
        private readonly IHzsfMassagesRepository _IHzsfMassagesRepository;
        private readonly Iv_csm_zhuyuanRepository _Iv_csm_zhuyuanRepository;
        private readonly ITSys_AreaRepository _sys_areaRepository;
        private readonly IdxsfjlsRepository _IdxsfjlsRepository;
        private readonly ILogger<TestController> _logger;
        private readonly IConfiguration _configuration;

        public TestController(IdxsfjlsRepository dxsfjlsRepository, ILogger<TestController> logger,
             IConfiguration configuration,
            ITSys_AreaRepository TSys_AreaRepository, 
            Iv_csm_zhuyuanRepository v_csm_zhuyuanRepository,
            IHzsfMassagesRepository HzsfMassagesRepository)
        {
            _IHzsfMassagesRepository =HzsfMassagesRepository;
            _Iv_csm_zhuyuanRepository = v_csm_zhuyuanRepository;
            _sys_areaRepository = TSys_AreaRepository;
            _IdxsfjlsRepository = dxsfjlsRepository;
            _configuration = configuration;
            _logger = logger;
        }
        #region 随访
        /// <summary>
        /// 获取出院三天的患者信息
        /// </summary>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        [HttpGet("gethzxxs")]
        public async Task<IActionResult> Gethzxxs(int PageIndex, int PageSize, string nowdatetime)
        {

            List<IConditionalModel> conModels = new List<IConditionalModel>();

            if (nowdatetime != null)
            {
                nowdatetime = Convert.ToDateTime(nowdatetime).AddDays(-3).ToString("yyyy-MM-dd");
            }
            else
            {
                nowdatetime = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd");
            }
            conModels.Add(new ConditionalModel() { FieldName = "CY_DATE", ConditionalType = ConditionalType.Equal, FieldValue = nowdatetime });
            conModels.Add(new ConditionalModel() { FieldName = "LY_TYPE", ConditionalType = ConditionalType.IsNot, FieldValue = "死亡" });
            //conModels.Add(new ConditionalModel() { FieldName = "IS_OP", ConditionalType = ConditionalType.IsNot, FieldValue ="1"  });
            int recordCount = 0;
            var list = await _Iv_csm_zhuyuanRepository.GetListViewByPage(conModels, new MyPageModel() { PageIndex = PageIndex, PageSize = PageSize, PageCount = recordCount }, nowdatetime, "zy_no desc");
            // var list = await _Iv_csm_zhuyuanRepository.GetListByPage(conModels, new MyPageModel() { PageIndex = PageIndex, PageSize = PageSize, PageCount = recordCount }, "zy_no desc");
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = list,
            };

            return Success("成功", obj);
        }
        /// <summary>
        /// 根据手机号和住院时间
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("gethzxxsbyid")]
        public async Task<IActionResult> GetSzmzsbyid(string telphone, string nowdatetime)
        {
            var model = await _Iv_csm_zhuyuanRepository.GetSingle(p => p.CY_DATE == nowdatetime && p.PAT_PHONE == telphone);
            return Success("成功", model);
        }

        /// <summary>
        /// 获取出院患者短信发送记录
        /// </summary>
        /// <returns></returns>
        [HttpGet("getsendhfinfo")]
        public async Task<IActionResult> GetSendhfinfo(int PageIndex, int PageSize, string key, string yqinfo, string sendmydcent)
        {
            var sort = Builders<HzsfMassages>.Sort.Descending("senddate");
            var listApp = new List<FilterDefinition<HzsfMassages>>();
            listApp.Add(Builders<HzsfMassages>.Filter.Eq("isdelete", 0));
            if (key != null && key != "")
            {
                var normallistAppor = new List<FilterDefinition<HzsfMassages>>();
                normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.ZY_DEPT_NAME.Contains(key)));
                normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.NAME.Contains(key)));
                normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.PAT_PHONE.Contains(key)));
                listApp.Add(Builders<HzsfMassages>.Filter.Or(normallistAppor));
            }
            if (sendmydcent != null || sendmydcent != "")
            {

                var normallistAppor = new List<FilterDefinition<HzsfMassages>>();
                if (sendmydcent == "满意")
                {
                    normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.sendmyeds == sendmydcent));
                    normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.replaycenters.Contains("1")));
                    listApp.Add(Builders<HzsfMassages>.Filter.Or(normallistAppor));
                }
                else if (sendmydcent == "表扬")
                {
                    normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.sendmyeds == sendmydcent));
                    normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.replaycenters.Contains("2")));
                    listApp.Add(Builders<HzsfMassages>.Filter.Or(normallistAppor));
                }
                else if (sendmydcent == "不满意")
                {
                    normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.sendmyeds == sendmydcent&&p.sendmyeds!="满意"));
                    normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.replaycenters.Contains("3")));
                    listApp.Add(Builders<HzsfMassages>.Filter.Or(normallistAppor));
                }
            }
            var filter = Builders<HzsfMassages>.Filter.And(listApp);

            var list = await _IHzsfMassagesRepository.GetByPage(filter, PageIndex, PageSize, sort);
            var redCount = await _IHzsfMassagesRepository.CountAsync(filter);   //获取总数
            var listmodel = new List<HzsfMassages>();
            foreach (var item in list)
            {
                listmodel.Add(item);
            }
            var obj = new
            {
                rows = listmodel,
                total = redCount
            };
            return Success("成功", obj);
        }

        /// <summary>
        /// 导出随访记录信息
        /// </summary>
        /// <param name="key"></param>
        /// <param name="yqinfo"></param>
        /// <param name="sendmydcent"></param>
        /// <returns></returns>
        [HttpGet("exportexcel")]
        [AllowAnonymous]
        public async Task<IActionResult> ExportExcelAsync(string key, string yqinfo, string sendmydcent)
        {
            try
            {
                var sort = Builders<HzsfMassages>.Sort.Descending("senddate");
                var listApp = new List<FilterDefinition<HzsfMassages>>();
                listApp.Add(Builders<HzsfMassages>.Filter.Eq("isdelete", 0));
                if (key != null && key != "")
                {
                    var normallistAppor = new List<FilterDefinition<HzsfMassages>>();
                    normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.ZY_DEPT_NAME.Contains(key)));
                    normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.NAME.Contains(key)));
                    normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.PAT_PHONE.Contains(key)));
                    listApp.Add(Builders<HzsfMassages>.Filter.Or(normallistAppor));
                }
                if (sendmydcent != null || sendmydcent != "")
                {

                    var normallistAppor = new List<FilterDefinition<HzsfMassages>>();
                    if (sendmydcent == "满意")
                    {
                        normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.sendmyeds == sendmydcent));
                        normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.replaycenters.Contains("1")));
                        listApp.Add(Builders<HzsfMassages>.Filter.Or(normallistAppor));
                    }
                    else if (sendmydcent == "表扬")
                    {
                        normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.sendmyeds == sendmydcent));
                        normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.replaycenters.Contains("2")));
                        listApp.Add(Builders<HzsfMassages>.Filter.Or(normallistAppor));
                    }
                    else if (sendmydcent == "不满意")
                    {
                        //normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.sendmyeds == sendmydcent && p.sendmyeds != "满意"));
                        //normallistAppor.Add(Builders<HzsfMassages>.Filter.Where(p => p.replaycenters.Contains("3")));
                        listApp.Add(Builders<HzsfMassages>.Filter.Where(p=>p.replaycenters.Contains("3") && p.sendmyeds == sendmydcent && p.sendmyeds != "满意"));
                    }
                }
                var filter = Builders<HzsfMassages>.Filter.And(listApp);

                var hzsflist =await _IHzsfMassagesRepository.Get(filter);

                List<Model.Hzsfsendmassage> list = new List<Model.Hzsfsendmassage>();
                foreach (var item in hzsflist)
                {
                    Model.Hzsfsendmassage model = new Model.Hzsfsendmassage();
                    model.replaycenters     =item.replaycenters;
                    model.sendmyeds         =item.sendmyeds;
                    model.senddate          =item.senddate!=null ? Convert.ToDateTime(item.senddate).ToString("yyyy - MM - dd  HH: mm:ss") : "";
                    model.ZY_NO             =item.ZY_NO;
                    model.NAME              =item.NAME;
                    model.SEX               =item.SEX;
                    model.ZY_AGE            =item.ZY_AGE;
                    model.PAT_PHONE         =item.PAT_PHONE;
                    model.CY_ZD             =item.CY_ZD;
                    model.CY_DEPT_NAME      =item.CY_DEPT_NAME;
                    model.CY_DATE           =item.CY_DATE;
                    model.ZY_DEPT_NAME      =item.ZY_DEPT_NAME;
                    model.statesissuccess   =item.statesissuccess;
                    model.nomybecause = item.nomybecause;
                    list.Add(model);
                }
                NPOIHelper npoi = new NPOIHelper();
                var tb = ModelConvertHelper<Model.Hzsfsendmassage>.ConvertListToDataTable(list);
                if (tb != null)
                {
                    //导出dtnew 
                    string[] cols = { "回复内容","满意度","发送时间","住院号","病人姓名","病人性别","住院年龄","本人联系电话","出院诊断","出院科室","出院日期","住院科室名称","发送状态","备注"};

                    byte[] sm = npoi.ExportToExcel1(tb, cols);
                    if (sm != null)
                    {
                        return File(sm, "application/vnd.ms-excel", "随访记录信息表.xlsx");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
                }
                return Error("导出失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出异常");
                return Error("导出失败");
            }
        }

        //获取统计报表信息
        [HttpGet("getsfbbinfolist")]
        public async Task<IActionResult> Getsfbbinfolist(string stime, string etime)
        {
            //if (!string.IsNullOrEmpty(stime))
            //    query = query.Where(it => it.createtime >= Convert.ToDateTime(stime + " 00:00:00"));
            //if (!string.IsNullOrEmpty(etime))
            //    query = query.Where(it => it.createtime <= Convert.ToDateTime(etime + " 23:59:59"));
            //定义字段
            var deptname = "";//科室名


            #region 获取集合信息
            //定义总数字段信息
            var hzallcounts = 0;
            var sfallcounts = "";//科室总发送数
            var yhfcounts = "";//已回复
            var whfcounts = "";//未回复
            var mycounts = "";//满意数 
            var mycountbls = "";//满意率
            var bycounts = "";//表扬数
            var bycountbls = "";//表扬率
            var nomycounts = "";//不满意数
            var nomycountbls = "";//不满意率
            var othercounts = "";//其他数量
            var hfmydbls = "";//回复满意率（回复前满意数加回复前表扬率除以总数）
            var zhmydbfbs = "";//综合满意度
            var hfqmycounts = "";//回复前满意数
            var hfqbycounts = "";//回复前表扬数

            //定义集合来存储统计信息
            List<Model.Hzsfmassagebblist> hzssmassagebblist = new List<Model.Hzsfmassagebblist>();


            //先获取所有的科室信息
            var deptnamelist = _IHzsfMassagesRepository.GetLists();
            //遍历所有存在的科室进行总结数据
            foreach (var item in deptnamelist)
            {
                #region 定义字段
                var hzallcuont = 0;
                var sfallcount = "0";//科室总发送数
                var yhfcount = "0";//已回复
                var whfcount = "0";//未回复
                var mycount = "0";//满意数 
                var mycountbl = "";//满意率
                var bycount = "0";//表扬数
                var bycountbl = "";//表扬率
                var nomycount = "0";//不满意数
                var nomycountbl = "";//不满意率
                var othercount = "0";//其他数量
                var hfmydbl = "";//回复满意率（回复前满意数加回复前表扬率除以总数）
                var hfqmycount = "0";//回复前满意数
                var hfqbycount = "0";//回复前表扬数
                var hfqnomycount = "0";//回复前不满意数
                var zhmydbfb = "";//综合满意度 
                #endregion
                 hzallcuont = _Iv_csm_zhuyuanRepository.GetListcount(stime,etime,item.ToString());

                //定义对象给集合数据赋值
                Model.Hzsfmassagebblist hzsfmassagemodel = new Model.Hzsfmassagebblist();
                hzsfmassagemodel.deptname = item.ToString();//赋值科室
                                                            //检索本科室的随访总数、满意数、表扬数、不满意数、其他数、综合满意度
                hzsfmassagemodel.hzallcount = hzallcuont;
                if (!string.IsNullOrEmpty(stime) && !string.IsNullOrEmpty(etime))
                {
                    //科室随访总数
                    sfallcount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                       && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                       && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                    //科室随访满意数
                    mycount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                         && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                         && (p.replaycenters == "1" || p.replaycenters == "满意" || p.sendmyeds == "满意")
                                                                           && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                    //科室随访表扬数
                    bycount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                           && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                           && (p.replaycenters == "2" || p.replaycenters == "表扬" || p.sendmyeds == "表扬")
                                                                             && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                    //科室随访不满意数
                    nomycount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                           && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                           && (p.replaycenters == "3" || p.replaycenters == "不满意" )
                                                                           && (p.sendmyeds != "满意" || p.sendmyeds != "表扬"|| p.replaycenters != "满意" || p.replaycenters != "表扬")
                                                                             && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                    ///获取已回复数
                    yhfcount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                         && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                         && p.CY_DEPT_NAME == item.ToString()
                                                                         && p.replaycenters != "").Result.ToString();
                    //获取未回复数
                    whfcount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                         && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                         && p.CY_DEPT_NAME == item.ToString()
                                                                         && p.replaycenters == "").Result.ToString();
                    //回复前满意数
                    hfqmycount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                           && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                           && (p.replaycenters == "1" || p.replaycenters == "满意")
                                                                             && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                    //回复前表扬数
                    hfqbycount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                            && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                            && (p.replaycenters == "2" || p.replaycenters == "表扬")
                                                                              && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                    hfqnomycount= _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                             && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                             && (p.replaycenters == "3" || p.replaycenters == "不满意")
                                                                               && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                }
                else
                {
                    //科室随访总数
                    sfallcount = _IHzsfMassagesRepository.Count(p => p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                    //科室随访满意数
                    mycount = _IHzsfMassagesRepository.Count(p => (p.replaycenters == "1" || p.replaycenters == "满意" || p.sendmyeds == "满意")
                                                             && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                    //科室随访表扬数
                    bycount = _IHzsfMassagesRepository.Count(p => (p.replaycenters == "2" || p.replaycenters == "表扬" || p.sendmyeds == "表扬")
                                                             && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                    //科室随访不满意数
                    nomycount = _IHzsfMassagesRepository.Count(p => p.sendmyeds != "满意"
                                                                      && (p.replaycenters == "3" || p.replaycenters == "不满意")
                                                                      && (p.sendmyeds != "满意" || p.sendmyeds != "表扬" || p.replaycenters != "满意" || p.replaycenters != "表扬")
                                                                      && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                    ///获取已回复数
                    yhfcount = _IHzsfMassagesRepository.Count(p => p.CY_DEPT_NAME == item.ToString()
                                                                         && p.replaycenters != "").Result.ToString();
                    //获取未回复数
                    whfcount = _IHzsfMassagesRepository.Count(p => p.CY_DEPT_NAME == item.ToString()
                                                                         && p.replaycenters == "").Result.ToString();
                    //回复前满意数
                    hfqmycount = _IHzsfMassagesRepository.Count(p => (p.replaycenters == "1" || p.replaycenters == "满意")
                                                                             && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                    //回复前表扬数
                    hfqbycount = _IHzsfMassagesRepository.Count(p => (p.replaycenters == "2" || p.replaycenters == "表扬")
                                                                              && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                    hfqnomycount = _IHzsfMassagesRepository.Count(p => (p.replaycenters == "3" || p.replaycenters == "不满意")
                                                                               && p.CY_DEPT_NAME == item.ToString()).Result.ToString();

                }
                //科室随访其他数量和综合满意度
                if (Convert.ToInt32(sfallcount) > 0)
                {
                    //科室随访其他数量
                    //othercount = (Convert.ToInt32(sfallcount) - Convert.ToInt32(hfqmycount) - Convert.ToInt32(hfqbycount) - Convert.ToInt32(hfqnomycount)- Convert.ToInt32(whfcount)).ToString();
                    othercount = (Convert.ToInt32(sfallcount) - Convert.ToInt32(mycount) - Convert.ToInt32(bycount) - Convert.ToInt32(nomycount) - Convert.ToInt32(whfcount)).ToString();

                }
                mycount = (Convert.ToInt32(mycount) + Convert.ToInt32(whfcount)).ToString();

                if (Convert.ToInt32(sfallcount) > 0)
                {
                    //满意率
                    mycountbl = (Convert.ToDouble(mycount) / Convert.ToDouble(sfallcount)).ToString("0.00%");
                    //表扬率
                    bycountbl = (Convert.ToDouble(bycount) / Convert.ToDouble(sfallcount)).ToString("0.00%");
                    //不满意率
                    nomycountbl = (Convert.ToDouble(nomycount) / Convert.ToDouble(sfallcount)).ToString("0.00%");
                    //回复满意率
                    hfmydbl = ((Convert.ToDouble(hfqmycount) + Convert.ToDouble(hfqbycount) + Convert.ToInt32(whfcount)) / (Convert.ToDouble(sfallcount) - Convert.ToDouble(othercount))).ToString("0.00%");
                    //综合满意度
                    double percent = (Convert.ToDouble(mycount) + Convert.ToDouble(bycount)) / (Convert.ToDouble(sfallcount)- Convert.ToDouble(othercount));
                    zhmydbfb = percent.ToString("0.00%");
                }
                else
                {
                    //满意率
                    mycountbl = "0.00%";
                    //表扬率
                    bycountbl = "0.00%";
                    //不满意率
                    nomycountbl = "0.00%";
                    //回复满意率
                    hfmydbl = "0.00%";
                    zhmydbfb = "0.00%";
                }

                hzallcounts += hzallcuont;
                #region 赋值
                hzsfmassagemodel.hzallcount = hzallcuont;
                hzsfmassagemodel.sfallcount = sfallcount;
                hzsfmassagemodel.yhfcount = yhfcount;
                hzsfmassagemodel.whfcount = whfcount;
                hzsfmassagemodel.mycount = mycount;
                hzsfmassagemodel.mycountbl = mycountbl;
                hzsfmassagemodel.bycount = bycount;
                hzsfmassagemodel.bycountbl = bycountbl;
                hzsfmassagemodel.nomycount = nomycount;
                hzsfmassagemodel.nomycountbl = nomycountbl;
                hzsfmassagemodel.othercount = othercount;
                hzsfmassagemodel.hfmydbl = hfmydbl;
                hzsfmassagemodel.zhmydbfb = zhmydbfb;
                hzssmassagebblist.Add(hzsfmassagemodel);
                #endregion

                #region 汇总信息
                if (sfallcounts == "")
                {

                    sfallcounts = sfallcount;//所有科室总随访书
                    yhfcounts = yhfcount;//已回复
                    whfcounts = whfcount;//未回复
                    mycounts = mycount;//所有科室总满意数
                    bycounts = bycount;//所有科室总表扬数
                    nomycounts = nomycount;//所有科室总不满意数
                    othercounts = othercount;//所有科室总其他数
                    hfqmycounts = hfqmycount;//回复前满意数
                    hfqbycounts = hfqbycount;//回复后满意数
                }
                else
                {
                    sfallcounts = (Convert.ToInt32(sfallcounts) + Convert.ToInt32(sfallcount)).ToString();//所有科室总随访书
                    yhfcounts = (Convert.ToInt32(yhfcounts) + Convert.ToInt32(yhfcount)).ToString();//所有科室已回复数
                    whfcounts = (Convert.ToInt32(whfcounts) + Convert.ToInt32(whfcount)).ToString();//所有科室未回复数
                    mycounts = (Convert.ToInt32(mycounts) + Convert.ToInt32(mycount)).ToString();//所有科室总满意数
                    bycounts = (Convert.ToInt32(bycounts) + Convert.ToInt32(bycount)).ToString();//所有科室总表扬数
                    nomycounts = (Convert.ToInt32(nomycounts) + Convert.ToInt32(nomycount)).ToString();//所有科室总不满意数
                    othercounts = (Convert.ToInt32(othercounts) + Convert.ToInt32(othercount)).ToString();//所有科室总其他数
                    hfqmycounts = (Convert.ToInt32(hfqmycounts) + Convert.ToInt32(hfqmycount)).ToString();//回复前满意数
                    hfqbycounts = (Convert.ToInt32(hfqbycounts) + Convert.ToInt32(hfqbycount)).ToString();//回复后满意数

                }
                #endregion
            }
            #region 总数赋值
            //if (Convert.ToInt32(yhfcounts) > 0)
            //{
            //    //满意率
            //    mycountbls = (Convert.ToDouble(mycounts) / Convert.ToDouble(yhfcounts)).ToString("0.00%");
            //    //表扬率
            //    bycountbls = (Convert.ToDouble(bycounts) / Convert.ToDouble(yhfcounts)).ToString("0.00%");
            //    //不满意率
            //    nomycountbls = (Convert.ToDouble(nomycounts) / Convert.ToDouble(yhfcounts)).ToString("0.00%");

            //    //回复满意率
            //    hfmydbls = ((Convert.ToDouble(hfqmycounts) + Convert.ToDouble(hfqbycounts)) / Convert.ToDouble(yhfcounts)).ToString("0.00%");
            //    //综合满意度
            //    double percent = (Convert.ToDouble(mycounts) + Convert.ToDouble(bycounts)) / Convert.ToDouble(yhfcounts);
            //    zhmydbfbs = percent.ToString("0.00%");
            //}
            if (Convert.ToInt32(sfallcounts) > 0)
            {
                //满意率
                mycountbls = (Convert.ToDouble(mycounts) / Convert.ToDouble(sfallcounts)).ToString("0.00%");
                //表扬率
                bycountbls = (Convert.ToDouble(bycounts) / Convert.ToDouble(sfallcounts)).ToString("0.00%");
                //不满意率
                nomycountbls = (Convert.ToDouble(nomycounts) / Convert.ToDouble(sfallcounts)).ToString("0.00%");
                //回复满意率
                hfmydbls = ((Convert.ToDouble(hfqmycounts) + Convert.ToDouble(hfqbycounts) + Convert.ToInt32(whfcounts)) / (Convert.ToDouble(sfallcounts) - Convert.ToDouble(othercounts))).ToString("0.00%");
                //综合满意度
                double percent = (Convert.ToDouble(mycounts) + Convert.ToDouble(bycounts)) / (Convert.ToDouble(sfallcounts) - Convert.ToDouble(othercounts));
                zhmydbfbs = percent.ToString("0.00%");
            }
            //定义对象给集合数据赋值
            Model.Hzsfmassagebblist hzsfmassagemodel1 = new Model.Hzsfmassagebblist();
            hzsfmassagemodel1.deptname = "合计";
            hzsfmassagemodel1.hzallcount = hzallcounts;
            hzsfmassagemodel1.sfallcount = sfallcounts;
            hzsfmassagemodel1.yhfcount = yhfcounts;
            hzsfmassagemodel1.whfcount = whfcounts;
            hzsfmassagemodel1.mycount = mycounts;
            hzsfmassagemodel1.mycountbl = mycountbls;
            hzsfmassagemodel1.bycount = bycounts;
            hzsfmassagemodel1.bycountbl = bycountbls;
            hzsfmassagemodel1.nomycount = nomycounts;
            hzsfmassagemodel1.nomycountbl = nomycountbls;
            hzsfmassagemodel1.othercount = othercounts;
            hzsfmassagemodel1.hfmydbl = hfmydbls;
            hzsfmassagemodel1.zhmydbfb = zhmydbfbs;
            hzssmassagebblist.Add(hzsfmassagemodel1);
            #endregion
            #endregion
            return Success("成功",hzssmassagebblist);
        }
/// <summary>
/// 导出统计报表
/// </summary>
/// <param name="stime"></param>
/// <param name="etime"></param>
/// <returns></returns>
        [HttpGet("exportexcelsfbb")]
        [AllowAnonymous]
        public async Task<IActionResult> Exportexcelsfbb(string stime, string etime)
        {
            try
            {

                #region 获取集合信息
                //定义总数字段信息
                var hzallcounts = 0;
                var sfallcounts = "";//科室总发送数
                var yhfcounts = "";//已回复
                var whfcounts = "";//未回复
                var mycounts = "";//满意数 
                var mycountbls = "";//满意率
                var bycounts = "";//表扬数
                var bycountbls = "";//表扬率
                var nomycounts = "";//不满意数
                var nomycountbls = "";//不满意率
                var othercounts = "";//其他数量
                var hfmydbls = "";//回复满意率（回复前满意数加回复前表扬率除以总数）
                var zhmydbfbs = "";//综合满意度
                var hfqmycounts = "";//回复前满意数
                var hfqbycounts = "";//回复前表扬数

                //定义集合来存储统计信息
                List<Model.Hzsfmassagebblist> hzssmassagebblist = new List<Model.Hzsfmassagebblist>();


                //先获取所有的科室信息
                var deptnamelist = _IHzsfMassagesRepository.GetLists();
                //遍历所有存在的科室进行总结数据
                foreach (var item in deptnamelist)
                {
                    #region 定义字段
                    var hzallcuont = 0;
                    var sfallcount = "0";//科室总发送数
                    var yhfcount = "0";//已回复
                    var whfcount = "0";//未回复
                    var mycount = "0";//满意数 
                    var mycountbl = "";//满意率
                    var bycount = "0";//表扬数
                    var bycountbl = "";//表扬率
                    var nomycount = "0";//不满意数
                    var nomycountbl = "";//不满意率
                    var othercount = "0";//其他数量
                    var hfmydbl = "";//回复满意率（回复前满意数加回复前表扬率除以总数）
                    var hfqmycount = "0";//回复前满意数
                    var hfqbycount = "0";//回复前表扬数
                    var hfqnomycount = "0";//回复前不满意数
                    var zhmydbfb = "";//综合满意度 
                    #endregion
                    hzallcuont = _Iv_csm_zhuyuanRepository.GetListcount(stime, etime, item.ToString());

                    //定义对象给集合数据赋值
                    Model.Hzsfmassagebblist hzsfmassagemodel = new Model.Hzsfmassagebblist();
                    hzsfmassagemodel.deptname = item.ToString();//赋值科室
                                                                //检索本科室的随访总数、满意数、表扬数、不满意数、其他数、综合满意度
                    hzsfmassagemodel.hzallcount = hzallcuont;
                    if (!string.IsNullOrEmpty(stime) && !string.IsNullOrEmpty(etime))
                    {
                        //科室随访总数
                        sfallcount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                           && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                           && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                        //科室随访满意数
                        mycount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                             && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                             && (p.replaycenters == "1" || p.replaycenters == "满意" || p.sendmyeds == "满意")
                                                                               && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                        //科室随访表扬数
                        bycount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                               && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                               && (p.replaycenters == "2" || p.replaycenters == "表扬" || p.sendmyeds == "表扬")
                                                                                 && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                        //科室随访不满意数
                        nomycount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                               && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                               && (p.replaycenters == "3" || p.replaycenters == "不满意")
                                                                               && (p.sendmyeds != "满意" || p.sendmyeds != "表扬" || p.replaycenters != "满意" || p.replaycenters != "表扬")
                                                                                 && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                        ///获取已回复数
                        yhfcount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                             && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                             && p.CY_DEPT_NAME == item.ToString()
                                                                             && p.replaycenters != "").Result.ToString();
                        //获取未回复数
                        whfcount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                             && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                             && p.CY_DEPT_NAME == item.ToString()
                                                                             && p.replaycenters == "").Result.ToString();
                        //回复前满意数
                        hfqmycount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                               && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                               && (p.replaycenters == "1" || p.replaycenters == "满意")
                                                                                 && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                        //回复前表扬数
                        hfqbycount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                                && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                                && (p.replaycenters == "2" || p.replaycenters == "表扬")
                                                                                  && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                        hfqnomycount = _IHzsfMassagesRepository.Count(p => p.senddate >= Convert.ToDateTime(stime + " 00:00:00")
                                                                                  && p.senddate <= Convert.ToDateTime(etime + " 23:59:59")
                                                                                  && (p.replaycenters == "3" || p.replaycenters == "不满意")
                                                                                    && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                    }
                    else
                    {
                        //科室随访总数
                        sfallcount = _IHzsfMassagesRepository.Count(p => p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                        //科室随访满意数
                        mycount = _IHzsfMassagesRepository.Count(p => (p.replaycenters == "1" || p.replaycenters == "满意" || p.sendmyeds == "满意")
                                                                 && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                        //科室随访表扬数
                        bycount = _IHzsfMassagesRepository.Count(p => (p.replaycenters == "2" || p.replaycenters == "表扬" || p.sendmyeds == "表扬")
                                                                 && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                        //科室随访不满意数
                        nomycount = _IHzsfMassagesRepository.Count(p => p.sendmyeds != "满意"
                                                                          && (p.replaycenters == "3" || p.replaycenters == "不满意")
                                                                          && (p.sendmyeds != "满意" || p.sendmyeds != "表扬" || p.replaycenters != "满意" || p.replaycenters != "表扬")
                                                                          && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                        ///获取已回复数
                        yhfcount = _IHzsfMassagesRepository.Count(p => p.CY_DEPT_NAME == item.ToString()
                                                                             && p.replaycenters != "").Result.ToString();
                        //获取未回复数
                        whfcount = _IHzsfMassagesRepository.Count(p => p.CY_DEPT_NAME == item.ToString()
                                                                             && p.replaycenters == "").Result.ToString();
                        //回复前满意数
                        hfqmycount = _IHzsfMassagesRepository.Count(p => (p.replaycenters == "1" || p.replaycenters == "满意")
                                                                                 && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                        //回复前表扬数
                        hfqbycount = _IHzsfMassagesRepository.Count(p => (p.replaycenters == "2" || p.replaycenters == "表扬")
                                                                                  && p.CY_DEPT_NAME == item.ToString()).Result.ToString();
                        hfqnomycount = _IHzsfMassagesRepository.Count(p => (p.replaycenters == "3" || p.replaycenters == "不满意")
                                                                                   && p.CY_DEPT_NAME == item.ToString()).Result.ToString();

                    }
                    //科室随访其他数量和综合满意度
                    if (Convert.ToInt32(sfallcount) > 0)
                    {
                        //科室随访其他数量
                        //othercount = (Convert.ToInt32(sfallcount) - Convert.ToInt32(hfqmycount) - Convert.ToInt32(hfqbycount) - Convert.ToInt32(hfqnomycount)- Convert.ToInt32(whfcount)).ToString();
                        othercount = (Convert.ToInt32(sfallcount) - Convert.ToInt32(mycount) - Convert.ToInt32(bycount) - Convert.ToInt32(nomycount) - Convert.ToInt32(whfcount)).ToString();

                    }
                    mycount = (Convert.ToInt32(mycount) + Convert.ToInt32(whfcount)).ToString();

                    if (Convert.ToInt32(sfallcount) > 0)
                    {
                        //满意率
                        mycountbl = (Convert.ToDouble(mycount) / Convert.ToDouble(sfallcount)).ToString("0.00%");
                        //表扬率
                        bycountbl = (Convert.ToDouble(bycount) / Convert.ToDouble(sfallcount)).ToString("0.00%");
                        //不满意率
                        nomycountbl = (Convert.ToDouble(nomycount) / Convert.ToDouble(sfallcount)).ToString("0.00%");
                        //回复满意率
                        hfmydbl = ((Convert.ToDouble(hfqmycount) + Convert.ToDouble(hfqbycount) + Convert.ToInt32(whfcount)) / (Convert.ToDouble(sfallcount) - Convert.ToDouble(othercount))).ToString("0.00%");
                        //综合满意度
                        double percent = (Convert.ToDouble(mycount) + Convert.ToDouble(bycount)) / (Convert.ToDouble(sfallcount) - Convert.ToDouble(othercount));
                        zhmydbfb = percent.ToString("0.00%");
                    }
                    else
                    {
                        //满意率
                        mycountbl = "0.00%";
                        //表扬率
                        bycountbl = "0.00%";
                        //不满意率
                        nomycountbl = "0.00%";
                        //回复满意率
                        hfmydbl = "0.00%";
                        zhmydbfb = "0.00%";
                    }

                    hzallcounts += hzallcuont;
                    #region 赋值
                    hzsfmassagemodel.hzallcount = hzallcuont;
                    hzsfmassagemodel.sfallcount = sfallcount;
                    hzsfmassagemodel.yhfcount = yhfcount;
                    hzsfmassagemodel.whfcount = whfcount;
                    hzsfmassagemodel.mycount = mycount;
                    hzsfmassagemodel.mycountbl = mycountbl;
                    hzsfmassagemodel.bycount = bycount;
                    hzsfmassagemodel.bycountbl = bycountbl;
                    hzsfmassagemodel.nomycount = nomycount;
                    hzsfmassagemodel.nomycountbl = nomycountbl;
                    hzsfmassagemodel.othercount = othercount;
                    hzsfmassagemodel.hfmydbl = hfmydbl;
                    hzsfmassagemodel.zhmydbfb = zhmydbfb;
                    hzssmassagebblist.Add(hzsfmassagemodel);
                    #endregion

                    #region 汇总信息
                    if (sfallcounts == "")
                    {

                        sfallcounts = sfallcount;//所有科室总随访书
                        yhfcounts = yhfcount;//已回复
                        whfcounts = whfcount;//未回复
                        mycounts = mycount;//所有科室总满意数
                        bycounts = bycount;//所有科室总表扬数
                        nomycounts = nomycount;//所有科室总不满意数
                        othercounts = othercount;//所有科室总其他数
                        hfqmycounts = hfqmycount;//回复前满意数
                        hfqbycounts = hfqbycount;//回复后满意数
                    }
                    else
                    {
                        sfallcounts = (Convert.ToInt32(sfallcounts) + Convert.ToInt32(sfallcount)).ToString();//所有科室总随访书
                        yhfcounts = (Convert.ToInt32(yhfcounts) + Convert.ToInt32(yhfcount)).ToString();//所有科室已回复数
                        whfcounts = (Convert.ToInt32(whfcounts) + Convert.ToInt32(whfcount)).ToString();//所有科室未回复数
                        mycounts = (Convert.ToInt32(mycounts) + Convert.ToInt32(mycount)).ToString();//所有科室总满意数
                        bycounts = (Convert.ToInt32(bycounts) + Convert.ToInt32(bycount)).ToString();//所有科室总表扬数
                        nomycounts = (Convert.ToInt32(nomycounts) + Convert.ToInt32(nomycount)).ToString();//所有科室总不满意数
                        othercounts = (Convert.ToInt32(othercounts) + Convert.ToInt32(othercount)).ToString();//所有科室总其他数
                        hfqmycounts = (Convert.ToInt32(hfqmycounts) + Convert.ToInt32(hfqmycount)).ToString();//回复前满意数
                        hfqbycounts = (Convert.ToInt32(hfqbycounts) + Convert.ToInt32(hfqbycount)).ToString();//回复后满意数

                    }
                    #endregion
                }
                #region 总数赋值
                //if (Convert.ToInt32(yhfcounts) > 0)
                //{
                //    //满意率
                //    mycountbls = (Convert.ToDouble(mycounts) / Convert.ToDouble(yhfcounts)).ToString("0.00%");
                //    //表扬率
                //    bycountbls = (Convert.ToDouble(bycounts) / Convert.ToDouble(yhfcounts)).ToString("0.00%");
                //    //不满意率
                //    nomycountbls = (Convert.ToDouble(nomycounts) / Convert.ToDouble(yhfcounts)).ToString("0.00%");

                //    //回复满意率
                //    hfmydbls = ((Convert.ToDouble(hfqmycounts) + Convert.ToDouble(hfqbycounts)) / Convert.ToDouble(yhfcounts)).ToString("0.00%");
                //    //综合满意度
                //    double percent = (Convert.ToDouble(mycounts) + Convert.ToDouble(bycounts)) / Convert.ToDouble(yhfcounts);
                //    zhmydbfbs = percent.ToString("0.00%");
                //}
                if (Convert.ToInt32(sfallcounts) > 0)
                {
                    //满意率
                    mycountbls = (Convert.ToDouble(mycounts) / Convert.ToDouble(sfallcounts)).ToString("0.00%");
                    //表扬率
                    bycountbls = (Convert.ToDouble(bycounts) / Convert.ToDouble(sfallcounts)).ToString("0.00%");
                    //不满意率
                    nomycountbls = (Convert.ToDouble(nomycounts) / Convert.ToDouble(sfallcounts)).ToString("0.00%");
                    //回复满意率
                    hfmydbls = ((Convert.ToDouble(hfqmycounts) + Convert.ToDouble(hfqbycounts) + Convert.ToInt32(whfcounts)) / (Convert.ToDouble(sfallcounts) - Convert.ToDouble(othercounts))).ToString("0.00%");
                    //综合满意度
                    double percent = (Convert.ToDouble(mycounts) + Convert.ToDouble(bycounts)) / (Convert.ToDouble(sfallcounts) - Convert.ToDouble(othercounts));
                    zhmydbfbs = percent.ToString("0.00%");
                }
                //定义对象给集合数据赋值
                Model.Hzsfmassagebblist hzsfmassagemodel1 = new Model.Hzsfmassagebblist();
                hzsfmassagemodel1.deptname = "合计";
                hzsfmassagemodel1.hzallcount = hzallcounts;
                hzsfmassagemodel1.sfallcount = sfallcounts;
                hzsfmassagemodel1.yhfcount = yhfcounts;
                hzsfmassagemodel1.whfcount = whfcounts;
                hzsfmassagemodel1.mycount = mycounts;
                hzsfmassagemodel1.mycountbl = mycountbls;
                hzsfmassagemodel1.bycount = bycounts;
                hzsfmassagemodel1.bycountbl = bycountbls;
                hzsfmassagemodel1.nomycount = nomycounts;
                hzsfmassagemodel1.nomycountbl = nomycountbls;
                hzsfmassagemodel1.othercount = othercounts;
                hzsfmassagemodel1.hfmydbl = hfmydbls;
                hzsfmassagemodel1.zhmydbfb = zhmydbfbs;
                hzssmassagebblist.Add(hzsfmassagemodel1);
                #endregion
                #endregion

                NPOIHelper npoi = new NPOIHelper();
                var tb = ModelConvertHelper<Model.Hzsfmassagebblist>.ConvertListToDataTable(hzssmassagebblist);
                if (tb != null)
                {
                    //导出dtnew 
                    string[] cols = { "科室","患者出院数","随访总数","已回复","未回复","满意","满意度","表扬","表扬度","不满意","不满意度","其他","回复满意度","综合满意度"};

                    byte[] sm = npoi.ExportToExcel1(tb, cols);
                    if (sm != null)
                    {
                        return File(sm, "application/vnd.ms-excel", "随访统计表.xlsx");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
                }
                return Error("导出失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出异常");
                return Error("导出失败");
            }
        }


        /// <summary>
        /// 根据id获取详情信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getsendhfinfos")]
        public async Task<IActionResult> GetSendhfinfos(string id)
        {
            var model = await _IHzsfMassagesRepository.Get(p => p.id == id);
            return Success("成功", model);
        }
        /// <summary>
        /// 修改发送记录信息满意度
        /// </summary>
        /// <param name="tps"></param>
        /// <returns></returns>
        [HttpGet("upSendhfinfo")]
        public async Task<IActionResult> upSendhfinfo(Model.Dto.HzsfMassages tps)
        {
            HzsfMassages tp = await _IHzsfMassagesRepository.GetSingle(p => p.id == tps.id);
            //tp.sendcenters      =tps.sendcenters;// 发送内容
            //tp.replaycenters    =tps.replaycenters;// 回复内容
            tp.sendmyeds = tps.sendmyeds; // 满意度
                                          //tp.senddate         =tps.senddate;// 发送时间
                                          //tp.ZY_NO            =tps.ZY_NO;  // --住院号
                                          //tp.NAME             =tps.NAME;  // --病人姓名
                                          //tp.SEX              =tps.SEX;    // --病人性别
                                          //tp.ZY_AGE = tps.ZY_AGE;    // --住院年龄
                                          //tp.PAT_PHONE        =tps.PAT_PHONE;         // --本人联系电话
                                          //tp.JB_NAME          =tps.JB_NAME;    // --疾病描述（名称）
                                          //tp.CY_ZD            =tps.CY_ZD;       //   --出院诊断
                                          //tp.IS_OP = tps.IS_OP;  // --是否手术
                                          //tp.DIA_NAME         =tps.DIA_NAME;        // --诊断方式
                                          //tp.NURSE_IN_CHARGE  =tps.NURSE_IN_CHARGE;     // --责任护士
                                          //tp.CY_DEPT_NAME     =tps.CY_DEPT_NAME;    // --出院科室名称
                                          //tp.RY_DATE          =tps.RY_DATE; // --入院日期
                                          //tp.CY_DATE          =tps.CY_DATE;  // --出院日期
                                          //tp.ZY_TIMES = tps.ZY_TIMES; // --住院次数
                                          //tp.DIRECTOR         =tps.DIRECTOR;    // 科主任
                                          //tp.ZZ_DOC           =tps.ZZ_DOC;    // 主治医师
                                          //tp.JZ_DOC           =tps.JZ_DOC; // 经治医师
                                          //tp.ZY_DAYS          =tps.ZY_DAYS;    // 住院天数
                                          //tp.ZY_DEPT_NAME     =tps.ZY_DEPT_NAME;  // 住院科室名称
                                          //tp.JOB              =tps.JOB;           // 职业
                                          //tp.OUT_OR_IN        =tps.OUT_OR_IN;   // 住院或出院
                                          //tp.isdelete = tps.isdelete;  //是否删除
            var resua = _IHzsfMassagesRepository.UpdateOne(tp);
            if (resua.Result)
            {
                return Success("成功");
            }
            else
            {
                return Error("失败");
            }

        }
        /// <summary>
        /// 修改不满意原因
        /// </summary>
        /// <param name="tps"></param>
        /// <returns></returns>
        [HttpGet("upbecausehfinfo")]
        public async Task<IActionResult> upbecausehfinfo(Model.Dto.HzsfMassages tps)
        {
            HzsfMassages tp = await _IHzsfMassagesRepository.GetSingle(p => p.id == tps.id);

            tp.nomybecause = tps.nomybecause; // 不满意原因

            var resua = _IHzsfMassagesRepository.UpdateOne(tp);
            if (resua.Result)
            {
                return Success("成功");
            }
            else
            {
                return Error("失败");
            }

        }

        /// <summary>
        /// 添加给出院患者发送短信记录
        /// </summary>
        /// <param name="tps"></param>
        /// <returns></returns>
        [HttpGet("addfxqytabs")]
        public async Task<IActionResult> AddFxqytabs(string ids, string nowdatetime)
        {
            //if (nowdatetime != null)
            //{
            //    nowdatetime = Convert.ToDateTime(nowdatetime).AddDays(-3).ToString("yyyy-MM-dd");
            //}
            //else
            //{
            //    nowdatetime = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd");
            //}
            string[] arrStr = ids.Split(',');
            foreach (var item in arrStr)
            {
                var massageinfo = await _IHzsfMassagesRepository.GetSingle(p => p.CY_DATE == nowdatetime && p.PAT_PHONE == item);
                if (massageinfo != null)
                {
                    continue;
                }
                var modelinfo = await _Iv_csm_zhuyuanRepository.GetSingle(p => p.CY_DATE == nowdatetime && p.PAT_PHONE == item);
                if (modelinfo != null)
                {
                    //发送成功一条就添加一条记录var a = _IHzsfMassagesRepository.AddRetID(tp);
                    //发送手机号
                    var sendtel = item;
                    //发送内容
                    var sendcenter = _configuration["sendcent:centers"].ToString();
                    string resultstrs = sendcyinfo(sendtel, sendcenter);
                    if (Convert.ToInt32(resultstrs) > 0)
                    {
                        //定义发送记录实例
                        #region 添加发送记录信息
                        HzsfMassages tp = new HzsfMassages();
                        tp.sendcenters = sendcenter;// 发送内容
                        tp.replaycenters = "";// 回复内容
                        tp.nomybecause = "";//不满意原因
                        tp.sendmyeds = ""; // 满意度
                        tp.senddate = DateTime.Now;// 发送时间
                        tp.ZY_NO = modelinfo.ZY_NO;  // --住院号
                        tp.NAME = modelinfo.NAME;  // --病人姓名
                        tp.SEX = modelinfo.SEX;    // --病人性别
                        tp.ZY_AGE = modelinfo.ZY_AGE;    // --住院年龄
                        tp.PAT_PHONE = modelinfo.PAT_PHONE;         // --本人联系电话
                        tp.JB_NAME = modelinfo.JB_NAME;    // --疾病描述（名称）
                        tp.CY_ZD = modelinfo.CY_ZD;       //   --出院诊断
                        tp.IS_OP = modelinfo.IS_OP;  // --是否手术
                        tp.DIA_NAME = modelinfo.DIA_NAME;        // --诊断方式
                        tp.NURSE_IN_CHARGE = modelinfo.NURSE_IN_CHARGE;     // --责任护士
                        tp.CY_DEPT_NAME = modelinfo.CY_DEPT_NAME;    // --出院科室名称
                        tp.RY_DATE = modelinfo.RY_DATE; // --入院日期
                        tp.CY_DATE = modelinfo.CY_DATE;  // --出院日期
                        tp.ZY_TIMES = modelinfo.ZY_TIMES; // --住院次数
                        tp.DIRECTOR = modelinfo.DIRECTOR;    // 科主任
                        tp.ZZ_DOC = modelinfo.ZZ_DOC;    // 主治医师
                        tp.JZ_DOC = modelinfo.JZ_DOC; // 经治医师
                        tp.ZY_DAYS = modelinfo.ZY_DAYS;    // 住院天数
                        tp.ZY_DEPT_NAME = modelinfo.ZY_DEPT_NAME;  // 住院科室名称
                        tp.JOB = modelinfo.JOB;           // 职业
                        tp.OUT_OR_IN = modelinfo.OUT_OR_IN;   // 住院或出院
                        tp.statesissuccess = "成功";
                        tp.isdelete = 0;  //是否删除
                        var a = _IHzsfMassagesRepository.AddRetID(tp);
                        #endregion

                    }
                    else if (Convert.ToInt32(resultstrs) == -5)
                    {
                        return Error("余额不足，请充值");
                    }
                    else if (Convert.ToInt32(resultstrs) == -6)
                    {
                        return Error("定时发送时间不是有效的时间格式");
                    }
                    else if (Convert.ToInt32(resultstrs) == -7)
                    {
                        return Error("提交信息末尾未签名，请添加中文的企业签名【 】");
                    }
                    else if (Convert.ToInt32(resultstrs) == -8)
                    {
                        return Error("发送内容需在1到300字之间");
                    }
                    else if (Convert.ToInt32(resultstrs) == -9)
                    {
                        return Error("发送号码为空");
                    }
                    else if (Convert.ToInt32(resultstrs) == -10)
                    {
                        return Error("定时时间不能小于系统当前时间");
                    }
                    else if (Convert.ToInt32(resultstrs) == -100)
                    {
                        return Error("IP黑名单");
                    }
                    else if (Convert.ToInt32(resultstrs) == -102)
                    {
                        return Error("账号黑名单");
                    }
                    else if (Convert.ToInt32(resultstrs) == -103)
                    {
                        return Error("IP未导白");
                    }
                    else
                    {
                        return Error("调用接口失败");
                    }
                }

            }

            #region 不用的备份
            /////根据住院号获取住院患者信息
            //List<IConditionalModel> conModels = new List<IConditionalModel>();

            //conModels.Add(new ConditionalModel() { FieldName = "CY_DATE", ConditionalType = ConditionalType.Equal, FieldValue = nowdatetime });
            //conModels.Add(new ConditionalModel() { FieldName = "zy_no", ConditionalType = ConditionalType.In, FieldValue = ids });
            //var list = _Iv_csm_zhuyuanRepository.GetListALL(conModels, "zy_no desc");
            //if (list.Result != null)
            //{
            //    foreach (var item in list.Result)
            //    {
            //        //发送成功一条就添加一条记录var a = _IHzsfMassagesRepository.AddRetID(tp);
            //        //发送手机号
            //        var sendtel = item.PAT_PHONE;
            //        //发送内容
            //        var sendcenter = _configuration["sendcent:centers"].ToString();
            //        string resultstrs = sendcyinfo(sendtel, sendcenter);
            //        if (Convert.ToInt32(resultstrs) > 0)
            //        {
            //            //定义发送记录实例
            //            #region 添加发送记录信息
            //            HzsfMassages tp = new HzsfMassages();
            //            tp.sendcenters = sendcenter;// 发送内容
            //            tp.replaycenters = "";// 回复内容
            //            tp.sendmyeds = ""; // 满意度
            //            tp.senddate = DateTime.Now;// 发送时间
            //            tp.ZY_NO = item.ZY_NO;  // --住院号
            //            tp.NAME = item.NAME;  // --病人姓名
            //            tp.SEX = item.SEX;    // --病人性别
            //            tp.ZY_AGE = item.ZY_AGE;    // --住院年龄
            //            tp.PAT_PHONE = item.PAT_PHONE;         // --本人联系电话
            //            tp.JB_NAME = item.JB_NAME;    // --疾病描述（名称）
            //            tp.CY_ZD = item.CY_ZD;       //   --出院诊断
            //            tp.IS_OP = item.IS_OP;  // --是否手术
            //            tp.DIA_NAME = item.DIA_NAME;        // --诊断方式
            //            tp.NURSE_IN_CHARGE = item.NURSE_IN_CHARGE;     // --责任护士
            //            tp.CY_DEPT_NAME = item.CY_DEPT_NAME;    // --出院科室名称
            //            tp.RY_DATE = item.RY_DATE; // --入院日期
            //            tp.CY_DATE = item.CY_DATE;  // --出院日期
            //            tp.ZY_TIMES = item.ZY_TIMES; // --住院次数
            //            tp.DIRECTOR = item.DIRECTOR;    // 科主任
            //            tp.ZZ_DOC = item.ZZ_DOC;    // 主治医师
            //            tp.JZ_DOC = item.JZ_DOC; // 经治医师
            //            tp.ZY_DAYS = item.ZY_DAYS;    // 住院天数
            //            tp.ZY_DEPT_NAME = item.ZY_DEPT_NAME;  // 住院科室名称
            //            tp.JOB = item.JOB;           // 职业
            //            tp.OUT_OR_IN = item.OUT_OR_IN;   // 住院或出院
            //            tp.statesissuccess = "成功";
            //            tp.isdelete = 0;  //是否删除
            //            var a = _IHzsfMassagesRepository.AddRetID(tp);
            //            #endregion

            //        }
            //        else if (Convert.ToInt32(resultstrs) == -5)
            //        {
            //            return Error("余额不足，请充值");
            //        }
            //        else if (Convert.ToInt32(resultstrs) == -6)
            //        {
            //            return Error("定时发送时间不是有效的时间格式");
            //        }
            //        else if (Convert.ToInt32(resultstrs) == -7)
            //        {
            //            return Error("提交信息末尾未签名，请添加中文的企业签名【 】");
            //        }
            //        else if (Convert.ToInt32(resultstrs) == -8)
            //        {
            //            return Error("发送内容需在1到300字之间");
            //        }
            //        else if (Convert.ToInt32(resultstrs) == -9)
            //        {
            //            return Error("发送号码为空");
            //        }
            //        else if (Convert.ToInt32(resultstrs) == -10)
            //        {
            //            return Error("定时时间不能小于系统当前时间");
            //        }
            //        else if (Convert.ToInt32(resultstrs) == -100)
            //        {
            //            return Error("IP黑名单");
            //        }
            //        else if (Convert.ToInt32(resultstrs) == -102)
            //        {
            //            return Error("账号黑名单");
            //        }
            //        else if (Convert.ToInt32(resultstrs) == -103)
            //        {
            //            return Error("IP未导白");
            //        }
            //        else
            //        {
            //            return Error("调用接口失败");
            //        }

            //    }

            //}
            //else
            //{
            //    return Error("没有转患者数据");
            //} 
            #endregion
            return Success("成功");

        }

        /// <summary>
        /// 获取发送短信记录更改回复内容
        /// </summary>
        /// <returns></returns>
        [HttpGet("getmassagereply")]
        public async Task<IActionResult> Getmassagereply()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            //调用接受短信接口 接受成功就填写数据
            var ifsend = true;

            //string replycent = GetFunction("https://sdk2.028lk.com/sdk2/BatchSend2.aspx?CorpID=DYRMYY011170&Pwd=xxk@80188");//
            //var replycent1 = DoGet("https://sdk2.028lk.com/sdk2/BatchSend2.aspx?CorpID=DYRMYY011170&Pwd=xxk@80188");

            string url = "https://sdk2.028lk.com/sdk2/Get.aspx?CorpID=DYRMYY011170&Pwd=xxk@80188";

            Encoding encoding = Encoding.GetEncoding("UTF-8");//UTF-8 

            // var replycent = GetHttpPost(url, "gb2312");


            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("CorpID", "DYRMYY011170");
            parameters.Add("Pwd", "xxk@80188");
            HttpWebResponse response = PostHttps(url, parameters, encoding);
            //打印返回值
            Stream stream = response.GetResponseStream();   //获取响应的字符串流
            StreamReader sr = new StreamReader(stream); //创建一个stream读取流

            //返回的信息
            string html = sr.ReadToEnd();
            //string html = "||19939971368#1#2020-11-17 10:33:24#||17801222151#1#2020-11-17 10:33:38#";
            var telcode = "";
            var replayscent = "";
            ///获取到接受短信的信息修改发送表信息中的回复内容
            if (html != "")
            {
                string[] arrstr1 = html.Split('|');
                {
                    foreach (var item in arrstr1)
                    {
                        if (item == "")
                        {
                            continue;
                        }
                        string[] arrStr = item.Split('#');
                        if (arrStr.Length > 1)
                        {
                            var aastr1 = arrStr[0].ToString();
                            telcode = arrStr[0].ToString();
                            //回复内容
                            replayscent = arrStr[1].ToString();
                        }
                        ///根据获取到的手机号查找发送信息表中的发送信息修改回复内容
                        HzsfMassages testuserlist = await _IHzsfMassagesRepository.GetSingle(p => p.PAT_PHONE == telcode);//
                        if (testuserlist != null)
                        {
                            //MassageInfo tp = new MassageInfo();
                            if (arrStr.Length > 1)
                            {
                                testuserlist.replaycenters = replayscent;
                            }

                            else
                            {
                                testuserlist.replaycenters = "";
                            }
                            var a = _IHzsfMassagesRepository.UpdateOne(testuserlist);
                        }
                    }
                    return Success("成功");

                }
            }
            else
            {
                //return Error("没有上行信息");
                return Success("成功");
            }
        }


        public string sendcyinfo(string telcode, string sendcenter)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            ////调用发送短信接口 发送成功就填写数据
            ////先转换成 GBK 编码数据
            //发送内容
            var str = sendcenter;// "您好 ！感谢您对我们医院的新人月支持请对我们的服质量给予评价1 满意；2不满意；3 表扬，回复数字即可。谢谢！顺祝生活愉快【郑州市第一人民医院】";//您好 ！感谢您对我们医院的新人月支持请对我们的服质量给予评价1 满意；2不满意；3 表扬，回复数字即可。谢谢！顺祝生活愉快  
            //发送给哪个手机号
            var Mobile = telcode;
            //定时发送还是立即发送
            var SendTime = "";
            string result1 = HttpUtility.UrlEncode(str, Encoding.GetEncoding("GB2312"));
            var ifsend = false;
            var aaa = " ";
            string url = "https://sdk2.028lk.com/sdk2/BatchSend2.aspx?CorpID=DYRMYY011170&Pwd=xxk@80188&Mobile=" + Mobile + "&Content=" + result1 + "&Cell=&SendTime=";

            //?CorpID=DYRMYY011170&Pwd=xxk@80188&Mobile=13935966971&Content="+ result1 + "&Cell=&SendTime= CQJS002679 zm0513@

            //Encoding encoding = Encoding.GetEncoding("GB2312");
            //Encoding encoding = Encoding.GetEncoding("UTF-8");
            Encoding encoding = Encoding.GetEncoding("GBK");
            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("CorpID", "DYRMYY011170");
            parameters.Add("Pwd", "xxk@80188");
            parameters.Add("Mobile", Mobile);
            parameters.Add("Content", result1);
            parameters.Add("Cell", "");
            parameters.Add("SendTime", SendTime.ToString());
            HttpWebResponse response = PostHttps(url, parameters, encoding);
            //打印返回值
            Stream stream = response.GetResponseStream();   //获取响应的字符串流
            StreamReader sr = new StreamReader(stream); //创建一个stream读取流

            //返回的信息
            string html = sr.ReadToEnd();
            return html;
        }
        private static readonly string DefaultUserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36";

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受   
        }
        public static HttpWebResponse PostHttps(string url, IDictionary<string, string> parameters, Encoding charset)
        {
            HttpWebRequest request = null;
            CookieContainer cookie = new CookieContainer();
            //HTTPSQ请求
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = cookie;
            request.ProtocolVersion = HttpVersion.Version11;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = DefaultUserAgent;
            request.KeepAlive = true;
            request.Headers["Accept-Language"] = "zh-CN,zh;q=0.9";
            //request.Headers["Cookie"] = "username=aaaaaa; Language=zh_CN";
            //如果需要POST数据   
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        if (key == "Content")
                        {
                            buffer.AppendFormat("&{0}={1}", key, HttpUtility.UrlEncode(parameters[key], Encoding.GetEncoding("GB2312"))); //UTF-8 
                        }
                        else
                        {
                            buffer.AppendFormat("&{0}={1}", key, WebUtility.UrlEncode(parameters[key])); //Encoding.GetEncoding("GBK").GetBytes(parameters[key])
                        }

                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, WebUtility.UrlEncode(parameters[key]));//
                    }
                    i++;
                }
                byte[] data = charset.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }

            return (HttpWebResponse)request.GetResponse();
        }
        #endregion
       
    }
}
