using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.LR;
using APT.MS.Domain.Entities.SC.SC;
using APT.MS.Domain.Enums;
using APT.Utility;
using InfluxData.Net.InfluxDb.Models.Responses;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace APT.LR.WebApi.Controllers.Api
{
    [Route("api/LR/LRLawIntegrateUpdate")]
    public class LawIntegrateUpdateController : AuthorizeApiController<T_LR_LAW_INTEGRATE_UPDATE>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public LawIntegrateUpdateController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_LR_LAW_INTEGRATE_UPDATE entity)
        {
            return SafeExecute<bool>(() =>
            {
                var lrLawInstitution = new List<T_LR_LAW_INSTITUTION>();
                var integrateUpdateDetail = entity.Nav_IntegrateUpdateDetail;
                entity.Nav_IntegrateUpdateDetail = null;
                T_FM_NOTIFICATION_TASK finishNotice = null;
                List<T_FM_NOTIFICATION_TASK> sendNotices = null;
                List<T_SC_STANDARD_CREATE> standards = new List<T_SC_STANDARD_CREATE>();
                List<T_LR_LAW_SC_SYSTEM> addLawSystems = null;
                List<T_LR_LAW_SC_SYSTEM> deleteSystems = null;
                integrateUpdateDetail.ForEach(detail =>
                {
                    if (detail.Nav_LRLawInstitution != null)
                    {
                        lrLawInstitution.AddRange(detail.Nav_LRLawInstitution);
                        detail.Nav_LRLawInstitution = null;
                    }
                });
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "LR009_SHOWPRINT");
                        if (!finishNotice.SOURCE_DATA_ID.HasValue)
                            finishNotice.SOURCE_DATA_ID = entity.ID;
                    }
                    //2023-07-31更新与融入时建立关联,先把之前的都删了,再新建
                    var newintegrateUpdateDetail = integrateUpdateDetail.Where(t => t.IS_DELETED == false);
                    var newlrLawInstitution = lrLawInstitution.Where(t => t.IS_DELETED == false);
                    var alllawids = newintegrateUpdateDetail.Select(t => t.LAW_ID);
                    deleteSystems = GetEntities<T_LR_LAW_SC_SYSTEM>(t => alllawids.Contains(t.LAW_ID), new BaseFilter(entity.ORG_ID)).ToList();
                    addLawSystems = new List<T_LR_LAW_SC_SYSTEM>();
                    foreach (var detail in newlrLawInstitution)
                    {
                        var newsystem = new T_LR_LAW_SC_SYSTEM();
                        newsystem.ID = Guid.NewGuid();
                        newsystem.LAW_ID = integrateUpdateDetail.FirstOrDefault(t => t.ID == detail.UPDATE_DETAIL_ID).LAW_ID;
                        newsystem.SC_SYSTEM_ID = (Guid)detail.SC_SYSTEM_ID;
                        newsystem.ORG_ID = entity.ORG_ID;
                        addLawSystems.Add(newsystem);
                    }
                    var updateDetail = newintegrateUpdateDetail.Where(t => t.UPDATE_STATUS == LRLawIntegrateUpdateStatusEnum.未更新);
                    if (updateDetail != null && updateDetail.Any())
                    {
                        var lawids = updateDetail.Select(t => t.LAW_ID);
                        var laws = GetEntities<T_LR_LAW>(t => lawids.Contains(t.ID), new BaseFilter(entity.ORG_ID), new string[] { "Nav_User" });

                        var noticeTitles = new List<string>();
                        var noticeUserIds = new List<Guid>();
                        var noticeUserNames = new List<string>();
                        var noticeDataIds = new List<Guid>();
                        //取标准化最新code
                        KeywordFilter filter = new KeywordFilter();
                        filter.OrgId = entity.ORG_ID;
                        filter.Keyword = "0";
                        var code = GetFileCode(filter).Data;
                        if (string.IsNullOrEmpty(code))
                            throw new Exception("获取制度编号错误，请联系管理员");
                        else
                        {
                            if (code.Length <= 5)
                                throw new Exception("获取制度编号错误，请联系管理员");
                        }
                        int i = 0;
                        foreach (var law in laws)
                        {
                            // 取最后五位序列号
                            var serial = code.Substring(code.Length - 5);
                            //序列号+1，不足五位补0
                            var num = (int.Parse(serial) + i).ToString().PadLeft(5, '0');
                            var temp = code.Substring(0, code.Length - 5);
                            var entityCode = temp + num;
                            T_SC_STANDARD_CREATE standard = new T_SC_STANDARD_CREATE();
                            standard.ID = Guid.NewGuid();
                            standard.USER_ID = law.USER_ID;
                            standard.ORG_ID = entity.ORG_ID;
                            standard.LAW_NAME = law.NAME;
                            standard.LAW_ID = law.ID;
                            standard.USER_ID = law.USER_ID;
                            standard.TYPE = SCType.制度;
                            standard.CODE = entityCode;
                            standards.Add(standard);
                            noticeUserIds.Add(law.USER_ID);
                            noticeUserNames.Add(law.Nav_User.NAME);
                            noticeTitles.Add("标准化制度创建");
                            noticeDataIds.Add(standard.ID);
                            i++;
                        }
                        sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(noticeTitles, noticeDataIds, entity.ORG_ID, noticeUserIds, noticeUserNames, DateTime.Now, DateTime.Now.AddDays(10), 0, "SC046");
                    }


                }

                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (lrLawInstitution.Any())
                        BantchSaveEntityNoCommit(lrLawInstitution);
                    if (integrateUpdateDetail.Any())
                        BantchSaveEntityNoCommit(integrateUpdateDetail);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (sendNotices != null && sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                    if (standards != null && standards.Any())
                        BantchAddEntityNoCommit(standards);
                    if (deleteSystems != null && deleteSystems.Any())
                        DeleteEntityNoCommit(deleteSystems);
                    if (addLawSystems != null && addLawSystems.Any())
                        BantchAddEntityNoCommit(addLawSystems);
                });
                return true;
            });
        }
        /// <summary>
        /// 自动生成CODE
        /// </summary>
        /// <param name="filter"></param>
        [HttpPost, Route("GetFileCode")]
        public JsonActionResult<string> GetFileCode([FromBody] KeywordFilter filter)
        {
            return SafeExecute<string>(() =>
            {
                var fileCode = "";
                var nextCodeInfo = this.GetEntities<T_SC_STANDARD_CREATE>(t => !t.IS_DELETED && (int)t.TYPE == int.Parse(filter.Keyword), new BaseFilter(filter.OrgId)).OrderByDescending(t => t.CREATE_TIME).FirstOrDefault();
                var year = DateTime.Now.Year;
                var month = DateTime.Now.Month.PadLeft(2, '0');
                var day = DateTime.Now.Day.PadLeft(2, '0');
                var prefix = "ZD";
                if (filter.Keyword == "1")
                    prefix = "ZRZ";
                if (filter.Keyword == "2")
                    prefix = "GWGC";
                if (filter.Keyword == "3")
                    prefix = "YJYA";
                if (nextCodeInfo == null)
                {
                    fileCode = prefix + year + month + day + "00001";
                }
                else
                {
                    if (nextCodeInfo.CODE.Length <= 5)
                    {
                        fileCode = prefix + year + month + day + "00001";
                    }
                    //取最后五位序列号
                    var serial = nextCodeInfo.CODE.Substring(nextCodeInfo.CODE.Length - 5);
                    //序列号+1，不足五位补0
                    var num = (int.Parse(serial) + 1).ToString().PadLeft(5, '0');
                    fileCode = prefix + year + month + day + num;
                }
                return fileCode;
            });
        }
    }
}