using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums.PF;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.OG;
using APT.MS.Domain.Entities.SC;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
namespace APT.SC.WebApi.Controllers.Api.OG
{
    [Route("api/OG/OGSafeAssessPlanInput")]
    public class OGSafeAssessPlanInputController : AuthorizeApiController<T_OG_SAFE_ASSESS_PLAN_INPUT>
    {
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody]T_OG_SAFE_ASSESS_PLAN_INPUT entity)
        {
            return SafeExecute(() =>
            {
                if (entity.USER_ID == null)
                {
                    entity.USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                }
                var items = entity.Nav_SafeAssessItem;
                entity.Nav_SafeAssessItem = null;
                decimal? score = 0;
                if (items != null)
                {
                    items.ForEach(i => {
                        score += i.SCORE;
                    });
                }

                if (score != 100)
                {
                    throw new Exception("标准分相加应为100分");
                }

                if (entity.CODE == null)
                {
                    entity.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                }

                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (items != null)
                    {
                        BantchSaveEntityNoCommit(items);
                    }
                });
                return true;
            });
        }

        public class AssessUserModel
        {
            public List<T_FM_USER> Nav_User { get; set; }
        }

        [HttpPost, Route("GetAssessUser")]
        public JsonActionResult<AssessUserModel> GetAssessUser([FromBody] KeywordFilter filter)
        {
            var ret = new JsonActionResult<AssessUserModel>();
            if (filter.Keyword == null)
            {
                ret.Data = new AssessUserModel
                {
                    Nav_User = new List<T_FM_USER>(),
                };
                ret.IsSuccessful = true;
                ret.TotalCount = 0;
                ret.ErrorMessage = "";
                return ret;
            }
            var id = new Guid(filter.Keyword);
            var departIds = new List<Guid>();
            var depUsers = new List<T_FM_USER>();
            var tmpUsers = new List<T_FM_USER>();
            var headUserId = new List<Guid>();
            var retUsers = new List<T_FM_USER>();
            var safeUserIds = new List<Guid>();
            var posts = GetEntities<T_FM_USER_POST>(t => t.ID == id,
                    new BaseFilter(filter.GetOrgId())).ToList();
            bool isAsSafeUser = false;

            //if (posts != null)
            //{
            //    if (posts.Count > 0)
            //    {
            //        isAsSafeUser = posts[0].Nav_Post.AS_SAFE_USER;
            //    }
            //    posts.ForEach(t =>
            //    {
            //        departIds.AddRange(t.Nav_Post.Nav_Posts.Select(m => m.Nav_Depost.DEPARTMENT_ID.Value).ToList());
            //    });
            //    tmpUsers = posts.Select(u => u.Nav_User).ToList();
            //}
            //if (isAsSafeUser)
            //{
            //    var safePost = GetEntities<T_FM_DEPARTMENT_POST>(
            //        t => t.Nav_Workduty.NAME == "安全员" && departIds.Contains(t.DEPARTMENT_ID),
            //        new BaseFilter(entity.ORG_ID),
            //        new string[] { "Nav_Workduty", "Nav_Users", "Nav_Users.Nav_User" }).ToList();
            //    if (safePost != null)
            //    {
            //        safePost.ForEach(t =>
            //        {
            //            safeUserIds.AddRange(t.Nav_Users.Select(u => u.USER_ID).ToList());
            //        });
            //    }
            //    tmpUsers = tmpUsers.Where(u => safeUserIds.Contains(u.ID)).ToList();
            //}

            //var userData = GetEntity<T_FM_USER>(u => u.ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID,
            //                new BaseFilter(entity.ORG_ID),
            //                new string[] { "Nav_Department" });

            //// 公司级，除选矿部和矿山部
            //if (userData.Nav_Department.DEPARTMENT_LEVEL == (int)FMDepartmentLevelEnum.公司级)
            //{
            //    var depData = GetEntities<T_FM_DEPARTMENT>(d => d.CODE == "XLKKS" || d.CODE == "XLKXK",
            //                    new BaseFilter(entity.ORG_ID),
            //                    new string[] { "" }).ToList();
            //    depData.ForEach(t =>
            //    {
            //        // 获取选矿部和矿山部所有成员
            //        getDepAllUser(t.ID, depUsers, headUserId);
            //    });
            //    if (tmpUsers.Count > 0)
            //    {
            //        tmpUsers.ForEach(t =>
            //        {
            //            if (depUsers.Count > 0)
            //            {
            //                var hasData = false;
            //                depUsers.ForEach(d =>
            //                {
            //                    if (t.ID == d.ID)
            //                    {
            //                        hasData = true;
            //                    }
            //                });
            //                if (!hasData)
            //                {
            //                    retUsers.Add(t);
            //                }
            //            }
            //        });
            //    }
            //}
            //else
            //{
            //    // 部门级，或车间级，或班组级时，把当前部门和下级人员，除了负责人过滤出来
            //    getDepAllUser(userData.DEPARTMENT_ID.Value, depUsers, headUserId);
            //    if (tmpUsers.Count > 0)
            //    {
            //        tmpUsers.ForEach(t =>
            //        {
            //            if (depUsers.Count > 0)
            //            {
            //                depUsers.ForEach(d =>
            //                {
            //                    if (t.ID == d.ID && !headUserId.Contains(t.ID))
            //                    {
            //                        retUsers.Add(t);
            //                    }
            //                });
            //            }
            //        });
            //    }
            //}

            //ret.Data = new AssessUserModel
            //{
            //    Nav_User = retUsers,
            //};
            ret.IsSuccessful = true;
            ret.TotalCount = retUsers == null ? 0 : retUsers.Count;
            ret.ErrorMessage = "";
            return ret;
        }

        public void getDepAllUser(Guid depId, List<T_FM_USER> user, List<Guid> headUserId)
        {

            var userData = GetEntities<T_FM_USER>(u => u.DEPARTMENT_ID == depId,
                            new BaseFilter(APT.Infrastructure.Api.AppContext.CurrentSession.OrgId),
                            new string[] { "Nav_Department" }).ToList();
            if (userData != null && userData.Count > 0)
            {
                userData.ForEach(u =>
                {
                    headUserId.Add(u.Nav_Department.USER_ID.Value);
                });
                user.AddRange(userData);
            }
            var chidlData = GetEntities<T_FM_DEPARTMENT>(d => d.PARENT_ID == depId,
                new BaseFilter(APT.Infrastructure.Api.AppContext.CurrentSession.OrgId),
                new string[] { }).ToList();
            if (chidlData != null && chidlData.Count > 0)
            {
                chidlData.ForEach(c =>
                {
                    getDepAllUser(c.ID, user, headUserId);
                });
            }
        }
        public String GetAssessPlanInputCode()
        {
            return DateTime.Now.ToString("yyyyMMddHHmmss");
        }
        /// <summary>
        /// 安全生产组织保障考核方案导入model
        /// </summary>
        public class AssessPlanInfoModel
        {
            /// <summary>
            /// 用户导入model
            /// </summary>
            public AssessPlanInfoModel()
            {
                this.MessageList = new List<string>();
                this.Nav_AssessPlanItem = new List<AssessPlanItemModel>();
            }

            /// <summary>
            /// 提示信息
            /// </summary>
            public List<string> MessageList { get; set; }

            public List<AssessPlanItemModel> Nav_AssessPlanItem { get; set; }
        }
        /// <summary>
        /// 安全生产组织保障考核方案导入model
        /// </summary>
        public class AssessPlanItemModel
        {
            /// <summary>
            /// ID
            /// </summary>
            public Guid? ID { get; set; }

            /// <summary>
            /// 被考核岗位ID
            /// </summary>
            public Guid? POST_ID { get; set; }

            /// <summary>
            /// 被考核岗位
            /// </summary>
            public string POST_NAME { get; set; }

            /// <summary>
            /// 考核年度
            /// </summary>
            public int ANNUAL { get; set; }

            /// <summary>
            /// 考核周期ID
            /// </summary>
            public PTAssessmentCycleEnums CYCLE { get; set; }

            /// <summary>
            /// 考核项目
            /// </summary>
            public string NAME { get; set; }

            /// <summary>
            /// 标准分
            /// </summary>
            public int SCORE { get; set; }

            /// <summary>
            /// 考核认定评分办法
            /// </summary>
            public string METHOD { get; set; }
        }
        /// <summary>
        /// 导入安全生产组织考核方案
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("ImportAssessPlan")]
        public JsonActionResult<AssessPlanInfoModel> ImportAssessPlan()
        {
            return SafeExecute<AssessPlanInfoModel>(() =>
            {
                AssessPlanInfoModel model = new AssessPlanInfoModel();
                var httpRequest = this.HttpContext.Request;
                string orgIdStr = httpRequest.Form["OrgId"];// 获取 组织
                Guid? orgId = null;
                if (!string.IsNullOrEmpty(orgIdStr))
                    orgId = new Guid(orgIdStr);
                var unitlists = this.GetEntities<T_FM_UNIT>(null, new BaseFilter(orgId));
                foreach (var key in httpRequest.Form.Files)  // 文件键
                {
                    var postedFile = key;    // 获取文件键对应的文件对象
                    var dic = Path.Combine(System.AppContext.BaseDirectory, "tempImportFiles");
                    if (!Directory.Exists(dic))
                        Directory.CreateDirectory(dic);
                    string fileName = Path.Combine(dic, DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + postedFile.FileName);
                    Byte[] fileData = new Byte[postedFile.Length];
                    Stream sr = postedFile.OpenReadStream();//创建数据流对象 
                    sr.Read(fileData, 0, (int)postedFile.Length);
                    using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
                    {
                        fs.Write(fileData, 0, fileData.Length);
                        fs.Flush();
                        fs.Close();
                    }

                    var table = FileUtils.ReadExcelTable(fileName, 0);
                    try
                    {
                        System.IO.File.Delete(fileName);
                    }
                    catch { }

                    if (table != null && table.Rows.Count > 0)
                    {
                        DataColumn colPostName = table.Columns[0];//被考核岗位
                        DataColumn colAnnual = table.Columns[1];//考核年度
                        DataColumn colCycleName = table.Columns[2];//考核周期
                        DataColumn colItem = table.Columns[3];//考核项目
                        DataColumn colScore = table.Columns[4];//标准分
                        DataColumn colMethod = table.Columns[5];//考核认定评分办法
                        DataColumn colRowNO = new DataColumn("RowNo", typeof(int));//序号
                        colRowNO.DefaultValue = 0;
                        table.Columns.Add(colRowNO);

                        int rowNo = 1;
                        foreach (DataRow row in table.Rows)
                        {
                            row[colRowNO] = rowNo;
                            rowNo++;
                        }

                        List<T_OG_SAFE_ASSESS_PLAN_INPUT> allPlanInput = this.GetEntities<T_OG_SAFE_ASSESS_PLAN_INPUT>(null, new BaseFilter(), new string[] { "Nav_Post", "Nav_SafeAssessItem" }).ToList();
                        List<T_SC_POST> postList = null;
                        postList = this.GetEntities<T_SC_POST>(null, new BaseFilter(null, FilterOrgTypeEnum.忽略组织), new string[] { "Nav_Posts" }).ToList();

                        DataView dataView = new DataView(table, string.Empty, colPostName.ColumnName, DataViewRowState.CurrentRows);
                        foreach (DataRowView rV in dataView)
                        {
                            AssessPlanItemModel item = new AssessPlanItemModel();
                            DataRow r = rV.Row;

                            string postcodeName = LibUtils.ToString(r[colPostName]);
                            int annual = LibUtils.ToInt(r[colAnnual]);
                            int cycleName = LibUtils.ToInt(r[colCycleName]);

                            string itemStr = LibUtils.ToString(r[colItem]);
                            int scoreInt = LibUtils.ToInt(r[colScore]);
                            string methodStr = LibUtils.ToString(r[colMethod]);

                            int tmpRowNo = LibUtils.ToInt(r[colRowNO]);

                            T_SC_POST post = postList == null ? null :
                                        postList.Where(t => t.NAME == postcodeName).FirstOrDefault();
                            if (string.IsNullOrEmpty(postcodeName))
                            {
                                model.MessageList.Add(string.Format("序号{0}：被考核岗位为空,已忽略导入", tmpRowNo));
                                continue;
                            }
                            item.ID = Guid.NewGuid();
                            item.ANNUAL = annual;
                            if (post != null)
                            {
                                item.POST_ID = post.ID;
                                item.POST_NAME = post.NAME;
                            }
                            else
                            {
                                model.MessageList.Add(string.Format("序号{0}：被考核岗位{1}不存在,已忽略导入", tmpRowNo, postcodeName));
                                continue;
                            }
                            item.CYCLE = (PTAssessmentCycleEnums)cycleName;
                            item.NAME = itemStr;
                            item.SCORE = scoreInt;
                            item.METHOD = methodStr;

                            model.Nav_AssessPlanItem.Add(item);
                        }
                    }
                }
                return model;
            });
        }
        /// <summary>
        /// 保存导入考核方案
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("SaveImportAssessPlan")]
        public JsonActionResult<bool> SaveImportAssessPlan([FromBody] AssessPlanInfoModel model)
        {
            return SafeExecute<bool>(() =>
            {
                if (model == null || model.Nav_AssessPlanItem == null || model.Nav_AssessPlanItem.Count == 0)
                    throw new Exception("请输入");

                var inputList = new List<T_OG_SAFE_ASSESS_PLAN_INPUT>();
                var itemList = new List<T_OG_SAFE_ASSESS_ITEM>();

                model.Nav_AssessPlanItem.ForEach(t =>
                {
                    var index = -1;
                    var codeIndex = 0;
                    int i = 0;
                    inputList.ForEach(p =>
                    {
                        if (p.POST_ID == t.POST_ID && p.ANNUAL == t.ANNUAL && p.CYCLE == t.CYCLE)
                        {
                            index = i;
                        }
                        i++;
                    });

                    if (index != -1)
                    {
                        T_OG_SAFE_ASSESS_ITEM item = new T_OG_SAFE_ASSESS_ITEM();
                        item.ID = Guid.NewGuid();
                        item.ORG_ID = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                        item.ASSESS_PLAN_INPUT_ID = inputList[index].ID;
                        item.NAME = t.NAME;
                        item.SCORE = t.SCORE;
                        item.METHOD = t.METHOD;
                        itemList.Add(item);
                    }
                    else
                    {
                        var userData = GetEntity<T_FM_USER>(u => u.ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID,new string[] { "Nav_Department" });
                        var depName = "";
                        if (userData != null && userData.Nav_Department != null)
                        {
                            depName = userData.Nav_Department.NAME;
                        }
                        var code = "";
                        while (true)
                        {
                            var hasData = false;
                            code = GetAssessPlanInputCode();
                            inputList.ForEach(p =>
                            {
                                if (p.CODE == code)
                                {
                                    hasData = true;
                                }
                            });
                            if (!hasData)
                            {
                                break;
                            }
                        }
                        T_OG_SAFE_ASSESS_PLAN_INPUT input = new T_OG_SAFE_ASSESS_PLAN_INPUT
                        {
                            ID = Guid.NewGuid(),
                            ORG_ID = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId,
                            CODE = code,
                            POST_ID = t.POST_ID,
                            USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID,
                            ANNUAL = t.ANNUAL,
                            CYCLE = t.CYCLE,
                            DEP_NAME = depName,
                            STATUS = (int)PFStandardStatus.Draft,
                            ENTITY_ORG_TPYE = 2
                        };
                        inputList.Add(input);

                        T_OG_SAFE_ASSESS_ITEM item = new T_OG_SAFE_ASSESS_ITEM();
                        item.ID = Guid.NewGuid();
                        item.ORG_ID = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                        item.ASSESS_PLAN_INPUT_ID = input.ID;
                        item.NAME = t.NAME;
                        item.SCORE = t.SCORE;
                        item.METHOD = t.METHOD;
                        itemList.Add(item);
                        codeIndex++;
                    }
                });

                UnifiedCommit(() =>
                {
                    if (inputList.Count > 0)
                        BantchSaveEntityNoCommit(inputList);
                    if (itemList.Count > 0)
                        BantchSaveEntityNoCommit(itemList);
                });
                return true;
            });
        }
    }
}
