using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.PF;
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.HM.WebApi.Controllers.Api
{
    [Route("api/HM/HMEvaluateRisk")]
    public partial class EvaluateRiskController : AuthorizeApiController<T_HM_EVALUATE_RISK>
    {
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_HM_EVALUATE_RISK entity)
        {
            {
                return SafeExecute<bool>(() =>
                {
                    var workduty = entity.Nav_EvaluateRiskWorkduty;
                    var facilities = entity.Nav_EvaluateRiskFacilities;
                    var equipment = entity.Nav_EvaluateRiskEquipment;
                    var Individual = entity.Nav_EvaluateRiskIndividualMeasures;
                    var Engineering = entity.Nav_EvaluateRiskEngineeringMeasures;
                    var Management = entity.Nav_EvaluateRiskManagementMeasures;
                    var Education = entity.Nav_EvaluateRiskEducationMeasures;
                    var Emergency = entity.Nav_EvaluateRiskEmergencyMeasures;


                    entity.Nav_EvaluateRiskWorkduty = null;
                    entity.Nav_EvaluateRiskFacilities = null;
                    entity.Nav_EvaluateRiskEquipment = null;
                    entity.Nav_EvaluateRiskIndividualMeasures = null;
                    entity.Nav_EvaluateRiskEngineeringMeasures = null;
                    entity.Nav_EvaluateRiskManagementMeasures = null;
                    entity.Nav_EvaluateRiskEducationMeasures = null;
                    entity.Nav_EvaluateRiskEmergencyMeasures = null;

                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)//保存主表
                            UpdateEntityNoCommit(entity);
                        if (workduty != null && workduty.Any())//保存子表
                            BantchSaveEntityNoCommit(workduty);
                        if (facilities != null && facilities.Any())//保存子表
                            BantchSaveEntityNoCommit(facilities);
                        if (equipment != null && equipment.Any()) //保存子表
                            BantchSaveEntityNoCommit(equipment);
                        if (Individual != null && Individual.Any()) //保存子表
                            this.BantchSaveEntityNoCommit(Individual);
                        if (Engineering != null && Engineering.Any()) //保存子表
                            this.BantchSaveEntityNoCommit(Engineering);
                        if (Management != null && Management.Any()) //保存子表
                            this.BantchSaveEntityNoCommit(Management);
                        if (Education != null && Education.Any()) //保存子表
                            this.BantchSaveEntityNoCommit(Education);
                        if (Emergency != null && Emergency.Any()) //保存子表
                            this.BantchSaveEntityNoCommit(Emergency);
                    });
                    return true;
                });
            }
        }
        /// <summary>
        /// 获取导入数据  
        /// 参考         [Route("api/PF/Import")]
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("GetImportData")]
        public JsonActionResult<ImportDataModel> GetImportData()
        {
            return SafeExecute<ImportDataModel>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var httpRequest = this.HttpContext.Request;
                string orgIdStr = httpRequest.Form["OrgId"];// 获取 组织            
                ImportDataModel result = new ImportDataModel();
                var dic = Path.Combine(System.AppContext.BaseDirectory, "tempImportFiles");
                if (!Directory.Exists(dic))
                    Directory.CreateDirectory(dic);
                foreach (var key in httpRequest.Form.Files)  // 文件键
                {
                    var postedFile = key;    // 获取文件键对应的文件对象
                    string filePath = 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(filePath, FileMode.CreateNew))
                    {
                        fs.Write(fileData, 0, fileData.Length);
                        fs.Flush();
                        fs.Close();
                    }

                    //获取数据
                    Dictionary<int, int> startRowIndexs = new Dictionary<int, int>();
                    startRowIndexs.Add(0, 1);//根据Excel格式数据赋值
                    var dataTables = FileUtils.ReadExcelByOledb(filePath, startRowIndexs);
                    string Msg = string.Empty;

                    bool isOK = InsertModel(dataTables.Tables[0], orgId, ref Msg);

                    try
                    {
                        System.IO.File.Delete(filePath);
                    }
                    catch { }

                    result.Data = Msg;
                    result.MessageList = new List<string> { Msg };
                }

                return result;
            });
        }

        /// <summary>
        /// 数据插入
        /// </summary>
        /// <param name="dtSource"></param>
        /// <param name="OrgID"></param>
        /// <param name="Msg"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public bool InsertModel(DataTable dtSource, Guid? orgId, ref string Msg, int rowIndex = 1)
        {
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            if (dtSource == null || dtSource.Rows.Count < rowIndex)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }
            int rowAll = dtSource.Rows.Count;
            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }
            List<T_HM_EVALUATE_RISK> riskAll = new List<T_HM_EVALUATE_RISK>();
            List<T_HM_EVALUATE_RISK_EQUIPMENT> addEquipment = new List<T_HM_EVALUATE_RISK_EQUIPMENT>();
            List<T_HM_EVALUATE_RISK_WORKDUTY> addWorkduty = new List<T_HM_EVALUATE_RISK_WORKDUTY>();
            List<T_HM_EVALUATE_RISK_INDIVIDUAL_MEASURES> addINDIVIDUAL = new List<T_HM_EVALUATE_RISK_INDIVIDUAL_MEASURES>();
            List<T_HM_EVALUATE_RISK_ENGINEERING_MEASURES> addENGINEERING = new List<T_HM_EVALUATE_RISK_ENGINEERING_MEASURES>();
            List<T_HM_EVALUATE_RISK_MANAGEMENT_MEASURES> addMANAGEMENT = new List<T_HM_EVALUATE_RISK_MANAGEMENT_MEASURES>();
            List<T_HM_EVALUATE_RISK_EDUCATION_MEASURES> addEDUCATION = new List<T_HM_EVALUATE_RISK_EDUCATION_MEASURES>();
            List<T_HM_EVALUATE_RISK_EMERGENCY_MEASURES> addEMERGENCY = new List<T_HM_EVALUATE_RISK_EMERGENCY_MEASURES>();
            var deps = GetEntities<T_FM_DEPARTMENT>(t => t.IS_DELETED == false, new BaseFilter(orgId));
            var posts = GetEntities<T_PF_APPROVAL_ROLE>(t => t.IS_DELETED == false, new BaseFilter(orgId));



            DateTime dtNow = DateTime.Now;
            for (int i = 0; i < rowAll; i++)
            {
                T_HM_EVALUATE_RISK item = new T_HM_EVALUATE_RISK();
                item.ID = Guid.NewGuid();
                item.ORG_ID = orgId;

                if (!string.IsNullOrEmpty(dtSource.Rows[i][0].ToString().Trim()))//辨识区域
                {
                    var item1 = GetEntity<T_HM_RISK_AREA>(t => t.NAME == dtSource.Rows[i][0].ToString().Trim());
                    if (item1 != null)
                    {
                        item.AREA_ID = item1.ID;
                    }
                    else
                    {
                        T_HM_RISK_AREA addarea = new T_HM_RISK_AREA();
                        addarea.ID = Guid.NewGuid();
                        addarea.NAME = dtSource.Rows[i][0].ToString().Trim();
                        addarea.ORG_ID = orgId;
                        item.AREA_ID = addarea.ID;
                        AddEntity(addarea);
                    }

                }

                if (!string.IsNullOrEmpty(dtSource.Rows[i][1].ToString().Trim()))//辨识对象
                {
                    var item1 = GetEntity<T_HM_IDENTIFYING>(t => t.NAME == dtSource.Rows[i][1].ToString().Trim());
                    if (item1 != null)
                    {
                        item.IDENTIFYING_ID = item1.ID;
                    }
                    else
                    {
                        T_HM_IDENTIFYING add = new T_HM_IDENTIFYING();
                        add.ID = Guid.NewGuid();
                        add.NAME = dtSource.Rows[i][1].ToString().Trim();
                        add.ORG_ID = orgId;
                        item.IDENTIFYING_ID = add.ID;
                        AddEntity(add);
                    }
                    if (dtSource.Rows[i][1].ToString().Trim() == "设备设施")
                    {
                        var conf = dtSource.Rows[i][2].ToString().Trim().Split(new[] { '、' }, StringSplitOptions.RemoveEmptyEntries);
                        if (conf.Length > 0)
                        {
                            foreach (var c in conf)
                            {
                                var item2 = GetEntity<T_HM_EQUIPMENT>(t => t.NAME == dtSource.Rows[i][2].ToString().Trim());
                                T_HM_EVALUATE_RISK_EQUIPMENT safeConf = new T_HM_EVALUATE_RISK_EQUIPMENT();
                                safeConf.ORG_ID = orgId;
                                safeConf.EVALUATION_RISK_ID = item.ID;

                                if (item2 == null)
                                {
                                    T_HM_EQUIPMENT addequ = new T_HM_EQUIPMENT();
                                    addequ.ID = Guid.NewGuid();
                                    addequ.NAME = c;
                                    addequ.ORG_ID = orgId;
                                    safeConf.EQUIPMENT_ID = addequ.ID;
                                    AddEntity(addequ);
                                }
                                else
                                {
                                    safeConf.EQUIPMENT_ID = item2.ID;
                                }
                                addEquipment.Add(safeConf);
                            }
                        }
                    }

                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][3].ToString().Trim()))//相关岗位
                {
                    var conf = dtSource.Rows[i][3].ToString().Trim().Split(new[] { '、' }, StringSplitOptions.RemoveEmptyEntries);
                    if (conf.Length > 0)
                    {
                        foreach (var c in conf)
                        {
                            var item1 = GetEntity<T_FM_USER_POST>(t => t.NAME == dtSource.Rows[i][3].ToString().Trim());
                            T_HM_EVALUATE_RISK_WORKDUTY safeConf = new T_HM_EVALUATE_RISK_WORKDUTY();
                            safeConf.ORG_ID = orgId;
                            safeConf.EVALUATION_RISK_ID = item.ID;
                            if (item1 == null)
                            {
                                T_FM_USER_POST additem = new T_FM_USER_POST();
                                additem.ID = Guid.NewGuid();
                                additem.NAME = c;
                                additem.ORG_ID = orgId;
                                safeConf.POST_ID = additem.ID;
                                AddEntity(additem);
                            }
                            else
                            {
                                safeConf.POST_ID = item1.ID;
                            }
                            addWorkduty.Add(safeConf);
                        }
                    }
                }
               
                if (!string.IsNullOrEmpty(dtSource.Rows[i][4].ToString().Trim()))//危险源
                {

                    var item1 = GetEntity<T_HM_RISKSOURCE>(t => t.NAME == dtSource.Rows[i][4].ToString().Trim());
                    if (item1 != null)
                    {
                        item.NAME = item1.NAME;
                    }
                    else
                    {
                        T_HM_RISKSOURCE add = new T_HM_RISKSOURCE();
                        add.ID = Guid.NewGuid();
                        add.NAME = dtSource.Rows[i][4].ToString().Trim();
                        add.ORG_ID = orgId;
                        item.NAME = add.NAME;
                        AddEntity(add);
                    }
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][5].ToString().Trim()))//伤害类型
                {
                    var item1 = GetEntity<T_HM_RISK_TYPE>(t => t.NAME == dtSource.Rows[i][5].ToString().Trim());
                    if (item1 != null)
                    {
                        item.TYPE_ID = item1.ID;
                    }
                    else
                    {
                        T_HM_RISK_TYPE add = new T_HM_RISK_TYPE();
                        add.ID = Guid.NewGuid();
                        add.NAME = dtSource.Rows[i][5].ToString().Trim();
                        add.ORG_ID = orgId;
                        item.TYPE_ID = add.ID;
                        AddEntity(add);
                    }
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][6].ToString().Trim()))//风险地点
                {
                    item.RISK_PLACE = dtSource.Rows[i][6].ToString().Trim();
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][7].ToString().Trim()))//L
                {
                    item.EVALUATE_L = decimal.Parse(dtSource.Rows[i][7].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][8].ToString().Trim()))//E
                {
                    item.EVALUATE_E = decimal.Parse(dtSource.Rows[i][8].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][9].ToString().Trim()))//C
                {
                    item.EVALUATE_C = decimal.Parse(dtSource.Rows[i][9].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][10].ToString().Trim()))//D
                {
                    item.EVALUATE_SCORE = decimal.Parse(dtSource.Rows[i][10].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][11].ToString().Trim()))//风险等级
                {
                    if (dtSource.Rows[i][11].ToString().Trim() == "一级")
                    {
                        item.EVALUATE_LEVEL = EvaluateLevelEnum.一级;
                    }
                    else if (dtSource.Rows[i][11].ToString().Trim() == "二级")
                    {
                        item.EVALUATE_LEVEL = EvaluateLevelEnum.二级;
                    }
                    else if (dtSource.Rows[i][11].ToString().Trim() == "三级")
                    {
                        item.EVALUATE_LEVEL = EvaluateLevelEnum.三级;
                    }
                    else if (dtSource.Rows[i][11].ToString().Trim() == "四级")
                    {
                        item.EVALUATE_LEVEL = EvaluateLevelEnum.四级;
                    }
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][12].ToString().Trim()))//工程控制
                {
                    var item1 = GetEntity<T_HM_ENGINEERING_MEASURES>(t => t.NAME == dtSource.Rows[i][12].ToString().Trim());
                    T_HM_EVALUATE_RISK_ENGINEERING_MEASURES measure = new T_HM_EVALUATE_RISK_ENGINEERING_MEASURES();
                    measure.ORG_ID = orgId;
                    measure.EVALUATION_RISK_ID = item.ID;
                    if (item1 == null)
                    {
                        T_HM_ENGINEERING_MEASURES additem = new T_HM_ENGINEERING_MEASURES();
                        additem.ID = Guid.NewGuid();
                        additem.NAME = dtSource.Rows[i][12].ToString().Trim();
                        additem.ORG_ID = orgId;
                        measure.ENGINEERING_MEASURES_ID = additem.ID;
                        AddEntity(additem);
                    }
                    else
                    {
                        measure.ENGINEERING_MEASURES_ID = item1.ID;
                    }
                    addENGINEERING.Add(measure);
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][13].ToString().Trim()))//管理控制措施
                {
                    var item1 = GetEntity<T_HM_MANAGEMENT_MEASURES>(t => t.NAME == dtSource.Rows[i][13].ToString().Trim());
                    T_HM_EVALUATE_RISK_MANAGEMENT_MEASURES measure = new T_HM_EVALUATE_RISK_MANAGEMENT_MEASURES();
                    measure.ORG_ID = orgId;
                    measure.EVALUATION_RISK_ID = item.ID;
                    if (item1 == null)
                    {
                        T_HM_MANAGEMENT_MEASURES additem = new T_HM_MANAGEMENT_MEASURES();
                        additem.ID = Guid.NewGuid();
                        additem.NAME = dtSource.Rows[i][13].ToString().Trim();
                        additem.ORG_ID = orgId;
                        measure.MANAGEMENT_MEASURES_ID = additem.ID;
                        AddEntity(additem);
                    }
                    else
                    {
                        measure.MANAGEMENT_MEASURES_ID = item1.ID;
                    }
                    addMANAGEMENT.Add(measure);
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][14].ToString().Trim()))//个体防护措施
                {
                    var item1 = GetEntity<T_HM_INDIVIDUAL_MEASURES>(t => t.NAME == dtSource.Rows[i][14].ToString().Trim());
                    T_HM_EVALUATE_RISK_INDIVIDUAL_MEASURES measure = new T_HM_EVALUATE_RISK_INDIVIDUAL_MEASURES();
                    measure.ORG_ID = orgId;
                    measure.EVALUATION_RISK_ID = item.ID;
                    if (item1 == null)
                    {
                        T_HM_INDIVIDUAL_MEASURES additem = new T_HM_INDIVIDUAL_MEASURES();
                        additem.ID = Guid.NewGuid();
                        additem.NAME = dtSource.Rows[i][14].ToString().Trim();
                        additem.ORG_ID = orgId;
                        measure.INDIVIDUAL_MEASURES_ID = additem.ID;
                        AddEntity(additem);
                    }
                    else
                    {
                        measure.INDIVIDUAL_MEASURES_ID = item1.ID;
                    }
                    addINDIVIDUAL.Add(measure);
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][15].ToString().Trim()))//教育培训措施
                {
                    var item1 = GetEntity<T_HM_EDUCATION_MEASURES>(t => t.NAME == dtSource.Rows[i][15].ToString().Trim());
                    T_HM_EVALUATE_RISK_EDUCATION_MEASURES measure = new T_HM_EVALUATE_RISK_EDUCATION_MEASURES();
                    measure.ORG_ID = orgId;
                    measure.EVALUATION_RISK_ID = item.ID;
                    if (item1 == null)
                    {
                        T_HM_EDUCATION_MEASURES additem = new T_HM_EDUCATION_MEASURES();
                        additem.ID = Guid.NewGuid();
                        additem.NAME = dtSource.Rows[i][15].ToString().Trim();
                        additem.ORG_ID = orgId;
                        measure.EDUCATION_MEASURES_ID = additem.ID;
                        AddEntity(additem);
                    }
                    else
                    {
                        measure.EDUCATION_MEASURES_ID = item1.ID;
                    }
                    addEDUCATION.Add(measure);
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][16].ToString().Trim()))//应急处置措施
                {
                    var item1 = GetEntity<T_HM_EMERGENCY_MEASURES>(t => t.NAME == dtSource.Rows[i][16].ToString().Trim());
                    T_HM_EVALUATE_RISK_EMERGENCY_MEASURES measure = new T_HM_EVALUATE_RISK_EMERGENCY_MEASURES();
                    measure.ORG_ID = orgId;
                    measure.EVALUATION_RISK_ID = item.ID;
                    if (item1 == null)
                    {
                        T_HM_EMERGENCY_MEASURES additem = new T_HM_EMERGENCY_MEASURES();
                        additem.ID = Guid.NewGuid();
                        additem.NAME = dtSource.Rows[i][16].ToString().Trim();
                        additem.ORG_ID = orgId;
                        measure.EMERGENCY_MEASURES_ID = additem.ID;
                        AddEntity(additem);
                    }
                    else
                    {
                        measure.EMERGENCY_MEASURES_ID = item1.ID;
                    }
                    addEMERGENCY.Add(measure);
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][17].ToString().Trim()))//管控层级
                {
                    if (dtSource.Rows[i][17].ToString().Trim() == "公司级")
                    {
                        item.LEVEL = FMDepartmentType.Company;
                    }
                    else if (dtSource.Rows[i][17].ToString().Trim() == "部门级")
                    {
                        item.LEVEL = FMDepartmentType.Department;
                    }
                    else if (dtSource.Rows[i][17].ToString().Trim() == "车间级")
                    {
                        item.LEVEL = FMDepartmentType.Workshop;
                    }
                    else if (dtSource.Rows[i][17].ToString().Trim() == "班组级")
                    {
                        item.LEVEL = FMDepartmentType.Class;
                    }
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][18].ToString().Trim()))//责任单位
                {
                    item.DEPARTMENT_LIABLE_ID = deps.FirstOrDefault(t => t.NAME == dtSource.Rows[i][18].ToString().Trim()).ID;
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][19].ToString().Trim()))//责任岗位
                {
                    item.POST_LIABLE_ID = posts.FirstOrDefault(t => t.NAME == dtSource.Rows[i][19].ToString().Trim()).ID;
                }
                riskAll.Add(item);

            }
            UnifiedCommit(() =>
            {
                BantchSaveEntityNoCommit(riskAll);
                if (addEquipment != null && addEquipment.Any())
                    BantchSaveEntityNoCommit(addEquipment);
                if (addWorkduty != null && addWorkduty.Any())
                    BantchSaveEntityNoCommit(addWorkduty);
                if (addINDIVIDUAL != null && addINDIVIDUAL.Any())
                    BantchAddEntityNoCommit(addINDIVIDUAL);
                if (addENGINEERING != null && addENGINEERING.Any())
                    BantchAddEntityNoCommit(addENGINEERING);
                if (addMANAGEMENT != null && addMANAGEMENT.Any())
                    BantchAddEntityNoCommit(addMANAGEMENT);
                if (addEDUCATION != null && addEDUCATION.Any())
                    BantchAddEntityNoCommit(addEDUCATION);
                if (addEMERGENCY != null && addEMERGENCY.Any())
                    BantchAddEntityNoCommit(addEMERGENCY);
            });
            Msg = "导入成功！";
            return true;
        }
    }
}
