using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Enums;
using APT.Utility;
using ICSharpCode.SharpZipLib.Core;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.Record.Chart;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.HM.WebApi.Controllers.Api
{
    [Route("api/HM/HMHazardTask")]
    public partial class HazardTaskController : AuthorizeApiController<T_HM_HAZARD_TASK>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }


        public HazardTaskController(IFMNotificationTaskService notificationTaskService, IPFCodeRuleService codeRuleService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IFMDepartmentService departmentService)
        {
            NotificationTaskService = notificationTaskService;
            CodeRuleService = codeRuleService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// HM062更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_HM_HAZARD_TASK entity)
        {
            {
                return SafeExecute<bool>(() =>
                {
                    var files = entity.Nav_Files;
                    var riskDetail = entity.Nav_Detail;
                    var areas = entity.Nav_Areas;
                    var identifyings = entity.Nav_Identifyings;
                    List<T_HM_HAZARD_TASK_DETAIL_USER> users = new List<T_HM_HAZARD_TASK_DETAIL_USER>();
                    List<T_HM_HAZARD_TASK_DETAIL_IDENTIFYING> subIdentifyings = new List<T_HM_HAZARD_TASK_DETAIL_IDENTIFYING>();

                    riskDetail.ForEach(detail =>
                    {
                        if (detail.Nav_Users != null)
                        {
                            detail.Nav_Users.ForEach(user =>
                            {
                                if (user.USER_ID != detail.RECORD_USER_ID)
                                {
                                    user.ROW_NO = 999;
                                }
                            });
                            users.AddRange(detail.Nav_Users);
                            detail.Nav_Users = null;
                        }
                        if (detail.Nav_Identifyings != null)
                        {
                            subIdentifyings.AddRange(detail.Nav_Identifyings);
                            detail.Nav_Identifyings = null;
                        }
                    });
                    if (entity.LIABLE_USER_ID == Guid.Empty || entity.LIABLE_USER_ID == null)
                    {
                        entity.LIABLE_USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    }
                    entity.Nav_Files = null;
                    entity.Nav_Detail = null;
                    entity.Nav_Areas = null;
                    entity.Nav_Identifyings = null;
                    identifyings?.ForEach(identifying => { identifying.Nav_Identifying = null; identifying.Nav_Task = null; });
                    areas?.ForEach(areas => { areas.Nav_Area = null; areas.Nav_Task = null; });
                    if (entity.INITIATING_DEPARTMENT == null)
                    {
                        var user = GetEntity<T_FM_USER>(t => t.ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID);
                        if (user != null)
                            entity.INITIATING_DEPARTMENT = user.DEPARTMENT_ID;
                    }
                    var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                    entity.STATUS = FOPreMeetingStatusEnum.草稿;
                    entity.APPROVECODE = null;
                    //是否需要发审批流，false不发，true的时候默认只发当前审核人
                    var isSendApprove = false;
                    //var isFinish = Guid.Empty;
                    T_FM_NOTIFICATION_TASK task = null;
                    if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                    {
                        entity.STATUS = FOPreMeetingStatusEnum.审核中;
                        isSendApprove = true;
                        entity.APPROVECODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                        //isFinish = entity.TaskID;
                        if (entity.TaskID != Guid.Empty)
                        {
                            task = NotificationTaskService.GetEntityTask(entity.TaskID, "HM101_SHOWPRINT");
                            if (task.SOURCE_DATA_ID == null)
                                task.SOURCE_DATA_ID = entity.ID;
                        }
                    }
                    MFlowPermitService.InsertApprove(entity.APPROVECODE, "HM102", null, entity.ID, "HM101_SHOWPRINT", null, isSendApprove, () =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //保存主表
                        if (task != null)
                            UpdateEntityNoCommit(task);
                        if (files != null && files.Any())
                            BantchSaveEntityNoCommit(files);    //保存子表
                        if (riskDetail != null && riskDetail.Any())
                            BantchSaveEntityNoCommit(riskDetail);
                        if (identifyings != null && identifyings.Any())
                            BantchSaveEntityNoCommit(identifyings);
                        if (subIdentifyings != null && subIdentifyings.Any())
                            BantchSaveEntityNoCommit(subIdentifyings);
                        if (areas != null && areas.Any())
                            BantchSaveEntityNoCommit(areas);
                        if (users.Any())
                            BantchSaveEntityNoCommit(users);    //保存孙表
                    });
                    return true;
                });
            }
        }

        /// <summary>
        /// 审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("PersonalApprove")]
        public JsonActionResult<bool> PersonalApprove(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("HM/HMHazardTask/PersonalApprove", id);
            });
        }
        /// <summary>
        /// 获取个人的班组前会议活动
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetUserDealStatus")]
        public JsonActionResult<bool> GetUserDealStatus([FromBody] T_HM_HAZARD_TASK entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                BaseFilter filter = new BaseFilter(orgId);
                filter.Include = new string[] { "Nav_Detail.Nav_Users.Nav_User" };
                var model = GetEntity<T_HM_HAZARD_TASK>(t => t.ID == entity.ID, filter);
                //if (model.STATUS != FOPreMeetingStatusEnum.签到中)
                //return false;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var userBool = false;
                foreach (var detail in model.Nav_Detail)
                {
                    var count = detail.Nav_Users.Count(t => t.USER_ID == userID && t.DEAL_STATUS == 0);
                    if (count > 0)  //该用户在该记录中是否参与且未同意则显示同意按钮
                    {
                        userBool = true;
                        break;
                    }
                    else
                    {
                        userBool = false;
                    }
                }
                return userBool;

            });
        }
        /// <summary>
        /// 签到
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("UserSignin")]
        public JsonActionResult<bool> UserSignin([FromBody] T_HM_HAZARD_TASK model)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var allTaskUsers = GetEntities<T_HM_HAZARD_TASK_DETAIL_USER>(t => t.Nav_Task_Detail.TASK_ID == model.ID, new BaseFilter(orgId));
                var filter = new BaseFilter(orgId);
                filter.Include = new string[] { "Nav_Identifyings", "Nav_Area", "Nav_User" };
                var allTaskDetails = GetEntities<T_HM_HAZARD_TASK_DETAIL>(t => t.TASK_ID == model.ID, filter);
                var currUser = allTaskUsers.Where(t => t.USER_ID == userID);
                var currDetail = allTaskDetails.Where(t => t.RECORD_USER_ID == userID);

                foreach (var useritem in currUser)
                {
                    useritem.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                }
                foreach (var useritem in currDetail)
                {
                    useritem.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                }
                var todoCount = currDetail.Count(t => t.DEAL_STATUS == 0);
                T_HM_HAZARD_TASK entity = null;
                List<T_HM_HAZARD_RECORD> hazardRecords = new List<T_HM_HAZARD_RECORD>();
                List<T_HM_HAZARD_RECORD_USER> allUsers = new List<T_HM_HAZARD_RECORD_USER>();
                List<T_HM_HAZARD_RECORD_FILE> allFiles = new List<T_HM_HAZARD_RECORD_FILE>();
                List<T_HM_HAZARD_RECORD_DETAIL> details = new List<T_HM_HAZARD_RECORD_DETAIL>();
                List<T_FM_NOTIFICATION_TASK> sendNotices = null;
                T_FM_NOTIFICATION_TASK finishNotice = null;
                if (todoCount == 0 && currDetail.Any())
                {
                    entity = GetEntity<T_HM_HAZARD_TASK>(model.ID, new string[] { "Nav_Files", "Nav_Areas.Nav_Area", "Nav_Identifyings.Nav_Identifying" });
                    var noticeTitles = new List<string>();
                    var noticeUserIds = new List<Guid>();
                    var noticeUserNames = new List<string>();
                    var noticeDataIds = new List<Guid>();
                    T_HM_HAZARD_RECORD hazardRecord = new T_HM_HAZARD_RECORD();
                    hazardRecord.ID = Guid.NewGuid();
                    var sysFilter1 = new SystemCodeFilter();
                    sysFilter1.CodeType = (int)PFCodeRuleType.风险辨识记录编号;
                    sysFilter1.Count = 1;
                    sysFilter1.OrgId = orgId;
                    var codes1 = CodeRuleService.NewGenSerial(sysFilter1);
                    hazardRecord.CODE = codes1;
                    hazardRecord.INITIATING_DEPARTMENT = entity.INITIATING_DEPARTMENT;
                    hazardRecord.NOTE_TAKER_ID = userID;
                    hazardRecord.STATUS = (int)FOPreMeetingStatusEnum.草稿;
                    hazardRecord.LEVEL = FMDepartmentType.部门;
                    hazardRecord.START_TIME = entity.START_TIME;
                    hazardRecord.END_TIME = entity.END_TIME;
                    hazardRecord.ORG_ID = orgId;
                    hazardRecord.LIABLE_USER_ID = entity.LIABLE_USER_ID;
                    hazardRecord.PLAN_ID = entity.PLAN_ID;
                    hazardRecord.AREAS = string.Join("、", entity.Nav_Areas.Select(t => t.Nav_Area.NAME));
                    hazardRecord.IDENTIFYINGS = string.Join("、", entity.Nav_Identifyings.Select(t => t.Nav_Identifying.NAME));
                    hazardRecords.Add(hazardRecord);
                    noticeTitles.Add("职业危害辨识记录" + DateTime.Now.ToShortDateString());
                    noticeUserIds.Add((Guid)userID);
                    noticeUserNames.Add(currDetail.FirstOrDefault().Nav_User.NAME);
                    noticeDataIds.Add(hazardRecord.ID);
                    //添加辨识对象
                    if (currDetail.Any())
                    {
                        var areaList = currDetail.Select(t => t.AREA_ID).ToList();
                        BaseFilter baseFilter = new BaseFilter(orgId);
                        var dangerDB = this.GetEntities<T_HM_EVALUATE_HAZARD>(t => areaList.Contains((Guid)t.AREA_ID) && t.STATUS == (int)HMOperationStepEnum.有效, baseFilter);
                        foreach (var detail in currDetail)
                        {
                            var dangerDBAreas = dangerDB.Where(t => t.AREA_ID == detail.AREA_ID && detail.Nav_Identifyings.Select(x => x.ID).Contains(t.IDENTIFYING_ID));
                            if (dangerDBAreas.Any())
                            {
                                foreach (var danger in dangerDBAreas)
                                {
                                    T_HM_HAZARD_RECORD_DETAIL recordDetail = new T_HM_HAZARD_RECORD_DETAIL();
                                    recordDetail.ID = Guid.NewGuid();
                                    recordDetail.RECORD_ID = hazardRecord.ID;
                                    recordDetail.AREA_ID = detail.AREA_ID;
                                    recordDetail.IDENTIFYING_ID = danger.IDENTIFYING_ID;
                                    recordDetail.ORG_ID = orgId;
                                    recordDetail.MODIFY_TYPE = HMModifyEnum.数据库;
                                    recordDetail.EXPOSURE_LIMIT_VALUE = danger.EXPOSURE_LIMIT_VALUE;
                                    recordDetail.EXPOSURE_NUMBER = danger.EXPOSURE_NUMBER;
                                    recordDetail.EXPOSURE_TIME = danger.EXPOSURE_TIME;
                                    recordDetail.EVALUATE_HAZARD_ID = danger.ID;
                                    recordDetail.HAZARD_POSITION = danger.HAZARD_POSITION;
                                    recordDetail.OCCUPATIONALRISK_ID = danger.OCCUPATIONALRISK_ID;
                                    details.Add(recordDetail);
                                }
                            }
                            var taskUsers = allTaskUsers.Where(t => t.TASK_DETAIL_ID == detail.ID);
                            foreach (var user in taskUsers)
                            {
                                T_HM_HAZARD_RECORD_USER recordUser = new T_HM_HAZARD_RECORD_USER();
                                recordUser.RECORD_ID = hazardRecord.ID;
                                recordUser.AREA_ID = detail.AREA_ID;
                                recordUser.USER_ID = user.USER_ID;
                                recordUser.ORG_ID = detail.ORG_ID;
                                if (user.USER_ID != userID)
                                {
                                    recordUser.DEAL_STATUS = FOUserShiftStatusEnum.待处理;
                                }
                                else
                                {
                                    recordUser.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                                }
                                allUsers.Add(recordUser);
                            }
                        }
                    }
                    //添加附件
                    if (entity.Nav_Files != null)
                    {
                        foreach (var fileitem in entity.Nav_Files)
                        {
                            T_HM_HAZARD_RECORD_FILE file = new T_HM_HAZARD_RECORD_FILE();
                            file.RECORD_ID = hazardRecord.ID;
                            file.IMG_FILE_ID = (Guid)fileitem.IMG_FILE_ID;
                            file.ORG_ID = orgId;
                            allFiles.Add(file);
                        }
                    }
                    var isallDone = allTaskUsers.Where(t => t.DEAL_STATUS == 0);
                    if (isallDone == null)
                    {
                        entity.STATUS = FOPreMeetingStatusEnum.归档;
                    }
                    sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(noticeTitles, noticeDataIds, orgId, noticeUserIds, noticeUserNames, DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(7).ToShortDateString() + " 23:59:59"), 0, "HM100");
                }
                if (model.TaskID != null)
                {
                    finishNotice = NotificationTaskService.FOGetTaskFinishModel(model.TaskID, model.ID);
                }
                UnifiedCommit(() =>
                {
                    if (currUser.Any())
                        BantchUpdateEntity(currUser, "DEAL_STATUS");
                    if (currDetail.Any())
                        BantchUpdateEntity(currDetail, "DEAL_STATUS");
                    if (entity != null)
                        UpdateEntityNoCommit(entity, "STATUS");
                    if (hazardRecords != null && hazardRecords.Any())
                        BantchAddEntityNoCommit(hazardRecords);
                    if (allUsers != null && allUsers.Any())
                        BantchAddEntityNoCommit(allUsers);
                    if (allFiles != null && allFiles.Any())
                        BantchAddEntityNoCommit(allFiles);
                    if (details != null && details.Any())
                        BantchAddEntityNoCommit(details);
                    if (sendNotices != null && sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                });
                return true;
            });
        }
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedArea")]
        public PagedActionResult<T_HM_RISK_AREA> OrderPagedArea([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_HM_RISK_AREA>((result) =>
            {
                if (pageFilter.Parameter1 != null)
                {
                    BaseFilter baseFilter = new BaseFilter(pageFilter.GetOrgId());
                    baseFilter.Include = new string[] { "Nav_Area" };
                    var info = GetEntities<T_HM_HAZARD_TASK_AREA>(t => t.TASK_ID == Guid.Parse(pageFilter.Parameter1), baseFilter).Select(e => e.Nav_Area).ToList();
                    if (info.Count == 0)
                    {
                        info = GetEntities<T_HM_RISK_AREA>(null, pageFilter).ToList();
                    }
                    result.TotalCount = info.Count;
                    result.Data = info.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit).ToList<T_HM_RISK_AREA>();
                }
                else
                {
                    var info = GetEntities<T_HM_RISK_AREA>(null, pageFilter).ToList();
                    result.TotalCount = info.Count;
                    result.Data = info.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit).ToList<T_HM_RISK_AREA>();
                }
            });
        }
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("HMOrderPaged")]
        public PagedActionResult<T_HM_HAZARD_TASK> HMOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_HM_HAZARD_TASK>();
            var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var admiId = this.GetEntity<T_FM_USER>(t => t.CODE == "admin" && t.ENABLE_STATUS == 0)?.ID;
            var currDep = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value;
            var AHDepartment = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人").DEPARTMENT_ID;
            if (loginUserId == null || loginUserId == admiId || currDep == AHDepartment)
            {
                result = this.GetOrderPageEntities<T_HM_HAZARD_TASK>(null, pageFilter);
            }
            else
            {
                var loginDepartmentId = this.GetEntity<T_FM_USER>(t => t.ID == loginUserId && t.ENABLE_STATUS == 0)?.DEPARTMENT_ID;
                List<Guid> departmentId = new List<Guid>();
                departmentId.Add((Guid)loginDepartmentId);
                List<Guid> departmentIds = new List<Guid>() { currDep };
                DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, departmentId, ref departmentIds);
                if (departmentIds != null && departmentIds.Any())
                {
                    result = this.GetOrderPageEntities<T_HM_HAZARD_TASK>(t => (departmentIds.Contains((Guid)t.INITIATING_DEPARTMENT)), pageFilter);//|| dataIds.Contains(t.ID)
                }
                else
                    result.Data = null;
            }
            return result;
        }
    }
}
