using System;
using System.Collections.Generic;
using System.Common;
using System.Common.Helpers;
using System.IRepositories;
using System.Linq;
using System.Linq.Expressions;
using System.Model;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Atp;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

namespace TVShoppingCallCenter_ZLJ.Controllers.SMS
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class SMSController : BaseController
    {
        [HttpGet("info")]
        public string Index()
        {
            return "Hello World";
        }

        private readonly IBus_SMSTemplateRepository bus_SMSTemplateRepository;
        private readonly IBus_SMSLogRepository bus_SMSLogRepository;

       public SMSController(IBus_SMSTemplateRepository _bus_SMSTemplateRepository, IBus_SMSLogRepository _bus_SMSLogRepository)
        {
            bus_SMSTemplateRepository = _bus_SMSTemplateRepository;
            bus_SMSLogRepository = _bus_SMSLogRepository;
        }

        #region 短信模板

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("addtemplate")]
        public async Task<IActionResult> AddTemplate(SMSTemplateInput input)
        {

            #region 验证 参数


            if (string.IsNullOrEmpty(input.F_Content))
                return Error("请输入模板内容");
            if (string.IsNullOrEmpty(input.F_ModelName))
                return Error("请输入模板名称");
            if (string.IsNullOrEmpty(input.F_Tel))
                return Error("请输入要绑定400电话");


            #endregion

            if (await bus_SMSTemplateRepository.GetCount(a => a.F_ModelName == input.F_ModelName) > 0)
            {
                return Error("模板名称不能重复");
            }
            T_Bus_SMSTemplate ModelAdd = new T_Bus_SMSTemplate();
            ModelConvertHelper<T_Bus_SMSTemplate, SMSTemplateInput>.ModeToModelDefault(ModelAdd, input);
            ModelAdd.F_AddUser = UserLogin.UserId.ObjToInt();
            ModelAdd.F_AddUserName = UserLogin.UserName;
            ModelAdd.F_AddTime = DateTime.Now;

            if (await bus_SMSTemplateRepository.Add(ModelAdd) > 0)
            {
                return Success("新增成功");
            }
            else
            {
                return Error("新增失败,请重试！");
            }
        }


        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("updatetemplate")]
        public async Task<IActionResult> UpdateTemplate(SMSTemplateInput input)
        {

            #region 验证 参数


            if (string.IsNullOrEmpty(input.F_Content))
                return Error("请输入模板内容");
            if (string.IsNullOrEmpty(input.F_ModelName))
                return Error("请输入模板名称");
            if (string.IsNullOrEmpty(input.F_Tel))
                return Error("请输入要绑定400电话");
            if (input.F_Id<1)
                return Error("参数缺失");

            #endregion

            if (await bus_SMSTemplateRepository.GetCount(q => q.F_ModelName == input.F_ModelName&&q.F_Id!= input.F_Id) > 0)
            {
                return Error("模板名称不能重复");
            }
            input.F_AddTime = DateTime.Now;
            T_Bus_SMSTemplate ModelAdd = await bus_SMSTemplateRepository.GetSingle(q=>q.F_Id==input.F_Id);
            ModelConvertHelper<T_Bus_SMSTemplate, SMSTemplateInput>.ModeToModelDefault(ModelAdd, input);
            ModelAdd.F_AddUser = UserLogin.UserId.ObjToInt();
            ModelAdd.F_AddUserName = UserLogin.UserName;

            if (await bus_SMSTemplateRepository.Update(ModelAdd))
            {
                return Success("保存成功");
            }

            return Error("保存失败,请重试！");
            
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids">格式   1,2,3,4</param>
        /// <returns></returns>
        [HttpPost("deletetemplate")]
        public async Task<IActionResult> DeleteTemplate(string ids)
        {
            if (string.IsNullOrEmpty(ids))
                return Error("请输入删除id");
            ids = ids.Trim(',');
            if (string.IsNullOrEmpty(ids))
                return Error("请输入删除id");
            string[] idsArry = ids.Split(',');
            if (await bus_SMSTemplateRepository.Delete(q => idsArry.Contains( q.F_Id.ToString())))
            {
                return Success("删除成功");
            }
            else
            {
                return Error("删除失败,请重试！");
            }
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("gettemplatebypage")]
        public async Task<IActionResult> GetTemplateByPage(SMSTemplateInput input)
        {

            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            if (!string.IsNullOrEmpty(input.F_ModelName))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_ModelName", ConditionalType = ConditionalType.Like, FieldValue = input.F_ModelName });
            }
            if (!string.IsNullOrEmpty(input.F_Tel))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Tel", ConditionalType = ConditionalType.Like, FieldValue = input.F_Tel });
            }
            if (input.F_Id>0)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Id", ConditionalType = ConditionalType.Equal, FieldValue = input.F_Id.ToString() });
            }

            #endregion
            RefAsync<int> count = 0;
            PageData<T_Bus_SMSTemplate> productClasselist = await bus_SMSTemplateRepository.GetListByPage(conModels, new MyPageModel() { PageIndex = input.pageindex, PageSize = input.pagesize, PageCount = count });

            return Success("成功", productClasselist);
        }


        #endregion

        #region 短信记录

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("addsmslog")]
        public async Task<IActionResult> AddSMSLog(SMSLogInput input)
        {

            #region 验证 参数


            if (string.IsNullOrEmpty(input.F_Content))
                return Error("没有内容");
            if (string.IsNullOrEmpty(input.F_Name))
                input.F_Name = DateTime.Now.ToString("yyyyMMddhhmmss");
            if (input.F_Type == 1 || input.F_Type == 2)
            { 
                if(input.F_TemplateId<1)
                return Error("请选择模板"); 

            }
            if (input.F_Type == 2 || input.F_Type == 4)
            {
                if (input.F_PlanSendTime <= DateTime.Now)
                { return Error("定时发送时间无效"); }
            } else
            {
                input.F_PlanSendTime = DateTime.Now;
            }
            if (string.IsNullOrEmpty(input.F_Tel))
                return Error("请输入手机号码");


            #endregion
            List<T_Bus_SMSLog> modelAddList = new List<T_Bus_SMSLog>();

            T_Bus_SMSLog ModelAdd = new T_Bus_SMSLog();
            ModelConvertHelper<T_Bus_SMSLog, SMSLogInput>.ModeToModelDefault(ModelAdd, input);
            ModelAdd.F_Content = input.F_Content.Replace("{phone}", input.F_Tel).Replace("{name}","");
            ModelAdd.F_AddUser = UserLogin.UserId.ObjToInt();
            ModelAdd.F_AddUserName = UserLogin.UserName;
            ModelAdd.F_AddTime = DateTime.Now;            
            ModelAdd.F_Id=Guid.NewGuid().ToString().Replace("-","");
            ModelAdd.F_Message = "";
            ModelAdd.F_State = 0;

            //ModelAdd.F_Tel = input.F_Tel;
            //ModelAdd.F_PlanSendTime = input.F_PlanSendTime;
            //ModelAdd.F_TemplateId = input.F_TemplateId;
            //ModelAdd.F_Type = input.F_Type;
            modelAddList.Add(ModelAdd);
            string retstr =await SendSMSLog(modelAddList);
            if (retstr.StartsWith("成功"))
            {
                return Success(retstr);
            }

            return Error(retstr);
            
        }


        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("updatesmslog")]
        public async Task<IActionResult> UpdateSMSLog(SMSLogInput input)
        {

            #region 验证 参数


            if (string.IsNullOrEmpty(input.F_Id))
                return Error("请输入ID");
            if (input.F_State<1)
                return Error("请输入状态");


            #endregion


            T_Bus_SMSLog ModelAdd = await bus_SMSLogRepository.GetSingle(q => q.F_Id == input.F_Id);
            ModelAdd.F_State = input.F_State;
            ModelAdd.F_AddUser = UserLogin.UserId.ObjToInt();
            ModelAdd.F_AddUserName = UserLogin.UserName;

            if (await bus_SMSLogRepository.Update(ModelAdd))
            {
                return Success("保存成功");
            }

            return Error("保存失败,请重试！");

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids">格式   1,2,3,4</param>
        /// <returns></returns>
        [HttpPost("deletesmslog")]
        public async Task<IActionResult> DeleteSMSLog(string ids)
        {
            if (string.IsNullOrEmpty(ids))
                return Error("请输入删除id");
            ids = ids.Trim(',');
            if (string.IsNullOrEmpty(ids))
                return Error("请输入删除id");
            string[] idsArry = ids.Split(',');
            if (await bus_SMSLogRepository.Delete(q => idsArry.Contains(q.F_Id.ToString())))
            {
                return Success("删除成功");
            }
            else
            {
                return Error("删除失败,请重试！");
            }
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getsmslogbypage")]
        public async Task<IActionResult> GetSMSLogByPage(SMSLogInput input)
        {

            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            if (!string.IsNullOrEmpty(input.F_Name))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Name", ConditionalType = ConditionalType.Like, FieldValue = input.F_Name });
            }
            if (!string.IsNullOrEmpty(input.F_Tel))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Tel", ConditionalType = ConditionalType.Like, FieldValue = input.F_Tel });
            }
            if (input.SearchEndTime != null)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.LessThan, FieldValue = input.SearchEndTime.GetValueOrDefault().ToString("yyyy-MM-dd 23:59:59") });
            }
            if (input.F_TemplateId >0)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_TemplateId", ConditionalType = ConditionalType.Equal, FieldValue = input.F_TemplateId.ToString() });
            }
            if (input.SearchStartTime != null)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.GreaterThan, FieldValue = input.SearchStartTime.GetValueOrDefault().ToString("yyyy-MM-dd 00:00:01") });
            }
            if (input.F_State > 0)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = input.F_State.ToString() });
            }

            #endregion
            RefAsync<int> count = 0;
            PageData<T_Bus_SMSLog> productClasselist = await bus_SMSLogRepository.GetListByPage(conModels, new MyPageModel() { PageIndex = input.pageindex, PageSize = input.pagesize, PageCount = count  }, "F_AddTime desc");

            return Success("成功", productClasselist);
        }


        #endregion


        #region 方法

        private async Task<string> SendSMSLog(List<T_Bus_SMSLog> list)
        {
            if (list != null && list.Count > 0)
            {
                int n = list.Count;
                int n1 = 0;
                int n2 = 0;
                bool bl = await bus_SMSLogRepository.AddMany(list);
                //记录短信  可暂时不发 放任务中
                if (bl)
                {
                    List<T_Bus_SMSLog> templist = new List<T_Bus_SMSLog>();
                    foreach (T_Bus_SMSLog m in list)
                    {

                        string ret = SendMessage(m.F_Tel, m.F_Content);
                        m.F_Message = ret;
                        m.F_SendTime = DateTime.Now;
                        if (ret == "success")
                        {
                            n1++;
                            m.F_State = 1;
                        }
                        else
                        {
                            n2++;
                            m.F_State = 2;
                        }
                        templist.Add(m);
                        if (templist.Count > 10)
                        {
                            if (!await bus_SMSLogRepository.UpdateListToColumns(templist, s => new { s.F_State, s.F_SendTime, s.F_Message }))
                            {
                                templist = new List<T_Bus_SMSLog>();
                                return string.Format("失败：全部/成功/失败-{0}/{1}/{2}", n, n1, n2);
                            }
                            templist = new List<T_Bus_SMSLog>();
                        }

                    }
                    if (templist.Count > 0)
                    {
                        await bus_SMSLogRepository.UpdateListToColumns(templist, s => new { s.F_State, s.F_SendTime, s.F_Message });
                    }
                    return string.Format("成功：全部/成功/失败-{0}/{1}/{2}", n, n1, n2);
                }
                else
                {
                    return "失败：短信插入失败";
                }
            }

            return "成功：" + 0;
        }


        private string SendMessage(string phone,string content)
        {
            return "success";
        }
        #endregion
    }
}