using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.Log;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Request;

namespace Siger.ApiConfig.Controller
{
    public class EmailController : BaseController
    {

        private readonly ISigerProjectEmailConfig _sigerProjectEmailConfig;
        private readonly ISigerProjectEmailMachine _sigerProjectEmailMachine;
        private readonly ISigerProjectUserRepository _sigerProjectUser;
        private readonly IUnitOfWork _unitOfWork;
        public EmailController(ISigerProjectEmailConfig sigerProjectEmailConfig, ISigerProjectEmailMachine sigerProjectEmailMachine,ISigerProjectUserRepository sigerProjectUserRepository, IUnitOfWork unitOfWork)
        {
            _sigerProjectEmailConfig = sigerProjectEmailConfig;
            _sigerProjectEmailMachine = sigerProjectEmailMachine;
            _sigerProjectUser = sigerProjectUserRepository;
            _unitOfWork = unitOfWork;
        }

 
        /// <summary>
        /// 获取发件配置
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEmailCfg()
        {

            var emailCfg = _sigerProjectEmailConfig.Get(f => f.project == ProjectId && f.status == (int)RowState.Valid);
            return new ObjectResult(emailCfg);
        }


        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="emailCfg"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ModifyEmailCfg([FromBody]RequestEmailCfg emailCfg)
        {



            //每个项目配置一个 发件箱
            var Cfg = _sigerProjectEmailConfig.Get(f => f.project == ProjectId && f.status == (int)RowState.Valid);
            if (Cfg == null)
            {
                _sigerProjectEmailConfig.Insert(new SigerProjectEmailConfig
                {
                    project = ProjectId,
                    send = emailCfg.Email,
                    code = emailCfg.Code,
                    server = emailCfg.Host,
                    status = (int)RowState.Valid,
                    time = DateTime.Now
                });
            }
            else
            {
                Cfg.server = emailCfg.Host;
                Cfg.send = emailCfg.Email;
                Cfg.code = emailCfg.Code;
                Cfg.time = DateTime.Now;
                _sigerProjectEmailConfig.Update(Cfg);
            }

            var result = _unitOfWork.Commit();
            if (result > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 未绑定设备
        /// </summary>
        /// <param name="title"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetUnSettingMachine(string title)
        {
            var EmailCfgs = _sigerProjectEmailMachine.GetList(f => f.project == ProjectId && f.status == (int)RowState.Valid);
            var mids = EmailCfgs.Select(f => f.machineid).ToList();
            var lst = _sigerProjectEmailConfig.GetMachineTitles(ProjectId, mids, 0, title);
            return new ObjectResult(lst);
        }

        /// <summary>
        /// 保存 设备邮箱设置
        /// </summary>
        /// <param name="requestSetting"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SettingMachineEmail([FromBody]RequestSettingMachineEmail requestSetting)
        {

            if (!requestSetting.Mids.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            if (!requestSetting.Users.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var Svc = _sigerProjectEmailConfig.Get(f => f.project == ProjectId && f.status == (int)RowState.Valid);
            if (Svc == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            foreach (var m in requestSetting.Mids)
            {
                if (!_sigerProjectEmailMachine.IsExist(f => f.machineid == m))
                {
                    foreach (var u in requestSetting.Users)
                    {
                        _sigerProjectEmailMachine.Insert(new SigerProjectEmailMachine
                        {
                            machineid = m,
                            server = Svc.id,
                            mid = u,
                            project = ProjectId,
                            time = DateTime.Now,
                            status = (int)RowState.Valid
                        });
                    }
                }
            }
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 配置列表
        /// </summary>
        /// <param name="section"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Settinglist(int section, int page = 1, int pageSize = PageSize)
        {
            var data = _sigerProjectEmailMachine.GetSettingLists(ProjectId, section, page, pageSize, out int total);
            foreach(var d in data)
            {
                d.section_dsc = _sigerProjectEmailConfig.GetLineLevelTitlebByMachine(d.MachinId, ProjectId);
            }
            return new PagedObjectResult(data, total, page, pageSize);
        }


        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="requestModify"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ModifySettingMachine([FromBody]RequestModifySettingMachineEmail requestModify)
        {
            var datalst = _sigerProjectEmailMachine.GetList(f => f.project == ProjectId && f.machineid == requestModify.MachineId);
            if (!datalst.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            //取消选中
            if (requestModify.Users == null || requestModify.Users.Count() == 0)
            {
                foreach (var d in datalst)
                {
                    _sigerProjectEmailMachine.Delete(d);
                }

                if (_unitOfWork.Commit() > 0)
                    return new ObjectResult(CommonEnum.Succefull);
                else
                    throw new BadRequestException(CommonEnum.Fail);
            }

            //有选中
            var svc = _sigerProjectEmailConfig.Get(f => f.project == ProjectId && f.status == (int)RowState.Valid);
            if (svc == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            foreach (var d in datalst)
            {
                _sigerProjectEmailMachine.Delete(d);
            }
            foreach (var m in requestModify.Users)
            {
                _sigerProjectEmailMachine.Insert(new SigerProjectEmailMachine
                {
                    project = ProjectId,
                    server = svc.id,
                    machineid = requestModify.MachineId,
                    mid = m,
                    time = DateTime.Now,
                    status = (int)RowState.Valid
                });

            }
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult DelSettingMachine(int id)
        {
            var data = _sigerProjectEmailMachine.Get(id);
            if (data == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            _sigerProjectEmailMachine.Delete(id);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                throw new BadRequestException(CommonEnum.Fail);
        }
        [HttpGet]
        public IActionResult GetSettingByMachineId(int machineId)
        {
            var datalst = _sigerProjectEmailMachine.GetList(f => f.project == ProjectId && f.machineid == machineId);
            var lstMid = datalst.Select(f => f.mid);

            return new ObjectResult(lstMid);
        }
        /// <summary>
        /// 测试发送
        /// </summary>
        /// <param name="mail"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SendEmail([FromBody]RequestSettingMail mail)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(mail.to))
                {
                    throw new BadRequestException(RequestEnum.ParameterError);
                }
                
                MailHelper.SendMail(mail.host, true, mail.from, mail.password, "江苏西格数据科技有限公司",
                    mail.from, mail.to, "测试邮件", "邮件测试成功，收发邮件正常", new List<string>());

                return new ObjectResult(CommonEnum.Succefull);
            }
            catch (Exception exception)
            {
                Logger.WriteLineError("test send email failed, error:" + exception);
                throw new BadRequestException(CommonEnum.SendMailError);
            }
        }
    }
}
