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

namespace APT.SC.WebApi.Controllers.Api.SE
{
    [Route("api/SE/SESafeSurvey")]
    public class SESafeSurveyController : AuthorizeApiController<T_SE_SAFE_SURVEY>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public SESafeSurveyController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SE_SAFE_SURVEY entity)
        {
            return SafeExecute(() =>
            {
                var currentUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var Nav_JoinDepartment = entity.Nav_JoinDepartment;
                var Nav_Points = entity.Nav_Points;
                var Nav_Files = entity.Nav_Files;
                List<T_FM_NOTIFICATION_TASK> noticeTask = null;
                T_FM_NOTIFICATION_TASK finishNotice = null;
                List<T_SE_SAFE_SURVEY_LIST_PAPER> Nav_Papers = null;

                if (entity.STATUS != SESafeSurveyStatus.草稿)
                {
                    throw new Exception("当前状态数据不可编辑");
                }
                //如果草稿状态已有人提交，且发起人不是自己，则不可再提交（多安全员）
                if (entity.STATUS == SESafeSurveyStatus.草稿 && (entity.LAUNCH_USER_ID != currentUserId.Value && entity.LAUNCH_USER_ID != Guid.Empty))
                {
                    throw new Exception("只能由本部门安全员填写!");
                }
                if (entity.LAUNCH_TIME == null)
                {
                    entity.LAUNCH_TIME = DateTime.Now;
                }
                if (entity.LAUNCH_USER_ID == Guid.Empty)
                {
                    entity.LAUNCH_USER_ID = (Guid)currentUserId;
                }
                if (entity.END_TIME == null)
                {
                    throw new Exception("请设置截止时间");
                }
                if (entity.LAUNCH_TIME.Value.AddDays(3) > entity.END_TIME)
                {
                    throw new Exception("截止时间至少比发起时间要大三天");
                }
                if (Nav_JoinDepartment == null)
                {
                    throw new Exception("参与人员不可为空");
                }
                entity.Nav_JoinDepartment = null;
                if (Nav_Points == null)
                {
                    throw new Exception("调查内容不可为空");
                }
                if (entity.LAUNCH_DEPARTMENT_ID == null)
                {
                    entity.LAUNCH_DEPARTMENT_ID = GetEntity<T_FM_USER>(entity.LAUNCH_USER_ID.ToString()).DEPARTMENT_ID;
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "SE005_SHOWPRINT");
                    }
                    Nav_Papers = new List<T_SE_SAFE_SURVEY_LIST_PAPER>();
                    entity.STATUS = SESafeSurveyStatus.调查中;
                    var config = GetEntity<T_SE_SECONFIG>(t => true);
                    var SCount = 1;
                    var MCount = 1;
                    var CCount = 1;
                    if (config != null)
                    {
                        if (config.M_TEST_COUNT > 0)
                        {
                            MCount = config.M_TEST_COUNT;
                        }
                        if (config.S_TEST_COUNT > 0)
                        {
                            SCount = config.S_TEST_COUNT;
                        }
                        if (config.C_TEST_COUNT > 0)
                        {
                            CCount = config.C_TEST_COUNT;
                        }
                    }
                    var testidlist = new List<Guid>();
                    var pointIDS = Nav_Points.Where(t => t.IS_DELETED == false).Select(t => (Guid)t.POINT_ID).ToList();
                    var allUsersIds = GetDepartmentUsers(Nav_JoinDepartment.Select(t => t.DEPARTMENT_ID).ToList(), entity.ORG_ID);
                    var currDep = GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.LAUNCH_DEPARTMENT_ID);
                    if (currDep != null && (currDep.NAME == "安全环保管理部" || currDep.NAME == "安全环保科" || currDep.NAME == "安全环保部" || currDep.NAME == "安环部"))
                    {
                        var manageUsers = GetEntities<T_FM_USER>(t => t.Nav_Department.DEPARTMENT_TYPE == 3 && t.ENABLE_STATUS == 0, new BaseFilter(entity.ORG_ID)).Select(t => t.ID);
                        allUsersIds.AddRange(manageUsers);
                    }
                    var allSendUserIds = new List<Guid>();
                    var allSendUserNames = new List<string>();
                    var allUserDepIds = new List<Guid?>();
                    var allUserPostIdS = new List<Guid?>();

                    var filter = new BaseFilter(entity.ORG_ID);
                    filter.Include = new string[] { "Nav_Person" };
                    var allUsers = this.GetEntities<T_FM_USER>(t => !t.CODE.Contains("admin") && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && allUsersIds.Contains(t.ID), filter);

                    foreach (var user in allUsersIds)
                    {
                        var current = allUsers.FirstOrDefault(t => t.ID == user);
                        allUserDepIds.Add(current?.DEPARTMENT_ID);
                        allUserPostIdS.Add(current?.Nav_Person.POST_ID);
                    }
                    var testFilter = new BaseFilter(entity.ORG_ID);
                    testFilter.Include = new string[] { "Nav_Points", "Nav_Posts" };

                    var allTests = GetEntities<T_SE_TEST>(st => st.Nav_Points.Any(pt => pointIDS.Contains(pt.POINT_ID.Value))
                    && (st.Nav_Posts.Any(pt => allUserPostIdS.Contains(pt.POST_ID)) || !st.Nav_Posts.Any()), testFilter).ToList();
                    var errorMsg = "";
                    foreach (var testPoint in pointIDS)
                    {
                        var havepoint = allTests.Where(st => st.Nav_Points.Any(pt => pt.POINT_ID == testPoint));
                        if (havepoint.Count() < 1)
                        {
                            var noPoint = GetEntity<T_SE_TEST_ENUM_POINT>(testPoint);
                            errorMsg += noPoint.NAME + ",";
                        }
                    }
                    if (errorMsg != "")
                    {
                        throw new Exception("知识点 " + errorMsg + " 没有题目!");
                    }
                    for (int i = 0; i < allUsersIds.Count; i++)
                    {
                        var userName = allUsers.FirstOrDefault(t => t.ID == allUsersIds[i]);
                        if (userName != null)
                        {
                            testidlist.Clear();
                            CreateTestList(allTests, testidlist, pointIDS, allUserPostIdS[i], (int)SETestTypeEnum.是非题, CCount);
                            CreateTestList(allTests, testidlist, pointIDS, allUserPostIdS[i], (int)SETestTypeEnum.单选题, SCount);
                            CreateTestList(allTests, testidlist, pointIDS, allUserPostIdS[i], (int)SETestTypeEnum.多选题, MCount);
                            if (testidlist.Count != 0)
                            {
                                testidlist.ForEach(testid =>
                                {
                                    var p = new T_SE_SAFE_SURVEY_LIST_PAPER
                                    {
                                        SAFE_ID = entity.ID,
                                        ID = Guid.NewGuid(),
                                        ORG_ID = entity.ORG_ID,
                                        USER_ID = allUsersIds[i],
                                        DEPARTMENT_ID = allUserDepIds[i],
                                        TEST_ID = testid,
                                        ANSWER = 0,
                                    };
                                    Nav_Papers.Add(p);
                                });
                                allSendUserIds.Add(allUsersIds[i]);
                                allSendUserNames.Add(userName.NAME);
                            }
                        }
                    }
                    if (allSendUserIds.Count == 0 || Nav_Papers.Count == 0)
                    {
                        entity.STATUS = SESafeSurveyStatus.草稿;
                        throw new Exception("出题失败。问卷会按照知识点、责任制岗位以及基础配置来抽取试题，请确认你的表单输入是否正确，以及题库是否有相应的试题供抽取");
                    }
                    noticeTask = NotificationTaskService.InsertUserNoticeTaskModels("安全意识调查问卷-" + entity.NAME, entity.ID, entity.ORG_ID, allSendUserIds, allSendUserNames,
                        DateTime.Now, (DateTime)entity.END_TIME, (int)FMFormTypeEnum.计划任务通知, "SESafeSurveyTest");
                }
                entity.Nav_JoinDepartment = null;
                entity.Nav_Points = null;
                entity.Nav_Papers = null;
                entity.Nav_Files = null;
                Nav_JoinDepartment.ForEach(p =>
                p.Nav_Department = null
                );
                Nav_Points.ForEach(p =>
               p.Nav_Point = null
               );
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (Nav_JoinDepartment != null)
                        BantchSaveEntityNoCommit(Nav_JoinDepartment);
                    if (Nav_Points != null && Nav_Points.Any())
                        BantchSaveEntityNoCommit(Nav_Points);
                    if (Nav_Files != null && Nav_Files.Any())
                        BantchSaveEntityNoCommit(Nav_Files);
                    if (Nav_Papers != null && Nav_Papers.Any())
                        BantchAddEntityNoCommit(Nav_Papers);
                    if (noticeTask != null && noticeTask.Any())
                        BantchAddEntityNoCommit(noticeTask);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });
                return true;
            });
        }
        private void CreateTestList(List<T_SE_TEST> allTests, List<Guid> ret, List<Guid> pointIDS, Guid? allUserPostIdS, int type, int count)
        {
            var tests = allTests.Where(t => t.TYPE == (SETestTypeEnum)type &&
            t.Nav_Points.Any(pt => pointIDS.Contains(pt.POINT_ID.Value)) &&
            (t.Nav_Posts.Any(pt => allUserPostIdS == pt.POST_ID) || !t.Nav_Posts.Any())
            ).OrderBy(t => Guid.NewGuid()).Take(count);
            if (tests != null)
            {
                if (tests.Count() < count)
                {
                    throw new Exception((SETestTypeEnum)type + "题库" + tests.Count() + "数量不足" + count + "题,无法生成试卷");
                }
                ret.AddRange(tests.Select(t => t.ID));
            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetPapers")]
        public JsonActionResult<SafeSurveyPaperModel> Papers([FromBody] KeywordFilter filter)
        {
            var papers = GetEntities<T_SE_SAFE_SURVEY_LIST_PAPER>(null, filter).ToList();
            var config = GetEntity<T_SE_SECONFIG>(t => true);
            var ret = new JsonActionResult<SafeSurveyPaperModel>();
            ret.Data = new SafeSurveyPaperModel
            {
                Nav_Papers = papers,
                Nav_Config = config
            };
            ret.IsSuccessful = true;
            ret.TotalCount = 1;
            ret.ErrorMessage = "";
            return ret;
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Approve")]
        public JsonActionResult<bool> Approve([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                if (filter.Parameter2 == null)
                {
                    throw new Exception("请从待办完成该表单!");
                }
                var finishId = new Guid(filter.Parameter2);
                var entity = GetEntity<T_SE_SAFE_SURVEY>(filter.Parameter1);
                if (entity == null)
                {
                    throw new Exception("未查到有效数据");
                }
                if (entity.STATUS != SESafeSurveyStatus.汇总审阅中)
                {
                    throw new Exception("当前状态无法完成审阅");
                }
                entity.STATUS = SESafeSurveyStatus.完成;
                var finishNoitice = NotificationTaskService.GetTaskFinishModel(finishId);
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity, "STATUS");
                    if (finishNoitice != null)
                        UpdateEntityNoCommit(finishNoitice);
                });
                return true;
            });
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetUsers")]
        public JsonActionResult<IEnumerable<T_FM_USER>> GetUsers([FromBody] KeywordFilter filter)
        {
            return SafeExecute<IEnumerable<T_FM_USER>>(() =>
            {
                return GetEntities<T_SE_SAFE_SURVEY_LIST_PAPER>(null, filter).Select(it => it.Nav_User).Distinct(it => it.ID).ToList();
            });
        }
        /// <summary>
        /// 提交试卷
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("SavePapers")]
        public JsonActionResult<bool> SavePapers([FromBody] SafeSurveyPaperModel entity)
        {
            return SafeExecute(() =>
            {
                if (entity.Nav_Papers == null || entity.Nav_Papers.Count == 0)
                {
                    throw new Exception("试卷不能为空");
                }
                var safeID = entity.Nav_Papers[0].SAFE_ID;
                var safe = GetEntity<T_SE_SAFE_SURVEY>(it => it.ID == safeID, new BaseFilter(null));
                if (safe == null)
                {
                    throw new Exception("未查到有效数据");
                }
                if (safe.STATUS != SESafeSurveyStatus.调查中)
                {
                    throw new Exception("问卷已结束，不可提交");
                }
                var score = 0;
                var sscore = entity.Nav_Config.S_TEST_SCORE;
                var mscore = entity.Nav_Config.M_TEST_SCORE;
                var cscore = entity.Nav_Config.C_TEST_SCORE;

                foreach (var item in entity.Nav_Papers)
                {
                    if (item.ANSWER != 0 && item.ANSWER == item.Nav_Test.ANSWER)
                    {
                        if (item.Nav_Test.TYPE == SETestTypeEnum.是非题)
                        {
                            score += cscore;
                        }
                        else if (item.Nav_Test.TYPE == SETestTypeEnum.单选题)
                        {
                            score += sscore;
                        }
                        else if (item.Nav_Test.TYPE == SETestTypeEnum.多选题)
                        {
                            score += mscore;
                        }
                    }
                }
                foreach (var item in entity.Nav_Papers)
                {
                    item.SCORE = score;
                }
                var noticeTask = NotificationTaskService.GetTaskFinishModel((Guid)entity.TaskID);
                UnifiedCommit(() =>
                {
                    BantchSaveEntityNoCommit(entity.Nav_Papers);
                    UpdateEntityNoCommit(noticeTask);
                });
                return true;
            });
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetReportList")]
        public JsonActionResult<IEnumerable<KeyValuePair<Guid, DateTime>>> GetReportIndex([FromBody] KeywordFilter filter)
        {
            return SafeExecute<IEnumerable<KeyValuePair<Guid, DateTime>>>(() =>
            {
                var ret = new List<KeyValuePair<Guid, DateTime>>();
                var dt = DateTime.Now;
                var data = GetEntities<T_SE_SAFE_SURVEY>(
                    it => it.STATUS == SESafeSurveyStatus.完成 && it.TASK_ID != null && it.LAUNCH_TIME != null && it.LAUNCH_TIME.Value.Year == dt.Year,
                    new BaseFilter(null)).Distinct(it => it.TASK_ID).ToList();
                if (data != null)
                {
                    data.ForEach(it =>
                    {
                        ret.Add(new KeyValuePair<Guid, DateTime>(it.TASK_ID.Value, it.LAUNCH_TIME.Value));
                    });
                }
                return ret;
            });
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetReport")]
        public JsonActionResult<SafeSurveyReportModel> GetReport([FromBody] KeywordFilter filter)
        {
            return SafeExecute<SafeSurveyReportModel>(() =>
            {
                var ret = new SafeSurveyReportModel
                {
                    ROWS = new List<List<string>>(),
                    SURVEY = new List<T_SE_SAFE_SURVEY>(),
                };
                var Colums = new List<string>();
                var Rows = new List<Row>();
                var points = new List<T_SE_TEST_ENUM_POINT>();

                if (filter.Parameter1 != null)
                {
                    ret.SURVEY_ID = new Guid((string)filter.Parameter1);
                }
                else
                {
                    if (filter.Parameter2 != null)
                    {
                        ret.TASK_ID = new Guid((string)filter.Parameter2);
                    }
                    else
                    {
                        throw new Exception("参数有误");
                    }

                }
                ret.TYPE = filter.Parameter3;
                if (ret.TYPE != "部门" && ret.TYPE != "岗位" && ret.TYPE != "人员")
                {
                    ret.TYPE = "部门";
                }
                var surveyIds = new List<Guid>();
                var paths = new string[] {
                "Nav_Points",
                "Nav_Points.Nav_Point",
                "Nav_LaunchDepartment",
                "Nav_LaunchUser",
                "Nav_JoinDepartment",
                "Nav_JoinDepartment.Nav_Department"
            };
                if (ret.SURVEY_ID != null)
                {
                    var tmp = GetEntity<T_SE_SAFE_SURVEY>(
                        t => t.ID == ret.SURVEY_ID.Value,
                        new BaseFilter(null),
                        paths);
                    if (tmp != null)
                    {
                        surveyIds.Add(ret.SURVEY_ID.Value);
                        points.AddRange(tmp.Nav_Points.Select(it => it.Nav_Point));
                        ret.SURVEY.Add(tmp);
                    }
                    else
                    {
                        throw new Exception("未查到相应数据");
                    }
                }
                else
                {
                    var tmp = GetEntities<T_SE_SAFE_SURVEY>(
                        t => t.TASK_ID != null && t.TASK_ID.Value == ret.TASK_ID.Value,
                        new BaseFilter(null),
                        paths).ToList();
                    if (tmp != null && tmp.Count > 0)
                    {
                        ret.SURVEY.AddRange(tmp);
                        surveyIds.AddRange(tmp.Select(it => it.ID));
                        tmp.ForEach(it =>
                        {
                            it.Nav_Points.ForEach(p =>
                            {
                                if (points.Find(f => f.ID == p.POINT_ID.Value) == null)
                                {
                                    points.Add(p.Nav_Point);
                                }
                            });
                        });
                    }
                    else
                    {
                        throw new Exception("未查到相应数据");
                    }
                }
                BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                baseFilter.Include = new string[] { "Nav_User.Nav_Person.Nav_Post", "Nav_User.Nav_Department.Nav_Parent", "Nav_Department.Nav_Parent", "Nav_Test.Nav_Posts", "Nav_Test.Nav_Points" };
                var papers = GetEntities<T_SE_SAFE_SURVEY_LIST_PAPER>(t => surveyIds.Contains(t.SAFE_ID), baseFilter);
                var colscount = points.Count;
                for (int i = 0; i < points.Count; i++)
                {
                    Colums.Add(points[i].NAME);
                }
                var MAP = new Dictionary<Guid, int>();
                if (ret.TYPE == "人员")
                {
                    papers.ForEach(paper =>
                    {
                        int idx = 0;
                        if (!MAP.TryGetValue(paper.USER_ID.Value, out idx))
                        {
                            idx = Rows.Count;
                            Rows.Add(new Row());
                            Rows[idx].NAME = paper.Nav_User.NAME + "(" + paper.Nav_User.CODE + ")";
                            Rows[idx].COL = new int[colscount, 2];
                            MAP[paper.USER_ID.Value] = idx;
                        }
                        for (int i = 0; i < points.Count; i++)
                        {
                            if (paper.Nav_Test.Nav_Points.Find(p => p.POINT_ID.Value == points[i].ID) != null)
                            {
                                Rows[idx].COL[i, 0]++;
                                if (paper.ANSWER != 0 && paper.ANSWER == paper.Nav_Test.ANSWER)
                                {
                                    Rows[idx].COL[i, 1]++;
                                }
                            }
                        }
                    });
                }
                else if (ret.TYPE == "岗位")
                {
                    papers.ForEach(paper =>
                    {
                        if (paper.Nav_User.Nav_Person.Nav_Post != null)
                        {
                            int idx = 0;
                            if (!MAP.TryGetValue(paper.Nav_User.Nav_Person.Nav_Post.ID, out idx))
                            {
                                idx = Rows.Count;
                                Rows.Add(new Row());
                                Rows[idx].NAME = paper.Nav_User.Nav_Person.Nav_Post.NAME;
                                Rows[idx].COL = new int[colscount, 2];
                                MAP[paper.Nav_User.Nav_Person.Nav_Post.ID] = idx;
                            }
                            for (int i = 0; i < points.Count; i++)
                            {
                                if (paper.Nav_Test.Nav_Points.Find(p => p.POINT_ID.Value == points[i].ID) != null)
                                {
                                    Rows[idx].COL[i, 0]++;
                                    if (paper.ANSWER != 0 && paper.ANSWER == paper.Nav_Test.ANSWER)
                                    {
                                        Rows[idx].COL[i, 1]++;
                                    }
                                }
                            }
                        }
                    });
                }
                else if (ret.TYPE == "部门")
                {
                    papers.ForEach(paper =>
                    {
                        int idx = 0;
                        T_FM_DEPARTMENT pd = paper.Nav_Department;
                        T_FM_DEPARTMENT cd = paper.Nav_User.Nav_Department;
                        if (pd.ID != cd.ID)
                        {
                            if (cd.Nav_Parent!=null && cd.Nav_Parent.ID != pd.ID)
                            {
                                cd = cd.Nav_Parent;
                            }
                        }
                        if (!MAP.TryGetValue(cd.ID, out idx))
                        {
                            idx = Rows.Count;
                            Rows.Add(new Row());
                            Rows[idx].NAME = pd.NAME;
                            if (pd.NAME == "宁化行洛坑钨矿有限公司")
                            {
                                Rows[idx].NAME = "公司领导";
                            }
                            if (pd.ID != cd.ID)
                            {
                                Rows[idx].NAME += "/" + cd.NAME;
                            }
                            Rows[idx].COL = new int[colscount, 2];
                            MAP[cd.ID] = idx;
                        }
                        for (int i = 0; i < points.Count; i++)
                        {
                            if (paper.Nav_Test.Nav_Points.Find(p => p.POINT_ID.Value == points[i].ID) != null)
                            {
                                Rows[idx].COL[i, 0]++;
                                if (paper.ANSWER != 0 && paper.ANSWER == paper.Nav_Test.ANSWER)
                                {
                                    Rows[idx].COL[i, 1]++;
                                }
                            }
                        }
                    });
                }
                var header = new List<string>();
                var TotalRow = new int[colscount, 2];
                header.Add("统计维度(" + ret.TYPE + ")");
                for (var i = 0; i < Colums.Count; i++)
                {
                    header.Add(Colums[i]);
                }
                header.Add("合计");
                ret.ROWS.Add(header);

                for (var i = 0; i < Rows.Count; i++)
                {
                    var total = 0;
                    var ok = 0;
                    var row = new List<string>();
                    row.Add(Rows[i].NAME);
                    for (var j = 0; j < Rows[i].COL.GetLength(0); j++)
                    {
                        total += Rows[i].COL[j, 0];
                        ok += Rows[i].COL[j, 1];
                        TotalRow[j, 0] += Rows[i].COL[j, 0];
                        TotalRow[j, 1] += Rows[i].COL[j, 1];
                        if (Rows[i].COL[j, 0] == 0)
                        {
                            row.Add("0");
                        }
                        else
                        {
                            row.Add(Math.Round(Rows[i].COL[j, 1] * 100.0 / Rows[i].COL[j, 0]).ToString());
                        }
                    }
                    if (total == 0)
                    {
                        row.Add("0");
                    }
                    else
                    {
                        row.Add(Math.Round(ok * 100.0 / total).ToString());
                    }
                    ret.ROWS.Add(row);
                }
                var alltotal = 0;
                var allok = 0;
                var footer = new List<string>();
                footer.Add("合计");
                for (var i = 0; i < TotalRow.GetLength(0); i++)
                {
                    alltotal += TotalRow[i, 0];
                    allok += TotalRow[i, 1];
                    if (TotalRow[i, 0] == 0)
                    {
                        footer.Add("0");
                    }
                    else
                    {
                        footer.Add(Math.Round(TotalRow[i, 1] * 100.0 / TotalRow[i, 0]).ToString());
                    }
                }
                if (alltotal == 0)
                {
                    footer.Add("0");
                }
                else
                {
                    footer.Add(Math.Round(allok * 100.0 / alltotal).ToString());
                }
                ret.ROWS.Add(footer);
                return ret;
            });
        }
        /// <summary>
        /// 查找部门下的所有人
        /// </summary>
        /// <param name="entity"></param>
        [HttpPost, Route("GetDepartmentUsers")]
        public List<Guid> GetDepartmentUsers(List<Guid> departmentIDs, Guid? orgId)
        {
            var allUsers = new List<Guid>();
            var departments = GetEntities<T_FM_DEPARTMENT>(t => departmentIDs.Contains(t.ID), new BaseFilter(orgId));
            var departmentInfos = departments.Where(x => x.DEPARTMENT_TYPE == (int)FMDepartmentType.公司).ToList();
            if (departmentInfos != null && departmentInfos.Any())
            {
                var allUsers1 = GetEntities<T_FM_USER>(i => i.ENABLE_STATUS == 0 && !i.CODE.Contains("admin"), new BaseFilter(orgId)).Select(t => t.ID).Distinct().ToList();
                allUsers.AddRange(allUsers1);
            }
            else
            {
                List<Guid> outputDepartmentIds = new List<Guid>();
                GetDepartmentIds(departmentIDs, orgId, ref outputDepartmentIds);
                var allUsers1 = GetEntities<T_FM_USER>(i => i.ENABLE_STATUS == 0 && i.DEPARTMENT_ID != null && outputDepartmentIds.Contains((Guid)i.DEPARTMENT_ID) && !i.CODE.Contains("admin"), new BaseFilter(orgId)).Select(t => t.ID).ToList();
                allUsers.AddRange(allUsers1);
            }
            return allUsers;
        }
        /// <summary>
        /// 返回所有部门节点
        /// <returns></returns>
        private void GetDepartmentIds(List<Guid> departmentIdList, Guid? orgId, ref List<Guid> departmentIds)
        {
            departmentIds.AddRange(departmentIdList);
            var departmentTemps = GetEntities<T_FM_DEPARTMENT>(t => t.PARENT_ID != null && departmentIdList.Contains((Guid)t.PARENT_ID), new BaseFilter(orgId));
            if (departmentTemps != null && departmentTemps.Any())
            {
                var temp = departmentTemps.Select(t => t.ID).Distinct().ToList();
                GetDepartmentIds(temp, orgId, ref departmentIds);
            }
        }
        public class SafeSurveyPaperModel
        {
            public List<T_SE_SAFE_SURVEY_LIST_PAPER> Nav_Papers { get; set; }
            public T_SE_SECONFIG Nav_Config { get; set; }
            public Guid? TaskID { get; set; }

        }

        public class Row
        {
            public string NAME { get; set; }
            public int[,] COL { get; set; }
        }
        public class SafeSurveyReportModel
        {
            public Guid? TASK_ID { get; set; }
            public Guid? SURVEY_ID { get; set; }
            public List<T_SE_SAFE_SURVEY> SURVEY;
            public string TYPE { get; set; }
            public List<List<string>> ROWS { get; set; }
        }
    }
}
