using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.TL;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.SC.WebApi.Controllers.Api.SC
{
    [Route("api/TL/TLWatchLine")]
    public class TLWatchLineController : AuthorizeApiController<T_TL_WATCH_LINE>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public TLWatchLineController(IFMFlowPermitService mFlowPermitService, IFMNotificationTaskService notificationTaskService)
        {
            MFlowPermitService = mFlowPermitService;
            NotificationTaskService = notificationTaskService;
        }

        /// <summary>
        /// 附件上传
        /// 设计文件专家评审意见 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_TL_WATCH_LINE entity)
        {
            return SafeExecute<bool>(() =>
            {
                T_FM_NOTIFICATION_TASK taskDo = null;
                //只要有一个人操作了 检测待办 其余 删除
                List<Guid> listTaskRemoveID = null;
                var loginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (!loginID.HasValue)
                {
                    throw new Exception("获取您的登录信息失败，请重新登录后再操作！");
                }
                if ((entity.CREATE_TIME == null || (entity.CREATE_TIME.Value - DateTime.Now).TotalHours < 1) && entity.SUM_ID == Guid.Empty && entity.TaskID == Guid.Empty)
                {
                    //判断为新增 无需任何处理
                }
                else if (entity.USER_ID.HasValue)
                {
                    if (entity.USER_ID.Value != loginID)
                    {
                        var userSend = GetEntity<T_FM_USER>(entity.USER_ID.Value);
                        if (userSend != null)
                        {
                            throw new Exception("您不是【" + userSend.NAME + "】无权限操作此单！");
                        }
                        else
                        {
                            throw new Exception("您无权限操作此单！");
                        }
                    }
                }
                else if (entity.TaskID == Guid.Empty)
                {
                    var listTaskTemp = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID.HasValue && e.SOURCE_DATA_ID.Value == entity.ID && e.SOURCE_FORMCODE == "TL041", null, null);

                    if (listTaskTemp != null && listTaskTemp.Any())
                    {
                        taskDo = listTaskTemp.FirstOrDefault(e => e.USER_ID == loginID.Value);
                        if (taskDo == null)
                        {
                            var listUserName = listTaskTemp.Where(e => e.USER_ID != loginID).Select(e => e.USER_NAME);
                            if (listUserName == null)
                            {
                                throw new Exception("您无权限操作此单！");
                            }
                            else
                            {
                                throw new Exception("您不是【" + String.Join(",", listUserName) + "】无权限操作此单！");
                            }
                        }
                        else
                        {
                            listTaskRemoveID = listTaskTemp.Where(e => e.USER_ID != loginID.Value).Select(e => e.ID).ToList();
                        }
                    }
                }
                else
                {
                    taskDo = GetEntity<T_FM_NOTIFICATION_TASK>(entity.TaskID, null);
                    if (taskDo == null)
                    {
                        throw new Exception("该位移观测已处理，您无需再次处理！");
                    }
                    else
                    {
                        var listTaskTemp = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID.HasValue && e.SOURCE_DATA_ID.Value == taskDo.SOURCE_DATA_ID.Value && e.ID != taskDo.ID && e.SOURCE_FORMCODE == "TL043", null, null);
                        if (listTaskTemp != null && listTaskTemp.Any())
                        {
                            listTaskRemoveID = listTaskTemp.Select(e => e.ID).ToList();
                        }
                    }
                }

                var liatDetail = entity.Nav_ListDetail;//明细
                entity.Nav_ListDetail = null;
                List<T_TL_WATCH_LINE_DETAIL_FILE> listDetailFile = new List<T_TL_WATCH_LINE_DETAIL_FILE>();
                if (!entity.USER_ID.HasValue || entity.USER_ID == Guid.Empty)
                {
                    entity.USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                    entity.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                }
                if (entity.USER_ID != APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value)
                {
                    throw new Exception("只能操作自己提交的记录！");
                }
                if (entity.DATE == DateTime.MinValue)
                {
                    throw new Exception("请选择日期！");
                }
                if (entity.STATUS == PFStandardStatus.Archived)
                {
                    if (entity.DATE.Date > DateTime.Now.Date)
                    {
                        throw new Exception("日期不能大于今天【" + DateTime.Now.ToString("yyyy-MM-dd") + "】！");
                    }
                    if (liatDetail == null || !liatDetail.Any())
                    {
                        throw new Exception("浸润线观测明细不能为空！");
                    }

                    //taskDo = GetEntity<T_FM_NOTIFICATION_TASK>(entity.TaskID, null);
                    if (taskDo != null)
                    {
                        //操作待办处理
                        taskDo.TASK_DT = DateTime.Now;
                        taskDo.SOURCE_FORMCODE = "TL043_SHOWPRINT";
                        if (taskDo.TASK_ENDDT >= taskDo.TASK_DT)
                            taskDo.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                        else
                            taskDo.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                    }
                }
                List<Guid> listUserID = null;
                List<T_TL_WATCH_LINE_DETAIL_USER> listUsers = null;//观测人
                List<T_TL_WATCH_LINE_DETAIL_USER> listUserTemp = null;//观测人
                if (liatDetail != null && liatDetail.Any())
                {
                    listUsers = new List<T_TL_WATCH_LINE_DETAIL_USER>();
                    int rowIndex = 0;
                    foreach (var item in liatDetail)
                    {
                        #region    数据填充
                        if (entity.TAILING_ID != Guid.Empty)
                        {
                            item.TAILING_ID = entity.TAILING_ID;
                        }

                        if (string.IsNullOrEmpty(item.TAILING_NAME) && !string.IsNullOrEmpty(entity.TAILING_NAME))
                        {
                            item.TAILING_NAME = entity.TAILING_NAME;
                        }
                        #endregion

                        //item.Nav_WatchMovePoint = null;
                        if (item.Nav_Files != null && item.Nav_Files.Any())
                        {
                            foreach (var itemF in item.Nav_Files)
                            {
                                if (itemF.LINE_DETAIL_ID == Guid.Empty)
                                    itemF.LINE_DETAIL_ID = item.ID;
                            }
                            listDetailFile.AddRange(item.Nav_Files.ToList());
                            item.Nav_Files = null;
                        }
                        rowIndex++;
                        if (item.Nav_ListUser != null && item.Nav_ListUser.Any())
                        {
                            listUserTemp = item.Nav_ListUser.ToList();
                            foreach (var itemWatch in listUserTemp)
                            {
                                if (itemWatch.USER_ID == entity.USER_ID)
                                {
                                    itemWatch.ISCHECK = true;
                                }
                                else
                                {
                                    itemWatch.ISCHECK = false;
                                }
                                itemWatch.ORG_ID = entity.ORG_ID;
                            }

                            listUsers.AddRange(listUserTemp);
                            if (entity.STATUS == PFStandardStatus.Archived && (listUserTemp.Count > 1 || listUserTemp[0].USER_ID != entity.USER_ID))
                            {
                                if (listUserID == null)
                                {
                                    listUserID = new List<Guid>();
                                }
                                foreach (var itemUser in listUserTemp)
                                {
                                    if (itemUser.USER_ID != entity.USER_ID && !listUserID.Contains(itemUser.USER_ID))
                                    {
                                        listUserID.Add(itemUser.USER_ID);
                                    }
                                }
                            }
                        }
                        if (entity.STATUS != PFStandardStatus.Archived)
                        {
                            continue;
                        }

                        if (item.DATE == DateTime.MinValue)
                        {
                            throw new Exception("观测日期行【" + rowIndex + "】不能为空！");
                        }
                        if (item.WATCH_LINE_POINT_ID == Guid.Empty)
                        {
                            throw new Exception("基准点号行【" + rowIndex + "】不能为空！");
                        }
                        //if (!string.IsNullOrEmpty(item.LOOKPOINT))
                        //{
                        //    throw new Exception("观测值X/Y/Z行【" + rowIndex + "】不能为空！");
                        //}
                        //if (!string.IsNullOrEmpty(item.CHANGELOOKPOINT))
                        //{
                        //    throw new Exception("变化量△X/△Y/△Z行【" + rowIndex + "】不能为空！");
                        //}

                        if (item.Nav_ListUser == null || !item.Nav_ListUser.Any())
                        {
                            throw new Exception("观测人员行【" + rowIndex + "】不能为空！");
                        }
                    }
                }

                List<T_FM_NOTIFICATION_TASK> listTask = null;
                //发送 确认单 待办
                if (listUserID != null && listUserID.Any())
                {
                    //接收确认 待办
                    List<T_FM_USER> listUserSend = GetEntities<T_FM_USER>(e => listUserID.Contains(e.ID), null, null).ToList();
                    entity.STATUS = PFStandardStatus.Sign;
                    List<Guid> listSendUserID = new List<Guid>();
                    List<string> listSendUserNAME = new List<string>();
                    foreach (var item in listUserSend)
                    {
                        listSendUserID.Add(item.ID);
                        listSendUserNAME.Add(item.NAME);
                    }
                    listTask = NotificationTaskService.InsertUserNoticeTaskModels("尾矿库浸润线观测记录确认-" + entity.DATE.ToString("MMdd"), entity.ID, entity.ORG_ID, listSendUserID, listSendUserNAME, DateTime.Now, 0, "TL043_SHOWPRINT", FMTASKTYPE.Default);
                }

                T_TL_WATCH_SUM sum = null;
                if (entity.SUM_ID == Guid.Empty)
                {
                    sum = GetEntity<T_TL_WATCH_SUM>(e => e.DATE == DateTime.Now.Date);
                    if (sum == null)
                    {
                        sum = new T_TL_WATCH_SUM();
                        sum.ID = Guid.NewGuid();
                        sum.ORG_ID = entity.ORG_ID;
                        sum.DATE = DateTime.Now.Date;
                        sum.TAILING_NAME = entity.TAILING_NAME;
                        sum.TAILING_ID = entity.TAILING_ID;
                    }
                    entity.SUM_ID = sum.ID;
                }
                liatDetail.ForEach(item => item.SUM_ID = entity.SUM_ID);

                //if (listUsers != null && listUsers.Any())
                //{
                //    foreach (var item in listUsers)
                //    {
                //        item.Nav_User = null;
                //    }
                //}
                this.UnifiedCommit(() =>
                {
                    if (sum != null)
                        UpdateEntityNoCommit(sum);

                    if (entity != null)//待办信息主题保存
                        UpdateEntityNoCommit(entity);
                    if (liatDetail != null && liatDetail.Any())//明细
                        BantchSaveEntityNoCommit(liatDetail);
                    if (listDetailFile != null && listDetailFile.Any())//明细
                        BantchSaveEntityNoCommit(listDetailFile);
                    if (listUsers != null && listUsers.Any())//观测人
                        BantchSaveEntityNoCommit(listUsers);

                    if (entity.STATUS != PFStandardStatus.Draft && taskDo != null)//检测记录待办删除
                        UpdateEntityNoCommit(taskDo);
                    if (listTaskRemoveID != null && listTaskRemoveID.Any())//同部门岗位人员检测待办 删除
                        BantchDeleteEntity<T_FM_NOTIFICATION_TASK>(listTaskRemoveID);
                    if (listTask != null && listTask.Any())//多检测人添加确认待办
                        BantchSaveEntityNoCommit(listTask);
                });
                return true;
            });
        }

        /// <summary>
        /// 确认
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("sendCheck")]
        public JsonActionResult<bool> sendCheck([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                if (string.IsNullOrEmpty(filter.Keyword) || string.IsNullOrEmpty(filter.Parameter1))
                    throw new Exception("获取参数有误");

                Guid id = Guid.Empty;
                try
                {
                    id = new Guid(filter.Keyword);
                }
                catch
                {
                    throw new Exception("获取参数有误");
                }

                Guid taskID = Guid.Empty;
                if (!string.IsNullOrEmpty(filter.Parameter1))
                {
                    try
                    {
                        taskID = new Guid(filter.Parameter1);
                    }
                    catch
                    {
                        throw new Exception("获取参数有误");
                    }
                }

                Guid LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;

                var detail = GetEntities<T_TL_WATCH_LINE_DETAIL>(e => e.LINE_ID == id, null, "Nav_ListUser");
                List<T_TL_WATCH_LINE_DETAIL_USER> listDestUserLogin = new List<T_TL_WATCH_LINE_DETAIL_USER>();
                bool isOther = false;
                if (detail != null && detail.Any())
                {
                    foreach (var item in detail)
                    {
                        if (item.Nav_ListUser != null && item.Nav_ListUser.Any())
                        {
                            try
                            {
                                var listDestUserTempLogin = item.Nav_ListUser.Where(e => !e.ISCHECK && e.USER_ID == LoginID);
                                if (listDestUserTempLogin != null && listDestUserTempLogin.Any())
                                {
                                    listDestUserLogin.AddRange(listDestUserTempLogin);
                                }

                                if (!isOther)
                                {
                                    var listDestUserTempNotLogin = item.Nav_ListUser.Where(e => !e.ISCHECK && e.USER_ID != LoginID);
                                    if (listDestUserTempNotLogin != null && listDestUserTempNotLogin.Any())
                                    {
                                        isOther = true;
                                    }
                                }
                            }
                            catch { }
                        }
                    }
                }

                var task = NotificationTaskService.GetEntityTask(taskID);
                if (listDestUserLogin != null && listDestUserLogin.Any())
                    listDestUserLogin.ForEach(e => { e.ISCHECK = true; e.MODIFY_TIME = DateTime.Now; });

                T_TL_WATCH_LINE modelLine = null;
                //如果没有未确认的观测人 修改主表状态
                if (!isOther)
                {
                    modelLine = GetEntity<T_TL_WATCH_LINE>(id);
                    modelLine.STATUS = PFStandardStatus.Archived;
                    modelLine.MODIFY_TIME = DateTime.Now;
                }

                this.UnifiedCommit(() =>
                {
                    if (task != null)//代办消息 清除
                        UpdateEntityNoCommit(task);//状态修改
                    if (listDestUserLogin != null && listDestUserLogin.Count > 0)
                        BantchSaveEntityNoCommit(listDestUserLogin);
                    if (modelLine != null)//代办消息 清除
                        UpdateEntityNoCommit(modelLine);//状态修改
                });
                return true;
            });
        }
    }
}