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

namespace APT.SC.WebApi.Controllers.Api.OH
{
    [Route("api/OH/OHHealthExamCycle")]
    public class OHHealthExamCycleController : AuthorizeApiController<T_OH_HEALTH_EXAM_CYCLE>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IAEAccidentEventReportService AccidentEventReportService { get; set; }
        public OHHealthExamCycleController(IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IAEAccidentEventReportService accidentEventReportService)
        {
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            AccidentEventReportService = accidentEventReportService;
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedDepWorkshop")]
        public PagedActionResult<T_FM_DEPARTMENT> OrderPagedDepWorkshop([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_FM_DEPARTMENT> result)
            {
                bool isSentDepID = false;
                if (pageFilter.FilterGroup.Rules.Count == 2)
                {
                    foreach (var item in pageFilter.FilterGroup.Rules)
                    {
                        if (item.Field == "PARENT_ID" && item.Value != null)
                        {
                            isSentDepID = true;
                        }
                    }
                }
                if (isSentDepID)
                {
                    //如果没有部门 返回空
                    PagedActionResult<T_FM_DEPARTMENT> orderPageEntities = GetOrderPageEntities<T_FM_DEPARTMENT>(null, pageFilter, null);
                    result.Data = orderPageEntities.Data;
                    result.TotalCount = orderPageEntities.TotalCount;
                }
                else
                {
                    result.Data = new List<T_FM_DEPARTMENT>();
                    result.TotalCount = 0;
                }
            });
        }

        /// <summary>
        /// 体检周期表 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_OH_HEALTH_EXAM_CYCLE entity)
        {
            #region       新版

            return SafeExecute<bool>(() =>
            {
                var listOcc = entity.Nav_ListOccHazard;
                entity.Nav_ListOccHazard = null;
                var listDepartmentInfo = entity.Nav_ListDepartmentInfo;
                entity.Nav_ListDepartmentInfo = null;

                List<T_OH_HEALTH_EXAM_CYCLE_DEPARTMENTINFO_POST> listDepartmentInfoPost = new List<T_OH_HEALTH_EXAM_CYCLE_DEPARTMENTINFO_POST>();

                //var listPost = entity.Nav_ListSCPost;
                //entity.Nav_ListSCPost = null;
                //if (listPost == null || !listPost.Any() || listPost.Where(e => e.IS_DELETED) == null)
                //{
                //    throw new Exception("请选择岗位");
                //}
                if (listOcc == null || !listOcc.Any())
                {
                    throw new Exception("请选择职业危害类型");
                }
                if (string.IsNullOrEmpty(entity.HEALTH_EXAM_CONTENT))
                {
                    throw new Exception("请填写体检项目");
                }
                else if (entity.HEALTH_EXAM_CONTENT.Length > 200)
                {
                    throw new Exception("体检项目不能超过200个字符");
                }
                if (entity.HEALTH_EXAM_CYCLE < 1)
                {
                    throw new Exception("体检周期不能小于1");
                }
                else if (entity.HEALTH_EXAM_CYCLE > 12)
                {
                    throw new Exception("体检周期不能大于12");
                }

                if (listDepartmentInfo == null || !listDepartmentInfo.Any())
                {
                    throw new Exception("请选择部门岗位信息！");
                }
                var listDepartmentInfoS = listDepartmentInfo.ToList();
                for (int i = 0; i < listDepartmentInfoS.Count(); i++)
                {
                    if (!listDepartmentInfoS[i].DEPARTMENT_ID.HasValue)
                    {
                        throw new Exception("请选择行【" + (i + 1) + "】的部门！");
                    }
                    if (listDepartmentInfoS[i].Nav_ListDepartmentInfoPost == null || !listDepartmentInfoS[i].Nav_ListDepartmentInfoPost.Any())
                    {
                        throw new Exception("请选择行【" + (i + 1) + "】的岗位！");
                    }
                    else
                    {
                        foreach (var item in listDepartmentInfoS[i].Nav_ListDepartmentInfoPost)
                        {
                            listDepartmentInfoPost.Add(item);
                            item.Nav_Post = null;
                        }
                        listDepartmentInfoS[i].Nav_ListDepartmentInfoPost = null;
                    }
                }

                if (listOcc != null && listOcc.Any())
                {
                    foreach (var item in listOcc)
                    {
                        item.Nav_Hazard = null;
                    }
                }
                if (listDepartmentInfoPost == null || !listDepartmentInfoPost.Any())
                {
                    throw new Exception("岗位");
                }

                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //事故事件上报
                    if (listOcc != null && listOcc.Any())//职业危害类型
                        BantchSaveEntityNoCommit(listOcc);
                    if (listDepartmentInfo != null && listDepartmentInfo.Any())//职业危害类型
                        BantchSaveEntityNoCommit(listDepartmentInfo);
                    if (listDepartmentInfoPost != null && listDepartmentInfoPost.Any())//职业危害类型
                        BantchSaveEntityNoCommit(listDepartmentInfoPost);
                    //if (listPost != null && listPost.Any())//岗位
                    //    BantchSaveEntityNoCommit(listPost);
                });

                return true;
            });

            #endregion

            #region       旧版
            //return SafeExecute<bool>(() =>
            //{
            //    if (entity.DEPARTMENT_ID == null)
            //    {
            //        throw new Exception("请选择部门");
            //    }

            //    var listOcc = entity.Nav_ListOccHazard;
            //    var listPost = entity.Nav_ListSCPost;
            //    entity.Nav_ListOccHazard = null;
            //    entity.Nav_ListSCPost = null;
            //    if (listPost == null || !listPost.Any() || listPost.Where(e => e.IS_DELETED) == null)
            //    {
            //        throw new Exception("请选择岗位");
            //    }
            //    //if (listOcc == null || !listOcc.Any())
            //    //{
            //    //    throw new Exception("请选择职业危害类型");
            //    //}
            //    if (string.IsNullOrEmpty(entity.HEALTH_EXAM_CONTENT))
            //    {
            //        throw new Exception("请填写体检项目");
            //    }
            //    else if (entity.HEALTH_EXAM_CONTENT.Length > 200)
            //    {
            //        throw new Exception("体检项目不能超过200个字符");
            //    }
            //    if (entity.HEALTH_EXAM_CYCLE < 1)
            //    {
            //        throw new Exception("体检周期不能小于1");
            //    }
            //    var listPostID = listPost.Where(e => !e.IS_DELETED).Select(e => e.SC_POST_ID);


            //    //车间 岗位 职业危害类型 不能重复
            //    Expression<Func<T_OH_HEALTH_EXAM_CYCLE, bool>> expression = e => e.ID != entity.ID && e.DEPARTMENT_ID == entity.DEPARTMENT_ID;
            //    if (entity.DEPARTMENT_ID_WORKSHOP.HasValue)
            //    {
            //        expression.And(e => e.DEPARTMENT_ID_WORKSHOP == entity.DEPARTMENT_ID_WORKSHOP);
            //    }

            //    var listCycle = GetEntities<T_OH_HEALTH_EXAM_CYCLE>(expression, null, new string[] { "Nav_ListSCPost.Nav_SCPost", "Nav_ListOccHazard.Nav_Hazard" });
            //    if (listCycle != null && listCycle.Any())
            //    {
            //        //岗位 
            //        //职业危害
            //        //不允许 同时 重复
            //        foreach (var item in listCycle)
            //        {
            //            var checkPost = item.Nav_ListSCPost.Where(e => !e.IS_DELETED && listPostID.Contains(e.SC_POST_ID));
            //            if (checkPost != null && checkPost.Any())
            //            {
            //                //有重复的岗位
            //                if (listOcc != null && listOcc.Any())
            //                {
            //                    //主表 判断查询的 都有职业危害类型
            //                    var listHAZARD_ID = item.Nav_ListOccHazard.Where(e => !e.IS_DELETED).Select(e => e.HAZARD_ID);
            //                    var repHazard = listOcc.Where(e => !e.IS_DELETED && listHAZARD_ID.Contains(e.HAZARD_ID));
            //                    if (repHazard != null && repHazard.Any())
            //                    {
            //                        var strRepHazard = string.Join(",", repHazard.ToList().Select(e => e.Nav_Hazard.NAME).ToList());
            //                        var strRepPost = string.Join(",", checkPost.ToList().Select(e => e.Nav_SCPost.NAME).ToList());
            //                        throw new Exception("此信息与系统中的【部门、车间、岗位(" + strRepPost + ")、职业危害类型(" + strRepHazard + ")】重复！");
            //                    }
            //                }
            //                else
            //                {
            //                    var strRepPost = string.Join(",", checkPost.ToList().Select(e => e.Nav_SCPost.NAME).ToList());
            //                    //没有职业危害类型
            //                    if (item.Nav_ListOccHazard == null || !item.Nav_ListOccHazard.Any())
            //                    {
            //                        //添加的 体检周期表  在这个岗位 没有 添加职业危害重复
            //                        throw new Exception("此信息与系统中的【部门、车间、岗位(" + strRepPost + ")】重复！");
            //                    }
            //                }
            //            }
            //        }
            //    }

            //    if (listOcc != null && listOcc.Any())
            //    {
            //        foreach (var item in listOcc)
            //        {
            //            item.Nav_Hazard = null;
            //        }
            //    }
            //    foreach (var item in listPost)
            //    {
            //        item.Nav_SCPost = null;
            //    }
            //    this.UnifiedCommit(() =>
            //    {
            //        if (entity != null)
            //            UpdateEntityNoCommit(entity);   //事故事件上报
            //        if (listOcc != null && listOcc.Any())//职业危害类型
            //            BantchSaveEntityNoCommit(listOcc);
            //        if (listPost != null && listPost.Any())//岗位
            //            BantchSaveEntityNoCommit(listPost);
            //    });

            //    return true;
            //}); 
            #endregion

        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedSub")]
        public PagedActionResult<T_OH_HEALTH_EXAM_CYCLE> OrderPagedSub([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_OH_HEALTH_EXAM_CYCLE> result)
            {
                //pageFilter.Include.Add("Nav_ListSCPost.Nav_SCPost");
                //pageFilter.Include.Add("Nav_ListOccHazard.Nav_Hazard");

                PagedActionResult<T_OH_HEALTH_EXAM_CYCLE> orderPageEntities = GetOrderPageEntities<T_OH_HEALTH_EXAM_CYCLE>(null, pageFilter, null);
                result.Data = orderPageEntities.Data;
                if (orderPageEntities.TotalCount > 0)
                {
                    var listID = result.Data.Select(e => e.ID);
                    var listPost = GetEntities<T_OH_HEALTH_EAXM_CYCLE_POST_MID>(e => listID.Contains(e.RECORD_ID), null, new string[] { "Nav_SCPost" });
                    var listOccHazard = GetEntities<T_OH_HEALTH_EAXM_CYCLE_OCC_HAZARD_MID>(e => listID.Contains(e.RECORD_ID), null, new string[] { "Nav_Hazard" });

                    int count = result.Data.Count();
                    foreach (var item in result.Data)
                    {
                        var listTOccHazard = listOccHazard.Where(e => e.RECORD_ID == item.ID);
                        if (listTOccHazard != null && listTOccHazard.Any())
                        {
                            if (item.OCCHAZARD == null)
                            {
                                item.OCCHAZARD = "";
                            }
                            foreach (var itemOCC in listTOccHazard)
                            {
                                item.OCCHAZARD += (item.OCCHAZARD.Length > 0 ? "，" : "") + itemOCC.Nav_Hazard.NAME;
                            }
                        }

                        var listTPost = listPost.Where(e => e.RECORD_ID == item.ID);
                        if (listTPost != null && listTPost.Any())
                        {
                            //TODO
                            //责任制岗位修改 0511
                            //if (item.SCPost == null)
                            //{
                            //    item.SCPost = "";
                            //}
                            //foreach (var itemPost in listTPost)
                            //{
                            //    item.SCPost += (item.SCPost.Length > 0 ? "，" : "") + itemPost.Nav_SCPost.NAME;
                            //}
                        }
                    }
                }
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }
    }
}