using System;
using System.Collections.Generic;
using System.Common;
using System.IRepositories;
using System.Linq;
using System.Model;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace TVShoppingCallCenter_ZLJ.Controllers.InternalMessages
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class InternalMessagesController : BaseController
    {
        private readonly ISMS_InternalMessagesReposytory _sys_internalMessagesrepository;
        private readonly ISys_UserAccountRepository _sys_useraccountRepository;

        public InternalMessagesController(ISMS_InternalMessagesReposytory sys_internalMessagesrepository, ISys_UserAccountRepository sys_useraccountRepository)
        {
            _sys_useraccountRepository = sys_useraccountRepository;
            _sys_internalMessagesrepository = sys_internalMessagesrepository;
        }
        /// <summary>
        /// 添加信息
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="receiveUserCode"></param>
        /// <param name="sendUserCode"></param>
        /// <returns></returns>
        public bool AddInternalMessagesInfo(int id,string title, string content, string sendUserCode, DateTime time, int smstype = 0, int smstop = 0,  int deptid=0,  string receiveUserCode="",int receivingType=0)
        {
            if (!string.IsNullOrEmpty (title) && !string.IsNullOrEmpty(content) && !string.IsNullOrEmpty(sendUserCode))
            {
              if (deptid==0&& receiveUserCode=="")
                    return false;

                T_SMS_InternalMessages model = new  T_SMS_InternalMessages();
                model.F_ID = id;
                model.SMS_Title = title;
                model.SMS_Content = content;
                model.SMS_ReceiveUserCode = receiveUserCode;
                model.SMS_SendUserCode = sendUserCode;
                model.SMS_IsRead = 0;
                model.SMS_SendTime = DateTime.Now;
                model.SMS_Remindertime = time;
                model.SMS_Deptid = deptid;
                model.SMS_IsDelete = 0;
                model.SMS_Order = 0;
                model.SMS_IsTop = smstop;
                model.SMS_Type = smstype;
                model.SMS_ReceivingType = receivingType;
                var res =  _sys_internalMessagesrepository.Add(model);
                if (res .Result > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 获取信息详情
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetailsAsync(int id)
        {
            if (id <= 0)
                return Error("参数错误");

            var model = await _sys_internalMessagesrepository.GetSingle(x => x.SMS_Id  == id);
            if (model == null)
            {
                return Error("获取失败");
            }
            return Success("获取成功！", model);
        }
        /// <summary>
        /// 获取信息列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getMsg")]
        public async Task<IActionResult> GetListMark(int istop=-1,int smstype=-1,int isread=-1, int pageindex = 0, int pagesize = 0)
        {
            //string user = "8000";
            string user = UserLogin.UserCode;
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "SMS_IsDelete", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumUserCountState.Enabled).ToString() });
            if (smstype > -1)
            {
                conModels.Add(new ConditionalModel() { FieldName = "SMS_Type", ConditionalType = ConditionalType.Equal, FieldValue = smstype.ToString() });
            }
            if (isread > -1)
            {
                conModels.Add(new ConditionalModel() { FieldName = "SMS_IsRead", ConditionalType = ConditionalType.Equal , FieldValue = isread.ToString() });
            }
            var dept = _sys_useraccountRepository.GetSingle(x => x.F_UserCode == user&&x.F_DeleteFlag ==0).Result != null ? _sys_useraccountRepository.GetSingle(x => x.F_UserCode == user && x.F_DeleteFlag == 0).Result.F_DeptId : 0;
            if (dept>0)
            {
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>(WhereType.And, new ConditionalModel() { FieldName = "SMS_ReceiveUserCode", ConditionalType = ConditionalType.Equal , FieldValue = user }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "SMS_Deptid", ConditionalType = ConditionalType.Equal , FieldValue = dept.ToString () }),
                    }
                });
            }
            else
            {
                conModels.Add(new ConditionalModel() { FieldName = "SMS_ReceiveUserCode", ConditionalType = ConditionalType.Equal, FieldValue = user });
            }
            conModels.Add(new ConditionalModel() { FieldName = "SMS_Remindertime", ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = DateTime .Now .ToString () });
            if (istop >-1)
            {
                conModels.Add(new ConditionalModel() { FieldName = "SMS_IsTop", ConditionalType = ConditionalType.Equal , FieldValue = istop.ToString () });
            }
            #endregion
            int recordCount = 0;
            if (pageindex > 0 && pagesize > 0)
            {
                var list = await _sys_internalMessagesrepository.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount }, "  SMS_Remindertime  desc") ;
                var row = list!=null ? list.Rows.Where(x => (x.SMS_ReceivingType == 0 && x.SMS_Deptid == dept) || (x.SMS_ReceivingType == 1 && x.SMS_ReceiveUserCode == user)):null ;
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = row,
                    total = list.Totals,
                };
                return Content(obj.ToJson());
            }
            else
            {
                var list = await _sys_internalMessagesrepository.GetListALL(conModels, " SMS_Remindertime  desc");
                var row = list!=null ? list.Where(x => (x.SMS_ReceivingType == 0 && x.SMS_Deptid == dept) || (x.SMS_ReceivingType == 1 && x.SMS_ReceiveUserCode == user)):null ;
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = row,
                    total = list.Count(),
                };
                return Content(obj.ToJson());
            }
        }
        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> Remove(int[] ids)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var model = await _sys_internalMessagesrepository.GetSingle(x => x.SMS_Id  == item);
                    model.SMS_IsDelete  = (int)EnumUserCountState.Delete;
                    model.SMS_DeleteTime  = DateTime.Now.ToLocalTime();
                    if (_sys_internalMessagesrepository.Update(model).Result)
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }
        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("updateState")]
        public async Task<IActionResult> UpdateState(int[] ids, int state = 0)
        {
            string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            if (string .IsNullOrEmpty (user))
                return Error("权限不足");
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var model = await _sys_internalMessagesrepository.GetSingle(x => x.SMS_Id  == item);
                    model.SMS_IsRead = state;
                    model.SMS_ReadTime = DateTime .Now ;
                    if (_sys_internalMessagesrepository.Update(model).Result)
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("操作成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分操作败，请查看后重新操作");
                else
                    return Error("操作失败，请查看后重新操作");
            }
            else
                return Error("请选择要操作的记录");
        }

        
    }
}