using System;
using System.Collections.Generic;
using System.Common;
using System.Common.Helpers;
using System.Data;
using System.Globalization;
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.ManagementCenter
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class TodoManagementController : BaseController
    {
        private readonly ISys_TodoManagementRepository _sys_todomanagementrepository;
        private readonly ISMS_InternalMessagesReposytory _sys_internalMessagesrepository;
        private readonly ISys_UserAccountRepository _sys_useraccountRepository;
        public TodoManagementController(ISys_TodoManagementRepository sys_todomanagementrepository, ISys_UserAccountRepository sys_useraccountRepository, ISMS_InternalMessagesReposytory sys_internalMessagesrepository)
        {
            _sys_todomanagementrepository = sys_todomanagementrepository;
            _sys_useraccountRepository = sys_useraccountRepository;
            _sys_internalMessagesrepository = sys_internalMessagesrepository;
        }
        /// <summary>
        /// 添加待办
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(T_Sys_TodoManagement input)
        {
            if (input.F_Type < 0)
                return Error("请选择待办类型");
          string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            input.F_CreateTime = DateTime.Now;
            input.F_CreateUser = user;
            input.F_IsDelete = 0;
            string title = "", count = "";
            if (input.F_Type == 0)
            {
                title = "日程提醒";
                count = input.F_Content;
            }
            else
            {
                title = "待联系人提醒";
                count = "待联系人"+ input.F_PeopleName ;
            }
                var res = await _sys_todomanagementrepository.Add(input);
            if (res > 0)
            {
                if (input .F_IsRemind >0)
                {
                    try
                    {
                        bool n = new InternalMessages.InternalMessagesController(_sys_internalMessagesrepository, _sys_useraccountRepository).AddInternalMessagesInfo(res, title, count, user, DateTime.Parse(input.F_Remindertime.ToString()), 3, 1, 0, user, 1);
                    }
                    catch
                    {

                    }
                }
               
                return Success("添加成功");
            }
            else
            {
                return Error("添加失败");
            }
        }
        /// <summary>
        /// 修改待办
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(T_Sys_TodoManagement input)
        {
            if (input.F_ID <= 0)
                return Error("参数错误");
            if (input.F_Type < 0)
                return Error("请选择待办类型");
            var model = await _sys_todomanagementrepository.GetSingle(x => x.F_ID == input.F_ID);
            if (model == null)
                return Error("操作失败");
            // string user = "8000";
            string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            input.F_IsDelete = 0;
            input.F_CreateUser = model.F_CreateUser;
            input.F_CreateTime = model.F_CreateTime;
            input.F_UpdateTime = DateTime.Now;
            input.F_UpdateUser = user;
            string title = "", count = "";
            if (input.F_Type == 0)
            {
                title = "日程提醒";
                count = input.F_Content;
            }
            else
            {
                title = "待联系人提醒";
                count = "待联系人" + input.F_PeopleName;
            }
            // model.F_UpdateUser = "8000";
            var b = await _sys_todomanagementrepository.Update(input);
            if (b)
            {
                if (input.F_IsRemind > 0)
                {
                    try
                    {
                        var InternalMessages = _sys_internalMessagesrepository.GetListALL(x => x.F_ID == model.F_ID && x.SMS_IsDelete == 0).Result.FirstOrDefault();
                        if (InternalMessages != null)
                        {
                            InternalMessages.SMS_Title = title;
                            InternalMessages.SMS_Content = count;
                            InternalMessages.SMS_Remindertime = input.F_Remindertime;
                            InternalMessages.SMS_ReceiveUserCode = user;
                            bool n = await _sys_internalMessagesrepository.Update(InternalMessages);
                        }
                        else
                        {
                            bool n = new InternalMessages.InternalMessagesController(_sys_internalMessagesrepository, _sys_useraccountRepository).AddInternalMessagesInfo(model.F_ID, title, count, user, DateTime.Parse(input.F_Remindertime.ToString()), 3, 1, 0, user, 1);
                        }

                    }
                   
                catch
                {

                }
                }
                return Success("修改成功");
            }
               
            return Error("修改失败");
        }
        /// <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_todomanagementrepository.GetSingle(x => x.F_ID == item);
                    var message = await _sys_internalMessagesrepository.GetListALL (x => x.F_ID  == item);
                    if (message!=null )
                    {
                        foreach (var it in message)
                        {
                            it .SMS_IsDelete = (int)EnumUserCountState.Delete;
                         var n=   _sys_internalMessagesrepository.Update(it);
                        }
                    }
                    model.F_IsDelete = (int)EnumUserCountState.Delete;
                    model.F_DeleteTime = DateTime.Now.ToLocalTime();
                    model.F_DeleteUser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                    if (_sys_todomanagementrepository.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="id">id</param>
        /// <returns></returns>
        [HttpPost("operation")]
        public async Task<IActionResult> GetOperationAsync(int[] ids, int state)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var model = await _sys_todomanagementrepository.GetSingle(x => x.F_ID == item);
                    model.F_State  = state;
                    if (_sys_todomanagementrepository.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="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public async Task<IActionResult> GetListMark(string keyword,int state=-1, int type = -1, int pageindex = 1, int pagesize = 20)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_IsDelete", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumUserCountState.Enabled).ToString() });
            if (!string.IsNullOrEmpty(keyword))
            {
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>(WhereType.And, new ConditionalModel() { FieldName = "F_Name", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_Content", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                         new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_PeopleName", ConditionalType = ConditionalType.Like, FieldValue = keyword })
                    }
                });
            }
            if (type > -1)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Type", ConditionalType = ConditionalType.Like, FieldValue = type.ToString() });
            }
            if (state > -1)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Like, FieldValue = state.ToString() });
            }

            #endregion
            int recordCount = 0;
            var list = await _sys_todomanagementrepository.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount }, "  F_CreateTime  desc");
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = list,
                total = list.Totals,
            };

            return Content(obj.ToJson());
        }
        /// <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_todomanagementrepository.GetSingle(x => x.F_ID == id);
            if (model == null)
            {
                return Error("获取失败");
            }
            return Success("获取成功！", model);
        }
        /// <summary>
        /// 上传文件并导入数据库
        /// </summary>
        /// <returns></returns>
        [HttpPost("importexcel")]
        public async Task<IActionResult> ImportExcel(int headrow = 0)
        {
            Microsoft.AspNetCore.Http.IFormFile _upfile = Request.Form.Files[0];
            if (!_upfile.ContentType.Equals("application/vnd.ms-excel") && !_upfile.ContentType.Equals("application/x-xls") && !_upfile.ContentType.Equals("application/x-xlsx") && !_upfile.ContentType.Equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") && !_upfile.ContentType.Equals("application/octet-stream"))
                return Error($"请正确上传Excel文件：file.ContentType={_upfile.ContentType}");
            NPOIHelper npoi = new NPOIHelper();
            var dtExcel = npoi.ExcelToTable1(_upfile, headrow);
            int num = dtExcel.Rows.Count;
            var cols = dtExcel.Columns;
            int colnum = cols.Count;
            string errmsg = string.Empty;
            if (num > 0)
            {
                int index = 1;
                foreach (DataRow dr in dtExcel.Rows)
                {
                    var model = new T_Sys_TodoManagement();
                    string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                    if (dr.Table.Columns.Contains ("分类"))
                    {
                        if (dr["分类"].ToString() == "日程")
                        {
                            model.F_Type = 0;
                            model.F_Name = dr["待办标题"].ToString();
                            model.F_Content = dr["待办内容"].ToString();
                        }
                        else
                        {
                            model.F_Type = 1;
                            model.F_PeopleName = dr["待联系人姓名"].ToString();
                            model.F_Tel = dr["待联系人电话"].ToString();
                        }
                    }
                    else
                    {
                        return Error("模板错误，请选择正确的模板");
                    }
                    if (dr.Table.Columns.Contains("任务状态"))
                    {
                        if (dr["任务状态"].ToString() == "未完成")
                            model.F_State = 0;
                        else
                            model.F_State = 1;
                    }
                    else
                    {
                        return Error("模板错误，请选择正确的模板");
                    }
                    if (dr.Table.Columns.Contains("是否提醒"))
                    {
                        if (dr["是否提醒"].ToString() == "是")
                        model.F_IsRemind = 1;
                    else
                        model.F_IsRemind = 0;
                    }
                    else
                    {
                        return Error("模板错误，请选择正确的模板");
                    }

                    if (dr.Table.Columns.Contains("待办提醒时间"))
                    {
                        if (!string.IsNullOrEmpty(dr["待办提醒时间"].ToString()))
                        {
                            try
                            {
                                model.F_Remindertime = DateTime.Parse(dr["待办提醒时间"].ToString());
                            }
                            catch
                            {
                                errmsg = errmsg + "\r\n第" + index + "行导入失败！待办提醒时间格式错误";
                                continue;
                            }
                        }
                    }
                    else
                    {
                        return Error("模板错误，请选择正确的模板");
                    }
                    model.F_CreateTime = DateTime.Now;
                    model.F_CreateUser = user;
                    model.F_IsDelete = 0;
                    int b = await _sys_todomanagementrepository.Add(model);
                    if (b <= 0)
                    {
                        if (!string.IsNullOrEmpty(errmsg))
                        {
                            errmsg = errmsg + "\r\n第" + index + "行导入失败！";
                        }
                        else
                        {
                            errmsg = "第" + index + "行导入失败！";
                        }
                    }
                    index++;

                }
            }
            else
            {
                return Error("文件中无数据");
            }

            if (!string.IsNullOrEmpty(errmsg))
            {
                return Error(errmsg);
            }

            return Success("导入成功");
        }
    }
}