using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.DomainServices;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.LR;
using APT.MS.Domain.Enums;
using APT.Utility;
using ICSharpCode.SharpZipLib.Core;
using InfluxData.Net.InfluxDb.Models.Responses;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using static NPOI.HSSF.Util.HSSFColor;

namespace APT.LR.WebApi.Controllers.Api
{
    [Route("api/LR/LRLegalList")]
    public class LegalListController : AuthorizeApiController<T_LR_LEGAL_LIST>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public LegalListController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_LR_LEGAL_LIST entity)
        {
            return SafeExecute<bool>(() =>
            {
                var legalListDetail = entity.Nav_LegalListDetail;
                entity.Nav_LegalListDetail = null;
                entity.YEARS = entity.DISTINGUISH_TIME.Year;
                List<T_LR_LEGAL_LIST_DETAIL_USER> users = new List<T_LR_LEGAL_LIST_DETAIL_USER>();
                List<T_LR_LEGAL_LIST_DETAIL_FILE> files = new List<T_LR_LEGAL_LIST_DETAIL_FILE>();
                entity.LEGAL_STATUS = PFStandardStatus.Sign;
                legalListDetail.ForEach(detail =>
                {
                    if (detail.Nav_LegalListDetailUser != null)
                    {
                        users.AddRange(detail.Nav_LegalListDetailUser);
                        detail.Nav_LegalListDetailUser = null;
                    }
                    if (detail.Nav_Files != null)
                    {
                        files.AddRange(detail.Nav_Files);
                        detail.Nav_Files = null;
                    }
                });

                if (entity.USER_ID == Guid.Empty)
                {
                    entity.USER_ID = (Guid)APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                }
                if (entity.DEPARTMENT_ID == Guid.Empty)
                {
                    entity.DEPARTMENT_ID = (Guid)GetEntity<T_FM_USER>(entity.USER_ID).DEPARTMENT_ID;
                }
                List<T_FM_NOTIFICATION_TASK> sendNotices = null;
                T_FM_NOTIFICATION_TASK finishNotice = null;

                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    List<Guid> userIds = new List<Guid>();
                    List<string> userNames = new List<string>();
                    List<string> titles = new List<string>();
                    List<Guid> dataIds = new List<Guid>();
                    if (legalListDetail == null && legalListDetail.Any())
                    {
                        throw new Exception("获取清单明细不能为空！");
                    }
                    var allChargeUsers = legalListDetail.Select(t => t.USER_ID).Distinct();
                    BaseFilter basefilter = new BaseFilter(entity.ORG_ID);
                    var usersNames = GetEntities<T_FM_USER>(t => allChargeUsers.Contains(t.ID), basefilter);
                    allChargeUsers.ForEach(user =>
                    {
                        titles.Add("安全生产法律法规获取清单-待获取");
                        dataIds.Add(entity.ID);
                        userIds.Add((Guid)user);
                        userNames.Add(usersNames.FirstOrDefault(t => t.ID == (Guid)user).NAME);
                    });
                    sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(titles, dataIds, entity.ORG_ID, userIds, userNames, DateTime.Now, DateTime.Today.AddDays(3).AddSeconds(-1), 0, "LR023");
                    finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (users != null && users.Any())
                        BantchSaveEntityNoCommit(users);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (legalListDetail != null && legalListDetail.Any())
                        BantchSaveEntityNoCommit(legalListDetail);
                    if (sendNotices != null)
                        BantchAddEntityNoCommit(sendNotices);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });

                return true;
            });
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("DetailUpdate")]
        public JsonActionResult<bool> DetailUpdate([FromBody] T_LR_LEGAL_LIST entity)
        {
            return SafeExecute<bool>(() =>
            {
                var UserID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.USER_ID == Guid.Empty)
                {
                    entity.USER_ID = (Guid)UserID;
                }
                if (entity.DEPARTMENT_ID == Guid.Empty)
                {
                    entity.DEPARTMENT_ID = (Guid)GetEntity<T_FM_USER>(entity.USER_ID.ToString()).DEPARTMENT_ID;
                }
                var legalListDetail = entity.Nav_LegalListDetail;
                entity.Nav_LegalListDetail = null;
                List<T_LR_LEGAL_LIST_DETAIL_USER> users = new List<T_LR_LEGAL_LIST_DETAIL_USER>();
                List<T_LR_LEGAL_LIST_DETAIL_FILE> files = new List<T_LR_LEGAL_LIST_DETAIL_FILE>();
                List<T_FM_NOTIFICATION_TASK> sendNotices = null;
                List<T_LR_LAW> laws = new List<T_LR_LAW>();
                List<T_LR_LAW_VERSION> lawVersions = new List<T_LR_LAW_VERSION>();
                List<T_LR_LAW_VERSION_FILE> lawVersionFiles = new List<T_LR_LAW_VERSION_FILE>();
                T_LR_LAW_INTEGRATE lawIntegrate = null;
                List<T_LR_LAW_INTEGRATE_DETAIL> lawIntegrateDetails = new List<T_LR_LAW_INTEGRATE_DETAIL>();
                T_FM_NOTIFICATION_TASK finishNotice = new T_FM_NOTIFICATION_TASK();
                List<T_LR_LAW> existLaws = new List<T_LR_LAW>();
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if(entity.LEGAL_STATUS== PFStandardStatus.Archived)
                    {
                        throw new Exception("状态已归档不允许修改！");
                    }
                    BaseFilter basefilter = new BaseFilter(entity.ORG_ID);
                    basefilter.SelectField = new string[] { "ID", "NAME", "DEPARTMENT_ID", "Nav_ApproveRole.NAME", "Nav_Department.Nav_User" };
                    var allUsers = GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.IS_DELETED == false, basefilter);
                    var allLaws = GetEntities<T_LR_LAW>(t => t.LAW_STATUS== BSLawStatusEnum.现行, new BaseFilter(entity.ORG_ID),new string[] { "Nav_LawVersion", "Nav_LawSCSystem" });
                    List<Guid> userIds = new List<Guid>();
                    List<string> userNames = new List<string>();
                    List<string> titles = new List<string>();
                    List<Guid> dataIds = new List<Guid>();
                    List<string> formCodes = new List<string>();

                    string title = "新增法律法规";

                    foreach (var item in legalListDetail)
                    {
                        //1有附件自动更新到法律法规
                        if (item.FILE_STATUS == LRLegalFileStatusEnum.否 && item.Nav_Files == null)
                        {
                            throw new Exception("文件在库状态为否,上传附件不能为空！");
                        }
                    }
                    if(legalListDetail.Count(t=>t.IS_DELETED==false&& t.FILE_STATUS== LRLegalFileStatusEnum.否) > 0)
                    {
                        //2触发给填写人法律法规融入
                        lawIntegrate = new T_LR_LAW_INTEGRATE();
                        lawIntegrate.ID = Guid.NewGuid();
                        lawIntegrate.YEAR = DateTime.Now.Year;
                        lawIntegrate.ORG_ID = entity.ORG_ID;
                        lawIntegrate.RATE = "0";
                    }
                    
                    foreach (var item in legalListDetail)
                    {
                        var isExistlaw =  allLaws.FirstOrDefault(t => t.NAME == item.FILE_NAME);
                        Guid lawid = Guid.Empty;
                        if (isExistlaw!=null&& isExistlaw.VERSION_NUM==item.VERSION_NUM&& item.FILE_STATUS == LRLegalFileStatusEnum.否)
                        {
                            throw new Exception("该法律已存在！");
                        }
                        if (isExistlaw==null&&item.FILE_STATUS== LRLegalFileStatusEnum.否)
                        {
                            lawid = Guid.NewGuid();
                            T_LR_LAW law = new T_LR_LAW();
                            law.ID = lawid;
                            law.NAME = item.FILE_NAME;
                            law.VERSION_NUM = item.VERSION_NUM;
                            law.LAW_STATUS = BSLawStatusEnum.现行;
                            law.UPDATE_TIME = item.UPDATE_TIME;
                            law.TYPE_ID = (Guid)item.DEMANDTYPE_ID;
                            law.ORG_ID = entity.ORG_ID;
                            law.USER_ID = (Guid)UserID;
                            laws.Add(law);
                            T_LR_LAW_VERSION lawVersion = new T_LR_LAW_VERSION();
                            lawVersion.LAW_ID = law.ID;
                            lawVersion.VERSION_NUM = law.VERSION_NUM;
                            lawVersion.UPDATE_TIME = law.UPDATE_TIME;
                            lawVersion.EXECUTE_TIME = item.EXECUTE_TIME;
                            lawVersion.ENTER_TIME = DateTime.Now;
                            lawVersion.VERSION_STATUS = BSLawStatusEnum.现行;
                            lawVersion.ORG_ID = entity.ORG_ID;
                            lawVersions.Add(lawVersion);
                            foreach (var file in item.Nav_Files)
                            {
                                T_LR_LAW_VERSION_FILE lawVersionFile = new T_LR_LAW_VERSION_FILE();
                                lawVersionFile.ID = Guid.NewGuid();
                                lawVersionFile.VERSION_ID = lawVersion.ID;
                                lawVersionFile.IMG_FILE_ID = file.IMG_FILE_ID;
                                lawVersionFile.ORG_ID = entity.ORG_ID;
                                lawVersionFiles.Add(lawVersionFile);
                            }
                            foreach (var user in item.Nav_LegalListDetailUser)
                            {
                                titles.Add("新增法律法规《" + item.FILE_NAME + "》");
                                dataIds.Add(entity.ID);
                                userIds.Add(user.USER_ID);
                                userNames.Add(allUsers.FirstOrDefault(t => t.ID == user.USER_ID).NAME);
                                formCodes.Add("PF135");
                            }
                            
                            T_LR_LAW_INTEGRATE_DETAIL lawIntegrateDetail = new T_LR_LAW_INTEGRATE_DETAIL();
                            lawIntegrateDetail.ID = Guid.NewGuid();
                            lawIntegrateDetail.LAW_INTEGRATE_ID = lawIntegrate.ID;
                            lawIntegrateDetail.LAW_ID = lawid;
                            lawIntegrateDetail.ORG_ID = entity.ORG_ID;
                            lawIntegrateDetails.Add(lawIntegrateDetail);
                        }
                        else if(isExistlaw != null && item.FILE_STATUS == LRLegalFileStatusEnum.否)
                        {
                            lawid = isExistlaw.ID;
                            var Nav_LawVersion = isExistlaw.Nav_LawVersion;
                            isExistlaw.Nav_LawVersion=null;
                            foreach ( var law in Nav_LawVersion)
                            {
                                law.VERSION_STATUS = (int)BSLawStatusEnum.废止;
                            }
                            isExistlaw.VERSION_NUM = item.VERSION_NUM;
                            isExistlaw.UPDATE_TIME = item.UPDATE_TIME;
                            isExistlaw.USER_ID = (Guid)UserID;
                            BantchSaveEntity(Nav_LawVersion);
                            existLaws.Add(isExistlaw);
                            T_LR_LAW_VERSION lawVersion = new T_LR_LAW_VERSION();
                            lawVersion.LAW_ID = isExistlaw.ID;
                            lawVersion.VERSION_NUM = item.VERSION_NUM;
                            lawVersion.UPDATE_TIME = item.UPDATE_TIME;
                            lawVersion.EXECUTE_TIME = item.EXECUTE_TIME;
                            lawVersion.ENTER_TIME = DateTime.Now;
                            lawVersion.VERSION_STATUS = BSLawStatusEnum.现行;
                            lawVersion.ORG_ID = entity.ORG_ID;
                            lawVersions.Add(lawVersion);

                            foreach (var file in item.Nav_Files)
                            {
                                T_LR_LAW_VERSION_FILE lawVersionFile = new T_LR_LAW_VERSION_FILE();
                                lawVersionFile.ID = Guid.NewGuid();
                                lawVersionFile.VERSION_ID = lawVersion.ID;
                                lawVersionFile.IMG_FILE_ID = file.IMG_FILE_ID;
                                lawVersionFile.ORG_ID = entity.ORG_ID;
                                lawVersionFiles.Add(lawVersionFile);
                            }
                            title = "新增法律法规《" + item.FILE_NAME + "》," ;
                            T_LR_LAW_INTEGRATE_DETAIL lawIntegrateDetail = new T_LR_LAW_INTEGRATE_DETAIL();
                            lawIntegrateDetail.ID = Guid.NewGuid();
                            lawIntegrateDetail.LAW_INTEGRATE_ID = lawIntegrate.ID;
                            lawIntegrateDetail.LAW_ID = lawid;
                            if(isExistlaw.Nav_LawSCSystem.Count > 0)
                            {
                                lawIntegrateDetail.SYSTEM_ID = isExistlaw.Nav_LawSCSystem.FirstOrDefault().SC_SYSTEM_ID;
                            }
                            lawIntegrateDetail.ORG_ID = entity.ORG_ID;
                            lawIntegrateDetails.Add(lawIntegrateDetail);
                        }
                    }
                    //foreach (var user in chargeUsers)
                    //{
                    //    //3触发给需求人员,需求人员部门负责人,安环负责人
                    //    titles.Add(title);
                    //    dataIds.Add(entity.ID);
                    //    var currUser = allUsers.FirstOrDefault(t => t.ID == user);
                    //    userIds.Add(currUser.Nav_Department.Nav_User.ID);
                    //    userNames.Add(currUser.Nav_Department.Nav_User.NAME);
                    //    formCodes.Add("PF135");
                    //}
                    var currentDetial = legalListDetail.Select(t => t.ID);
                    var legaldetailAll = GetEntities<T_LR_LEGAL_LIST_DETAIL>(t => t.LEGAL_ID==entity.ID&&t.IS_DELETED==false && !currentDetial.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                    var countlegalDetail = legaldetailAll.Where(t => t.FILE_NAME == null);
                    //全部完成后发送给安环部负责人
                    if (countlegalDetail.Count()==0)
                    {
                       // string title1 = String.Join("》,《", legaldetailAll.Where(t => t.FILE_STATUS == LRLegalFileStatusEnum.否).Select(t => t.FILE_NAME).ToList());
                        string title2 = String.Join("》,《", legalListDetail.Where(t => t.FILE_STATUS == LRLegalFileStatusEnum.否).Select(t => t.FILE_NAME).ToList());

                        entity.LEGAL_STATUS = PFStandardStatus.Archived;
                        var ahUser = allUsers.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "安环部负责人");
                        //titles.Add("新增法律法规《" + title1+ "》,《" + title2+ "》");
                        titles.Add("新增法律法规《" + title2+ "》");
                        dataIds.Add(entity.ID);
                        userIds.Add(ahUser.ID);    
                        userNames.Add(ahUser.NAME);
                        formCodes.Add("PF135");
                    }
                    sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(titles, dataIds, entity.ORG_ID, userIds, userNames, DateTime.Now, DateTime.Today.AddDays(3).AddSeconds(-1), (int)FMNoticeTypeEnum.今日提醒, formCodes);
                    if (lawIntegrate != null)
                    {
                        sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("安全生产法律法规融入", lawIntegrate.ID, entity.ORG_ID, (Guid)UserID, allUsers.FirstOrDefault(t => t.ID == UserID).NAME, DateTime.Now, DateTime.Today.AddDays(3).AddSeconds(-1), 0, "LR008"));
                    }
                    finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                }
                legalListDetail.ForEach(detail =>
                {
                    if (detail.Nav_LegalListDetailUser != null)
                    {
                        users.AddRange(detail.Nav_LegalListDetailUser);
                        detail.Nav_LegalListDetailUser = null;
                    }
                    if (detail.Nav_Files != null)
                    {
                        files.AddRange(detail.Nav_Files);
                        detail.Nav_Files = null;
                    }
                });
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (laws != null && laws.Any())
                        BantchAddEntityNoCommit(laws);
                    if (lawVersions != null && lawVersions.Any())
                        BantchAddEntityNoCommit(lawVersions);
                    if (lawVersionFiles != null && lawVersionFiles.Any())
                        BantchAddEntityNoCommit(lawVersionFiles);
                    if (legalListDetail != null && legalListDetail.Any())
                        BantchSaveEntityNoCommit(legalListDetail);
                    if (lawIntegrate != null)
                        AddEntityNoCommit(lawIntegrate);
                    if (lawIntegrateDetails != null && lawIntegrateDetails.Any())
                        BantchAddEntityNoCommit(lawIntegrateDetails);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (sendNotices != null&&sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if(existLaws.Any())
                        BantchSaveEntityNoCommit(existLaws);
                });

                return true;
            });
        }
        /// <summary>
		/// 根据当前用户过滤子表
		/// </summary>
		/// <param name="filter"></param>
		/// <returns></returns>
		[HttpPost, Route("FullGet")]
        public JsonActionResult<T_LR_LEGAL_LIST> FullGet([FromBody] KeywordFilter filter)
        {
            JsonActionResult<T_LR_LEGAL_LIST> jsonActionResult = new JsonActionResult<T_LR_LEGAL_LIST>();
            var data = WitEntity(null, filter);
            T_LR_LEGAL_LIST model = data.Data;
            if (model != null && model.Nav_LegalListDetail != null && model.Nav_LegalListDetail.Count() > 0)
            {
                var Nav_LegalListDetail = model.Nav_LegalListDetail;
                var user_id = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                model.Nav_LegalListDetail = Nav_LegalListDetail.Where(t => t.USER_ID == user_id).ToList();
            }
            jsonActionResult.Data = model;
            return jsonActionResult;
        }
    }
}