using APT.BaseData.Domain.Entities.FM;
using Microsoft.AspNetCore.Mvc;
using APT.Infrastructure.Api;
using System;
using System.Collections.Generic;
using APT.Infrastructure.Core;
using APT.BaseData.Domain.Enums;
using APT.SC.WebApi.Controllers.Api.BIController;
using Microsoft.Extensions.DependencyModel;
using APT.BaseData.Domain.Entities.OP;
using APT.Migrations;
using NPOI.SS.Formula.Functions;
using APT.MS.Domain.Entities.SE;
using System.Linq;
using System.Linq.Expressions;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Enums;
using APT.MS.Domain.Entities.SK;
using APT.BaseData.Domain.Enums.PF;
using APT.Utility;

namespace APT.SC.WebApi.Controllers.Api.BI
{
    /// <summary>
    ///  年度监测汇总
    /// </summary>
    [Route("api/BI/H5Controller")]
    public class H5Controller : APTApiController<T_FM_USER>
    {
        public class DataReturn
        {
            public int code { get; set; }
            public string msg { get; set; }
            public object data { get; set; }
        }
        public class Menu
        {
            public string name { get; set; }
            public string iconName { get; set; }
            public string url { get; set; }
            public Guid ORG_ID { get; set; }

            /// <summary>
            /// 类型 5  10  15  20
            /// </summary>
            public int TYPE { get; set; }

        }
        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <param name="OrgId">分页过滤实体</param>
        /// <returns></returns>
        [HttpGet, Route("GetMenu")]
        public DataReturn GetMenu(string OrgId)
        {
            DataReturn DataReturn = new DataReturn()
            {
                msg = "",
                code = 200
            };
            List<Menu> menus = new List<Menu>();
            Guid ORG_ID = Guid.Empty;
            if (string.IsNullOrEmpty(OrgId))
            {
                ORG_ID = new Guid("B043B28B-BBC3-C452-6052-4FBA1457ABFA");
            }
            else
            {
                ORG_ID = new Guid(OrgId);
            }
            Menu menu = new Menu();
            menu.name = "新增用户";
            menu.iconName = "man-add";
            menu.url = "/pages/apply/index";
            menu.ORG_ID = ORG_ID;
            menu.TYPE = 2;
            menus.Add(menu);


            Menu menuPerson = new Menu();
            menuPerson.name = "当班员工";
            menuPerson.iconName = "order";
            menuPerson.url = "/pages/apply/user";
            menuPerson.ORG_ID = ORG_ID;
            menuPerson.TYPE = 20;
            menus.Add(menuPerson);

            Menu menuQrcode = new Menu();
            menuQrcode.name = "二维码生成器";
            menuQrcode.iconName = "scan";
            menuQrcode.url = "/pages/apply/qrcodeMake";
            menuQrcode.ORG_ID = ORG_ID;
            menuQrcode.TYPE = 5;
            menus.Add(menuQrcode);

            Menu menuEvaluation = new Menu();
            menuEvaluation.name = "风险查看";
            menuEvaluation.iconName = "eye";
            menuEvaluation.url = "/pages/apply/viewEvaluation";
            menuEvaluation.ORG_ID = ORG_ID;
            menuEvaluation.TYPE = 10;
            menus.Add(menuEvaluation);

            Menu menuRisk = new Menu();
            menuRisk.name = "隐患查看";
            menuRisk.iconName = "bell";
            menuRisk.url = "/pages/apply/viewRisk";
            menuRisk.ORG_ID = ORG_ID;
            menuRisk.TYPE = 10;
            menus.Add(menuRisk);

            //Menu menuCheck = new Menu();
            //menuCheck.name = "检查库查看";
            //menuCheck.iconName = "file-text";
            //menuCheck.url = "/pages/apply/viewCheck";
            //menuCheck.ORG_ID = ORG_ID;
            //menuCheck.TYPE = 10;
            //menus.Add(menuCheck);

            Menu menuVideo = new Menu();
            menuVideo.name = "视频查看";
            menuVideo.iconName = "eye";
            menuVideo.url = "/pages/apply/viewVideo";
            menuVideo.ORG_ID = ORG_ID;
            menuVideo.TYPE = 10;
            menus.Add(menuVideo);

            DataReturn.data = menus;
            return DataReturn;
        }
        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="model">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("RegisterUser")]
        public DataReturn RegisterUser([FromBody] RegisterUserModel model)
        {
            DataReturn DataReturn = new DataReturn();
            if (model.Name == null || model.Phone == null)
            {
                DataReturn.msg = "请填写信息！";
                DataReturn.code = 500;
                return DataReturn;
            }
            if (model.ORG_ID == Guid.Empty)
            {
                DataReturn.msg = "获取公司信息失败！";
                DataReturn.code = 500;
                return DataReturn;
            }
            if (model.DEPARTMENT_ID == null || (model.DEPARTMENT_ID.HasValue && model.DEPARTMENT_ID.Value == Guid.Empty))
            {
                DataReturn.msg = "请选择入职组织！";
                DataReturn.code = 500;
                return DataReturn;
            }

            var Tenant = this.Request.Headers["Tenant"];
            Guid orgId = model.ORG_ID;
            var isrepeat = GetEntity<T_FM_USER>(t => t.CODE == model.Phone);
            if (isrepeat != null)
            {
                DataReturn.msg = "该账户已注册！";
                DataReturn.code = 500;
                return DataReturn;
            }
            T_FM_PERSON newPerson = new T_FM_PERSON();
            newPerson.ID = Guid.NewGuid();
            newPerson.CODE = model.Phone;
            newPerson.NAME = model.Name;
            newPerson.SEX = model.Sex;
            newPerson.TEL = model.Phone;
            newPerson.ORG_ID = orgId;
            newPerson.DEPARTMENT_ID = model.DEPARTMENT_ID;
            if (model.POST_ID.HasValue && model.POST_ID.Value != Guid.Empty)
            {
                newPerson.POST_ID = model.POST_ID;
            }

            T_FM_USER newUser = new T_FM_USER();
            newUser.ID = Guid.NewGuid();
            newUser.CODE = model.Phone;
            newUser.NAME = model.Name;
            newUser.SEX = model.Sex;
            newUser.PHONE = model.Phone;
            newUser.ID_CARD = model.ID_CARD;
            newUser.ENTRYTIME = model.InTime;
            newUser.WORKINGYEAR = model.WORKINGYEAR;
            newUser.PERSON_ID = newPerson.ID;
            newUser.PASSWORD = "E10ADC3949BA59ABBE56E057F20F883E";
            newUser.ORG_ID = orgId;
            newUser.DEPARTMENT_ID = model.DEPARTMENT_ID;
            newUser.NUM = 1000;//按 NUM 排序 靠后
            //newUser.ENABLE_STATUS = 1;//先配置不可用 三级安全教育完成后 再启用

            T_SE_USER_TEMP newTemp = new T_SE_USER_TEMP();
            newTemp.ID = Guid.NewGuid();
            newTemp.USER_ID = newUser.ID;
            newTemp.ORG_ID = orgId;

            var listDefault = GetEntities<T_FM_ROLE>(e => e.ISDEFAULT && !e.IS_DELETED, null, null);
            List<T_FM_USER_BELONG_ROLE> listRole = new List<T_FM_USER_BELONG_ROLE>();
            if (listDefault != null && listDefault.Count() > 0)
            {
                T_FM_USER_BELONG_ROLE modelRole = null;
                foreach (var item in listDefault)
                {
                    modelRole = new T_FM_USER_BELONG_ROLE();
                    modelRole.USER_ID = newUser.ID;
                    modelRole.BELONG_ROLE_ID = item.ID;
                    modelRole.ORG_ID = orgId;
                    listRole.Add(modelRole);
                }
            }
            else
            {
                var role1 = this.GetEntity<T_FM_ROLE>(t => t.NAME == "APP用户");
                var role2 = this.GetEntity<T_FM_ROLE>(t => t.NAME == "作业员");
                T_FM_USER_BELONG_ROLE belongRole1 = null;
                T_FM_USER_BELONG_ROLE belongRole2 = null;
                if (role1 != null)
                {
                    belongRole1 = new T_FM_USER_BELONG_ROLE();
                    belongRole1.USER_ID = newUser.ID;
                    belongRole1.BELONG_ROLE_ID = role1.ID;
                    belongRole1.ORG_ID = orgId;
                    listRole.Add(belongRole1);
                }
                if (role2 != null)
                {
                    belongRole2 = new T_FM_USER_BELONG_ROLE();
                    belongRole2.USER_ID = newUser.ID;
                    belongRole2.BELONG_ROLE_ID = role2.ID;
                    belongRole2.ORG_ID = orgId;
                    listRole.Add(belongRole2);
                }
            }

            using (var context = new MigrationContext(ConfigurationManager.ConnectionStrings["default"]))
            {
                T_OP_ALLUSER alluser = new T_OP_ALLUSER();
                alluser.CODE = model.Phone;
                alluser.TENANT = Tenant;
                alluser.ORG_ID = orgId;
                alluser.PHONE = model.Phone;
                context.AddEntity(alluser);
                context.SaveChanges();
            }
            UnifiedCommit(() =>
            {
                if (newUser != null)
                    AddEntityNoCommit(newUser);
                if (newPerson != null)
                    AddEntityNoCommit(newPerson);
                //if (belongRole1 != null)
                //    AddEntityNoCommit(belongRole1);
                //if (belongRole2 != null)
                //    AddEntityNoCommit(belongRole2);
                if (listRole != null && listRole.Count() > 0)
                    BantchSaveEntityNoCommit(listRole);
                if (newTemp != null)
                    AddEntityNoCommit(newTemp);
            });
            DataReturn.msg = "";
            DataReturn.code = 200;
            return DataReturn;
        }
        //public DataReturn RegisterUser(string Name, int Sex, string Phone, string ID_CARD, DateTime InTime, int WORKINGYEAR)
        //{
        //    DataReturn DataReturn = new DataReturn();
        //    if (Name == null || Phone == null)
        //    {
        //        DataReturn.msg = "请填写信息！";
        //        DataReturn.code = 500;
        //        return DataReturn;
        //    }
        //    var Tenant = this.Request.Headers["Tenant"];
        //    Guid orgId = getOrgIdByTenant(Tenant);
        //    var isrepeat = GetEntity<T_FM_USER>(t => t.CODE == Phone);
        //    if (isrepeat != null)
        //    {
        //        DataReturn.msg = "该账户已注册！";
        //        DataReturn.code = 500;
        //        return DataReturn;
        //    }
        //    T_FM_PERSON newPerson = new T_FM_PERSON();
        //    newPerson.ID = Guid.NewGuid();
        //    newPerson.CODE = Phone;
        //    newPerson.NAME = Name;
        //    newPerson.SEX = Sex;
        //    newPerson.TEL = Phone;
        //    newPerson.ORG_ID = orgId;
        //    T_FM_USER newUser = new T_FM_USER();
        //    newUser.ID = Guid.NewGuid();
        //    newUser.CODE = Phone;
        //    newUser.NAME = Name;
        //    newUser.SEX = Sex;
        //    newUser.PHONE = Phone;
        //    newUser.ID_CARD = ID_CARD;
        //    newUser.ENTRYTIME = InTime;
        //    newUser.WORKINGYEAR = WORKINGYEAR;
        //    newUser.PERSON_ID = newPerson.ID;
        //    newUser.PASSWORD = "E10ADC3949BA59ABBE56E057F20F883E";
        //    newUser.ORG_ID = orgId;
        //    T_SE_USER_TEMP newTemp = new T_SE_USER_TEMP();
        //    newTemp.ID = Guid.NewGuid();
        //    newTemp.USER_ID = newUser.ID;
        //    newTemp.ORG_ID = orgId;
        //    var role1 = this.GetEntity<T_FM_ROLE>(t => t.NAME == "APP用户");
        //    var role2 = this.GetEntity<T_FM_ROLE>(t => t.NAME == "作业员");
        //    T_FM_USER_BELONG_ROLE belongRole1 = null;
        //    T_FM_USER_BELONG_ROLE belongRole2 = null;
        //    if (role1 != null)
        //    {
        //        belongRole1 = new T_FM_USER_BELONG_ROLE();
        //        belongRole1.USER_ID = newUser.ID;
        //        belongRole1.BELONG_ROLE_ID = role1.ID;
        //        belongRole1.ORG_ID = orgId;
        //    }
        //    if (role2 != null)
        //    {
        //        belongRole2 = new T_FM_USER_BELONG_ROLE();
        //        belongRole2.USER_ID = newUser.ID;
        //        belongRole2.BELONG_ROLE_ID = role2.ID;
        //        belongRole2.ORG_ID = orgId;
        //    }
        //    using (var context = new MigrationContext(ConfigurationManager.ConnectionStrings["default"]))
        //    {
        //        T_OP_ALLUSER alluser = new T_OP_ALLUSER();
        //        alluser.CODE = Phone;
        //        alluser.TENANT = Tenant;
        //        alluser.ORG_ID = orgId;
        //        alluser.PHONE = Phone;
        //        context.AddEntity(alluser);
        //        context.SaveChanges();
        //    }
        //    UnifiedCommit(() =>
        //    {
        //        if (newUser != null)
        //            AddEntityNoCommit(newUser);
        //        if (newPerson != null)
        //            AddEntityNoCommit(newPerson);
        //        if (belongRole1 != null)
        //            AddEntityNoCommit(belongRole1);
        //        if (belongRole2 != null)
        //            AddEntityNoCommit(belongRole2);
        //        if (newTemp != null)
        //            AddEntityNoCommit(newTemp);
        //    });
        //    DataReturn.msg = "";
        //    DataReturn.code = 200;
        //    return DataReturn;
        //}
        public class RegisterUserModel
        {
            public string Name { get; set; }
            public int Sex { get; set; }
            public string Phone { get; set; }
            public string ID_CARD { get; set; }
            public DateTime InTime { get; set; }
            public int WORKINGYEAR { get; set; }
            public Guid ORG_ID { get; set; }
            public Guid? DEPARTMENT_ID { get; set; }
            public Guid? POST_ID { get; set; }
        }

        //private Guid getOrgIdByTenant(string Tenant)
        //{
        //    Guid orgId = Guid.Empty;
        //    if (Tenant.Equals("0001"))//XLK
        //    {
        //        orgId = Guid.Parse("b043b28b-bbc3-c452-6052-4fba1457abfa");
        //    }
        //    else if (Tenant.Equals("A0000024"))//豫鹭
        //    {
        //        orgId = Guid.Parse("d9871ba8-0eec-9e4a-bb87-7d5a540d8913");
        //    }
        //    else if (Tenant.Equals("A0000025"))//金鼎
        //    {
        //        orgId = Guid.Parse("8b3c41aa-51b1-7ce9-1879-248a038c1b5c");
        //    }
        //    else if (Tenant.Equals("0002"))//龙岩稀土
        //    {
        //        orgId = Guid.Parse("8f1cf418-8bf3-ea3f-7a6d-fc5d61247008");
        //    }
        //    return orgId;
        //}


        #region     当班工作人员


        /// <summary>
        /// 获取当班员工
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("WorkerScheduling")]
        public JsonActionResult<WorkerSchedulingResult> WorkerScheduling([FromBody] KeywordFilter filter)
        {
            return SafeExecute<WorkerSchedulingResult>(() =>
            {
                WorkerSchedulingResult result = new WorkerSchedulingResult();
                Guid DEPARTMENT_ID = Guid.Empty;
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    try
                    {
                        DEPARTMENT_ID = new Guid(filter.Keyword);
                    }
                    catch
                    {
                        throw new Exception("传参有误！");
                    }
                }
                else
                {
                    throw new Exception("未获取到传参！");
                }

                var dep = GetEntity<T_FM_DEPARTMENT>(DEPARTMENT_ID);
                if (dep == null)
                {
                    throw new Exception("获取组织信息失败！");
                }
                else if (dep.DEPARTMENT_TYPE != 2)
                {
                    throw new Exception("当班员工查询只能查询班组级信息，该组织为：" + ((FMDepartmentType)dep.DEPARTMENT_TYPE).GetDescription() + "！");
                }

                var team = GetEntity<T_FM_TEAM>(e => e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID.Value == DEPARTMENT_ID);
                if (team == null)
                {
                    throw new Exception("未获取到该班组的排班表信息！");
                }

                DateTime dtNow = DateTime.Now;
                var listSCH = GetEntities<T_FM_DEPARTMENT_SCHEDULING>(e => e.TEAM_ID.HasValue && e.TEAM_ID.Value == team.ID && e.START_TIME != e.END_TIME && e.DATE_TIME >= dtNow.Date && e.ENABLE_STATUS == 0 && !e.IS_DELETED, null, null).ToList();
                if (listSCH == null || listSCH.Count() < 1)
                {
                    throw new Exception("未获取到该班组的排班信息！");
                }
                var SCHEDULING = listSCH.FirstOrDefault(e => e.DATE_TIME == dtNow.Date);//当天排班
                if (SCHEDULING == null)
                {
                    //未获取到当天的排班
                    result.SchedulingType = "未排班";
                }
                else if (dtNow < SCHEDULING.START_TIME)
                {
                    //还没开始上班
                    result.SchedulingType = "未开始上班";
                }
                else if (dtNow > SCHEDULING.END_TIME)
                {
                    //已经下班了
                    result.SchedulingType = "已下班";
                }
                else
                {
                    result.SchedulingType = "正常";
                }
                var listSCHafter = listSCH.Where(e => e.DATE_TIME != dtNow.Date).OrderBy(e => e.DATE_TIME);
                if (listSCHafter != null && listSCHafter.Any())
                {
                    var listSCHNex = listSCHafter.ToList()[0];
                    result.SchedulingNEXTTIME = listSCHNex.START_TIME.ToString("yyyy-MM-dd HH:mm") + " ~ " + (listSCHNex.START_TIME.Date == listSCHNex.END_TIME.Date ? (listSCHNex.END_TIME.ToString("HH:mm")) : (listSCHNex.END_TIME.ToString("MM-dd HH:mm")));
                }

                List<Guid> listPersonID = null;
                if (SCHEDULING != null)
                {
                    result.START_TIME = SCHEDULING.START_TIME;
                    result.END_TIME = SCHEDULING.END_TIME;

                    var echdulingDetail = GetEntities<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(e => e.DEPARTMENT_SCHEDULING_ID == SCHEDULING.ID && !e.IS_DELETED, null, "Nav_Person");
                    if (echdulingDetail != null && echdulingDetail.Any())
                    {
                        result.LISTPERSON_SCHEDULING = new List<T_FM_PERSON>();
                        foreach (var item in echdulingDetail)
                        {
                            result.LISTPERSON_SCHEDULING.Add(item.Nav_Person);
                        }
                    }
                    listPersonID = result.LISTPERSON_SCHEDULING.Select(e => e.ID).ToList();
                }
                Expression<Func<T_FM_USER, bool>> expression = e => e.PERSON_ID.HasValue && e.DEPARTMENT_ID == DEPARTMENT_ID && !e.IS_DELETED && e.ENABLE_STATUS == 0;
                if (listPersonID != null && listPersonID.Count > 0)
                {
                    expression = expression.And(e => !listPersonID.Contains(e.PERSON_ID.Value));
                }
                result.LISTUSER_LEAVE = GetEntities<T_FM_USER>(expression, null, null);

                result.DEPARTMENT_NAME = dep.NAME;
                result.COUNT_WORKER = result.LISTPERSON_SCHEDULING.Count;
                result.COUNT_LEVEL = result.LISTUSER_LEAVE.Count();
                return result;
            });
        }

        /// <summary>
        /// 查询班组
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("PagedDep")]
        public PagedActionResult<T_FM_DEPARTMENT> PagedDep([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_FM_DEPARTMENT> result)
            {
                PagedActionResult<T_FM_DEPARTMENT> orderPageEntities = GetOrderPageEntities<T_FM_DEPARTMENT>(e => e.DEPARTMENT_TYPE == 20 && e.ENABLE_STATUS == 0 && !e.IS_DELETED, pageFilter, null);
                result.Data = orderPageEntities.Data;
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }

        /// <summary>
        /// 当班工作人员信息
        /// </summary>
        public class WorkerSchedulingResult
        {
            /// <summary>
            /// 部门名称
            /// </summary>
            public string DEPARTMENT_NAME { get; set; }
            /// <summary>
            /// 排班状态
            /// </summary>
            public string SchedulingType { get; set; }
            /// <summary>
            /// 当班人数
            /// </summary>
            public int COUNT_WORKER { get; set; }
            /// <summary>
            /// 组织人数
            /// </summary>
            public int COUNT_LEVEL { get; set; }
            /// <summary>
            /// 排班开始时间
            /// </summary>
            public DateTime? START_TIME { get; set; }

            /// <summary>
            ///排班结束时间 
            /// </summary>
            public DateTime? END_TIME { get; set; }

            /// <summary>
            /// 下次排班信息 年月日 开始时间 结束时间
            /// </summary>
            public string SchedulingNEXTTIME { get; set; }
            /// <summary>
            /// 当班人员
            /// </summary>
            public List<T_FM_PERSON> LISTPERSON_SCHEDULING { get; set; }

            /// <summary>
            /// 请假人员
            /// </summary>
            public IEnumerable<T_FM_USER> LISTUSER_LEAVE { get; set; }
        }

        #endregion

        #region    隐患查看

        /// <summary>
        /// 查询班组
        /// T_SK_HIDDEN_DANGER_RECTIFY_RECORD => T_SK_HIDDEN_DANGER_RECTIFY_RECORD
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("PagedRisk")]
        public PagedActionResult<T_SK_HIDDEN_DANGER_RECTIFY_RECORD> PagedRisk([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_SK_HIDDEN_DANGER_RECTIFY_RECORD> result)
            {
                Guid? RISK_AREA_ID = null;
                bool ISDOWN = false;
                if (!string.IsNullOrEmpty(pageFilter.Keyword))
                {
                    try
                    {
                        RISK_AREA_ID = new Guid(pageFilter.Keyword);
                    }
                    catch { }
                    pageFilter.Keyword = "";
                }
                if (pageFilter.Parameter1 != null && pageFilter.Parameter1 == "true")
                {
                    ISDOWN = true;
                }

                Expression<Func<T_SK_HIDDEN_DANGER_RECTIFY_RECORD, bool>> expression = e => !e.IS_DELETED && e.STATUS != PFStandardStatus.Archived;
                if (RISK_AREA_ID.HasValue)
                {
                    if (ISDOWN)
                    {
                        List<Guid> listResultID = new List<Guid>();
                        List<Guid> listID = new List<Guid>() { RISK_AREA_ID.Value };
                        GetDownRiskID(listID, ref listResultID);//递归获取区域ID
                        expression = expression.And(e => e.RISK_AREA_ID.HasValue && listResultID.Contains(e.RISK_AREA_ID.Value));
                    }
                    else
                    {
                        expression = expression.And(e => e.RISK_AREA_ID.HasValue && e.RISK_AREA_ID.Value == RISK_AREA_ID.Value);
                    }
                }

                PagedActionResult<T_SK_HIDDEN_DANGER_RECTIFY_RECORD> orderPageEntities = GetOrderPageEntities(expression, pageFilter, null);

                //Expression<Func<T_BS_RISK_SUBMIT_CONTENT, bool>> expression = e => !e.IS_DELETED && e.RiskContentState != 12 && e.CHECKCONTENT != null;
                //if (RISK_AREA_ID.HasValue)
                //{
                //    if (ISDOWN)
                //    {
                //        List<Guid> listResultID = new List<Guid>();
                //        List<Guid> listID = new List<Guid>() { RISK_AREA_ID.Value };
                //        GetDownRiskID(listID, ref listResultID);//递归获取区域ID
                //        expression = expression.And(e => e.RISK_AREA_ID.HasValue && listResultID.Contains(e.RISK_AREA_ID.Value));
                //    }
                //    else
                //    {
                //        expression = expression.And(e => e.RISK_AREA_ID.HasValue && e.RISK_AREA_ID.Value == RISK_AREA_ID.Value);
                //    }
                //}
                //PagedActionResult<T_BS_RISK_SUBMIT_CONTENT> orderPageEntities = GetOrderPageEntities(expression, pageFilter, null);

                result.Data = orderPageEntities.Data;
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }

        /// <summary>
        /// 底肥获取区域的下级
        /// </summary>
        /// <param name="listPARENT_ID"></param>
        /// <param name="listResult"></param>
        private void GetDownRiskID(IEnumerable<Guid> listPARENT_ID, ref List<Guid> listResult)
        {
            List<Guid> ids = new List<Guid>();
            //var listAreaIDDown = GetEntities<T_HM_RISK_AREA>(e => e.PARENT_ID.HasValue && listPARENT_ID.Contains(e.PARENT_ID.Value) && !e.IS_DELETED, null, null);
            var listAreaIDDown = GetEntities<T_SK_RISK_AREA>(e => e.PARENT_ID.HasValue && listPARENT_ID.Contains(e.PARENT_ID.Value) && !e.IS_DELETED, null, null);
            if (listResult == null)
            {
                listResult = new List<Guid>();
            }
            listResult.AddRange(listPARENT_ID);//每次把入参存起来
            if (listAreaIDDown != null && listAreaIDDown.Count() > 0)
            {
                var listIDPass = listAreaIDDown.Select(e => e.ID);
                GetDownRiskID(listIDPass, ref listResult);
            }
            else
            {
                return;
            }
        }


        /// <summary>
        /// 排序分页查询数据 T_HM_RISK_AREA => T_SK_RISK_AREA
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedRiskArea")]
        public PagedActionResult<T_SK_RISK_AREA> OrderPagedRiskArea([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_SK_RISK_AREA> result)
            {
                PagedActionResult<T_SK_RISK_AREA> orderPageEntities = GetOrderPageEntities<T_SK_RISK_AREA>(null, pageFilter, null);
                result.Data = orderPageEntities.Data;
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }

        /// <summary>
        /// 查询班组
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("PagedCheckMain")]
        public PagedActionResult<T_BS_CHECK_MAIN> PagedCheckMain([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_BS_CHECK_MAIN> result)
            {
                Guid? RISK_AREA_ID = null;
                bool ISDOWN = false;
                if (!string.IsNullOrEmpty(pageFilter.Keyword))
                {
                    try
                    {
                        RISK_AREA_ID = new Guid(pageFilter.Keyword);
                    }
                    catch { }
                    pageFilter.Keyword = "";
                }
                if (pageFilter.Parameter1 != null && pageFilter.Parameter1 == "true")
                {
                    ISDOWN = true;
                }
                Expression<Func<T_BS_CHECK_MAIN, bool>> expression = e => !e.IS_DELETED && e.ENABLE_STATUS == 0 && e.CHECKCONTENT != null;
                if (RISK_AREA_ID.HasValue)
                {
                    if (ISDOWN)
                    {
                        List<Guid> listResultID = new List<Guid>();
                        List<Guid> listID = new List<Guid>() { RISK_AREA_ID.Value };
                        GetDownRiskID(listID, ref listResultID);//递归获取区域ID
                        expression = expression.And(e => e.RISK_AREA_ID.HasValue && listResultID.Contains(e.RISK_AREA_ID.Value));
                    }
                    else
                    {
                        expression = expression.And(e => e.RISK_AREA_ID.HasValue && e.RISK_AREA_ID.Value == RISK_AREA_ID.Value);
                    }
                }
                PagedActionResult<T_BS_CHECK_MAIN> orderPageEntities = GetOrderPageEntities(expression, pageFilter, null);
                result.Data = orderPageEntities.Data;

                foreach (var item in result.Data)
                {
                    if (item.QUESTION_LEVEL > 0)
                    {
                        item.QUESTION_LEVE_DESCRIPTION = ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription();
                    }
                }
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }

        /// <summary>
        /// 风险查看  T_HM_EVALUATE_RISK => T_SK_ENTERPRISE_LIBRARY
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("PagedEvaluateRisk")]
        public PagedActionResult<T_SK_ENTERPRISE_LIBRARY> PagedEvaluateRisk([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_SK_ENTERPRISE_LIBRARY> result)
            {
                Guid? AREA_ID = null;
                bool ISDOWN = false;
                if (!string.IsNullOrEmpty(pageFilter.Keyword))
                {
                    try
                    {
                        AREA_ID = new Guid(pageFilter.Keyword);
                    }
                    catch { }
                    pageFilter.Keyword = "";
                }
                if (pageFilter.Parameter1 != null && pageFilter.Parameter1 == "true")
                {
                    ISDOWN = true;
                }
                Expression<Func<T_SK_ENTERPRISE_LIBRARY, bool>> expression = e => !e.IS_DELETED;
                if (AREA_ID.HasValue)
                {
                    if (ISDOWN)
                    {
                        List<Guid> listResultID = new List<Guid>();
                        List<Guid> listID = new List<Guid>() { AREA_ID.Value };
                        GetDownRiskID(listID, ref listResultID);//递归获取区域ID
                        expression = expression.And(e => e.AREA_ID.HasValue && listResultID.Contains(e.AREA_ID.Value));
                    }
                    else
                    {
                        expression = expression.And(e => e.AREA_ID.HasValue && e.AREA_ID.Value == AREA_ID.Value);
                    }
                }
                PagedActionResult<T_SK_ENTERPRISE_LIBRARY> orderPageEntities = GetOrderPageEntities(expression, pageFilter, null);
                //Expression<Func<T_HM_EVALUATE_RISK, bool>> expression = e => !e.IS_DELETED;
                //if (AREA_ID.HasValue)
                //{
                //    if (ISDOWN)
                //    {
                //        List<Guid> listResultID = new List<Guid>();
                //        List<Guid> listID = new List<Guid>() { AREA_ID.Value };
                //        GetDownRiskID(listID, ref listResultID);//递归获取区域ID
                //        expression = expression.And(e => e.AREA_ID.HasValue && listResultID.Contains(e.AREA_ID.Value));
                //    }
                //    else
                //    {
                //        expression = expression.And(e => e.AREA_ID.HasValue && e.AREA_ID.Value == AREA_ID.Value);
                //    }
                //}
                //PagedActionResult<T_HM_EVALUATE_RISK> orderPageEntities = GetOrderPageEntities(expression, pageFilter, null);

                result.Data = orderPageEntities.Data;
                foreach (var item in result.Data)
                {
                    try
                    {
                        item.EVALUATE_LEVEL_SHOW = item.EVALUATE_LEVEL.GetDescription();
                    }
                    catch
                    {
                        item.EVALUATE_LEVEL_SHOW = "";
                    }
                }
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }

        /// <summary>
        /// 视频查看  T_SK_VIDEO_AREA
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("PagedVideo")]
        public PagedActionResult<T_SK_VIDEO_AREA> PagedVideo([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_SK_VIDEO_AREA> result)
            {
                Guid? AREA_ID = null;
                bool ISDOWN = false;
                if (!string.IsNullOrEmpty(pageFilter.Keyword))
                {
                    try
                    {
                        AREA_ID = new Guid(pageFilter.Keyword);
                    }
                    catch { }
                    pageFilter.Keyword = "";
                }
                if (pageFilter.Parameter1 != null && pageFilter.Parameter1 == "true")
                {
                    ISDOWN = true;
                }
                Expression<Func<T_SK_VIDEO_AREA, bool>> expression = e => !e.IS_DELETED;
                if (AREA_ID.HasValue)
                {
                    if (ISDOWN)
                    {
                        List<Guid> listResultID = new List<Guid>();
                        List<Guid> listID = new List<Guid>() { AREA_ID.Value };
                        GetDownRiskID(listID, ref listResultID);//递归获取区域ID
                        expression = expression.And(e => listResultID.Contains(e.AREA_ID));
                    }
                    else
                    {
                        expression = expression.And(e => e.AREA_ID == AREA_ID.Value);
                    }
                }
                PagedActionResult<T_SK_VIDEO_AREA> orderPageEntities = GetOrderPageEntities(expression, pageFilter, null);
                result.Data = orderPageEntities.Data;
                //string signStr = string.Empty;
                //string userid = "3cbccb39d9";
                //string secretKey = "vlUAYy8sr4";
                //if (orderPageEntities.Data != null && orderPageEntities.Data.Any())
                //{
                //    foreach (var item in orderPageEntities.Data)
                //    {
                //        if (!item.Nav_Viedo.ISLOCAL && item.Nav_Viedo.FILE_PATH.Contains('='))
                //        {
                //            //http://share.polyv.net/front/video/view?vid=3cbccb39d9c879ce2e82e9d8b8251822_3
                //            signStr = string.Empty;
                //            string ptime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
                //            signStr = string.Format("userid={0},ptime={1},requestId={2},vid={3}{4}", userid, ptime, Guid.NewGuid().ToString().Replace("-", ""), item.Nav_Viedo.FILE_PATH.Split('=')[1], secretKey);
                //            var sign = PolyvSignatureHelper.GenerateSha1Signature(signStr);
                //            item.Nav_Viedo.FILE_PATH = String.Format(item.Nav_Viedo.FILE_PATH + "&userid={0}&ptime={1}&sign={2}&playerId={3}", userid, ptime, sign, userid);
                //        }
                //    }
                //}
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }

        #endregion

        #region    common

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("UserPostOrderPaged")]
        public PagedActionResult<T_FM_USER_POST> UserPostOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_FM_USER_POST> result)
            {
                PagedActionResult<T_FM_USER_POST> orderPageEntities = GetOrderPageEntities<T_FM_USER_POST>(null, pageFilter, null);
                result.Data = orderPageEntities.Data;
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("DepartmentOrderPaged")]
        public PagedActionResult<T_FM_DEPARTMENT> DepartmentOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_FM_DEPARTMENT> result)
            {
                PagedActionResult<T_FM_DEPARTMENT> orderPageEntities = GetOrderPageEntities<T_FM_DEPARTMENT>(null, pageFilter, null);
                result.Data = orderPageEntities.Data;
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("DepartmentPostEntities")]
        public JsonActionResult<IEnumerable<T_FM_USER_POST>> DepartmentPostEntities([FromBody] KeywordFilter filter)
        {
            return SafeExecute<IEnumerable<T_FM_USER_POST>>(() =>
            {
                List<T_FM_USER_POST> result = new List<T_FM_USER_POST>();
                Guid? DEPARTMENT_ID = null;
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    try
                    {
                        DEPARTMENT_ID = new Guid(filter.Keyword);
                    }
                    catch
                    {
                        DEPARTMENT_ID = null;
                    }
                }

                if (DEPARTMENT_ID == null)
                {
                    result = GetEntities<T_FM_USER_POST>(e => e.STATUS == 1, null, null).OrderBy(e => e.NAME).ToList();//启用的岗位
                }
                else
                {
                    var listPersons = GetEntities<T_FM_PERSON>(e => e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID.Value == DEPARTMENT_ID.Value && e.POST_ID.HasValue, null, null);
                    var listPostID = listPersons.Select(e => e.POST_ID.Value).Distinct().ToList();
                    result = GetEntities<T_FM_USER_POST>(e => listPostID.Contains(e.ID) && e.STATUS == 1, null, null).OrderBy(e => e.NAME).ToList();
                }
                return result;
            });
        }

        /// <summary>
        /// 区域查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("AreaEntities")]
        public JsonActionResult<IEnumerable<T_SK_RISK_AREA>> AreaEntities([FromBody] KeywordFilter filter)
        {
            return SafeExecute<IEnumerable<T_SK_RISK_AREA>>(() =>
            {
                List<T_SK_RISK_AREA> result = new List<T_SK_RISK_AREA>();
                Expression<Func<T_SK_RISK_AREA, bool>> expression = e => !e.IS_DELETED;
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    try
                    {
                        Guid AREA_ID = new Guid(filter.Keyword);
                        expression = expression.And(e => e.ID == AREA_ID);
                    }
                    catch { }
                }
                result = GetEntities(expression, filter, null).OrderBy(e => e.NAME).ToList();//启用的岗位
                return result;
            });
        }


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedPost")]
        public PagedActionResult<T_FM_USER_POST> OrderPagedPost([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_FM_USER_POST> result)
            {
                Guid DEPARTMENT_ID = Guid.Empty;
                if (pageFilter.FilterGroup.Rules != null && pageFilter.FilterGroup.Rules.Any())
                {
                    var rules = pageFilter.FilterGroup.Rules;
                    foreach (var rule in rules)
                    {
                        if (rule.Field == "DEPARTMENT_ID")
                        {
                            DEPARTMENT_ID = new Guid(rule.Value.ToString());
                            rules.Remove(rule);
                            break;
                        }
                    }
                    pageFilter.FilterGroup.Rules = rules;
                }
                else if (pageFilter.FilterGroup.Groups != null && pageFilter.FilterGroup.Groups.Any())
                {
                    var rules = pageFilter.FilterGroup.Groups.ToList()[0].Rules;
                    foreach (var rule in rules)
                    {
                        if (rule.Field == "DEPARTMENT_ID")
                        {
                            DEPARTMENT_ID = new Guid(rule.Value.ToString());
                            rules.Remove(rule);
                            break;
                        }
                    }
                    //pageFilter.FilterGroup.Groups = rules;
                }

                if (DEPARTMENT_ID != Guid.Empty)
                {
                    List<Guid> listPersonID = new List<Guid>();
                    var IListPersons = GetEntities<T_FM_USER>(e => e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID == DEPARTMENT_ID && e.PERSON_ID.HasValue && !e.IS_DELETED && e.ENABLE_STATUS == 0, null, null);
                    if (IListPersons != null && IListPersons.Any())
                    {
                        foreach (var item in IListPersons)
                        {
                            listPersonID.Add(item.PERSON_ID.Value);
                        }
                    }
                    //var listPersonID = GetEntities<T_FM_USER>(e => e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID == DEPARTMENT_ID && e.PERSON_ID.HasValue, null, null).ToList().Select(e => e.PERSON_ID);

                    if (listPersonID != null && listPersonID.Any())
                    {
                        var IlistPerson = GetEntities<T_FM_PERSON>(e => e.POST_ID.HasValue && listPersonID.Contains(e.ID), null, null);
                        if (IlistPerson != null && IlistPerson.Any())
                        {
                            List<Guid> listPostID = new List<Guid>();
                            foreach (var item in IlistPerson)
                            {
                                listPostID.Add(item.POST_ID.Value);
                            }

                            if (listPostID.Any())
                            {
                                Expression<Func<T_FM_USER_POST, bool>> expression = e => !e.IS_DELETED && e.STATUS == 1 && listPostID.Contains(e.ID);
                                PagedActionResult<T_FM_USER_POST> orderPageEntities = this.GetOrderPageEntities<T_FM_USER_POST>(expression, pageFilter, null);
                                result.Data = orderPageEntities.Data;
                                result.TotalCount = orderPageEntities.TotalCount;
                            }
                        }

                    }
                }
                else
                {
                    result.Data = new List<T_FM_USER_POST>();
                    result.TotalCount = 0;
                }
            });
        }


        #endregion
    }
}
