using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EmitMapper;

namespace BLL
{
    public static class APIHazardListService
    {
        #region 根据主键ID获取危险源辨识与评价详细
        /// <summary>
        ///  根据主键ID获取危险源辨识与评价详细
        /// </summary>
        /// <param name="hazardListId"></param>
        /// <returns></returns>
        public static Model.HazardListItem getHazardListInfoByHazardListId(string hazardListId)
        {
            using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
            {
                var getInfo = from x in db.Hazard_HazardList
                              where x.HazardListId == hazardListId
                              select new Model.HazardListItem
                              {
                                  HazardListId = x.HazardListId,
                                  ProjectId = x.ProjectId,
                                  HazardListCode = x.HazardListCode,
                                  VersionNo = x.VersionNo,
                                  CompileManId = x.CompileMan,
                                  CompileManName = db.Sys_User.First(u => u.UserId == x.CompileMan).UserName,
                                  CompileDate = string.Format("{0:yyyy-MM-dd}", x.CompileDate),
                                  WorkStageIds = x.WorkStage,
                                  WorkStageNames = WorkStageService.getWorkStageNamesWorkStageIds(x.WorkStage),
                                  Contents = x.Contents,
                                  WorkAreaName = x.WorkAreaName,
                                  IdentificationDate = string.Format("{0:yyyy-MM-dd}", x.IdentificationDate),
                                  ControllingPersonId = x.ControllingPerson,
                                  ControllingPersonName = db.Sys_User.First(u => u.UserId == x.ControllingPerson).UserName,
                                  States = x.States,
                              };
                return getInfo.FirstOrDefault();
            }
        }
        #endregion        

        #region 根据projectId获取危险源辨识评价列表
        /// <summary>
        /// 根据projectId获取危险源辨识评价列表
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static List<Model.HazardListItem> getHazardListList(string projectId)
        {
            using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
            {
                var getHazardList = from x in db.Hazard_HazardList
                                    where x.ProjectId == projectId && x.States == Const.State_2
                                    orderby x.IdentificationDate descending
                                    select new Model.HazardListItem
                                    {
                                        HazardListId = x.HazardListId,
                                        ProjectId = x.ProjectId,
                                        HazardListCode = x.HazardListCode,
                                        VersionNo = x.VersionNo,
                                        CompileManId = x.CompileMan,
                                        CompileManName = db.Sys_User.First(u => u.UserId == x.CompileMan).UserName,
                                        CompileDate = string.Format("{0:yyyy-MM-dd}", x.CompileDate),
                                        WorkStageIds = x.WorkStage,
                                        WorkStageNames = WorkStageService.getWorkStageNamesWorkStageIds(x.WorkStage),
                                        Contents = x.Contents,
                                        WorkAreaName = x.WorkAreaName,
                                        IdentificationDate = string.Format("{0:yyyy-MM-dd}", x.IdentificationDate),
                                        ControllingPersonId = x.ControllingPerson,
                                        ControllingPersonName = db.Sys_User.First(u => u.UserId == x.ControllingPerson).UserName,
                                        States = x.States,
                                    };
                return getHazardList.ToList();
            }
        }
        #endregion        

        #region 根据HazardListId获取危险源辨识评价明细信息
        /// <summary>
        /// 根据HazardListId获取危险源辨识评价明细信息
        /// </summary>
        /// <param name="hazardListId"></param>
        /// <returns></returns>
        public static List<Model.HazardListSelectedItem> getHazardListSelectedInfo(string hazardListId)
        {
            using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
            {
                var getHazardList = from x in db.Hazard_HazardSelectedItem
                                    join y in db.Technique_HazardListType on x.HazardListTypeId equals y.HazardListTypeId
                                    where x.HazardListId == hazardListId
                                    orderby x.HazardListTypeId descending
                                    select new Model.HazardListSelectedItem
                                    {
                                        HazardId = x.HazardId,
                                        WorkStageName = WorkStageService.getWorkStageNamesWorkStageIds(x.WorkStage),
                                        SupHazardListTypeName = db.Technique_HazardListType.First(z => z.HazardListTypeId == y.SupHazardListTypeId).HazardListTypeName,
                                        HazardListTypeName = y.HazardListTypeName,
                                        HazardCode = y.HazardListTypeCode,
                                        HazardItems = x.HazardItems,
                                        DefectsType = x.DefectsType,
                                        MayLeadAccidents = x.MayLeadAccidents,
                                        HelperMethod = x.HelperMethod,
                                        HazardJudge_L = x.HazardJudge_L,
                                        HazardJudge_E = x.HazardJudge_E,
                                        HazardJudge_C = x.HazardJudge_C,
                                        HazardJudge_D = x.HazardJudge_D,
                                        HazardLevel = x.HazardLevel,
                                        ControlMeasures = x.ControlMeasures,
                                    };
                return getHazardList.ToList();
            }
        }
        #endregion

        #region 获取风险等级列表信息
        /// <summary>
        /// 获取风险等级列表信息
        /// </summary>
        /// <returns></returns>
        public static List<Model.BaseInfoItem> getRiskLevel()
        {
            using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
            {
                var getRiskLevel = from x in db.Base_RiskLevel
                                   orderby x.RiskLevel
                                   select new Model.BaseInfoItem
                                   {
                                       BaseInfoId = x.RiskLevelId,
                                       BaseInfoCode = (x.RiskLevel ?? 0).ToString(),
                                       BaseInfoName = x.RiskLevelName,
                                   };
                return getRiskLevel.ToList();
            }
        }
        #endregion

        #region 根据HazardListId获取危险源辨识评价明细信息
        /// <summary>
        /// 根据HazardListId获取危险源辨识评价明细信息
        /// </summary>
        /// <param name="hazardListId"></param>
        /// <returns></returns>
        public static List<Model.HazardListSelectedItem> getHazardItemInfo(string hazardSelectedItemId)
        {
            using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
            {
                var getHazardList = from x in db.Hazard_HazardSelectedItem
                                    join y in db.Technique_HazardListType on x.HazardListTypeId equals y.HazardListTypeId
                                    where x.HazardSelectedItemId == hazardSelectedItemId
                                    orderby x.HazardListTypeId descending
                                    select new Model.HazardListSelectedItem
                                    {
                                        HazardSelectedItemId = hazardSelectedItemId,
                                        HazardId = x.HazardId,
                                        WorkStageName = WorkStageService.getWorkStageNamesWorkStageIds(x.WorkStage),
                                        SupHazardListTypeName = db.Technique_HazardListType.First(z => z.HazardListTypeId == y.SupHazardListTypeId).HazardListTypeName,
                                        HazardListTypeName = y.HazardListTypeName,
                                        HazardCode = y.HazardListTypeCode,
                                        HazardItems = x.HazardItems,
                                        DefectsType = x.DefectsType,
                                        MayLeadAccidents = x.MayLeadAccidents,
                                        HelperMethod = x.HelperMethod,
                                        HazardJudge_L = x.HazardJudge_L,
                                        HazardJudge_E = x.HazardJudge_E,
                                        HazardJudge_C = x.HazardJudge_C,
                                        HazardJudge_D = x.HazardJudge_D,
                                        HazardLevel = x.HazardLevel,
                                        ControlMeasures = x.ControlMeasures,
                                        DutyPersonId = x.DutyPerson,
                                        DutyPersonName = UserService.getUserNamesUserIds(x.DutyPerson),
                                        PatrolPlanId = (from z in db.Hazard_PatrolPlan where z.HazardSelectedItemId == hazardSelectedItemId && z.CheckDate == null select z.PatrolPlanId).FirstOrDefault(),
                                        Position = x.Position,
                                    };
                return getHazardList.ToList();
            }
        }
        #endregion

        #region 保存风险巡检记录明细项
        /// <summary>
        ///  保存风险巡检记录明细项
        /// </summary>
        /// <param name="newDetail"></param>
        public static string SaveRoutingInspection(Model.RoutingInspectionItem newDetail)
        {
            string message = string.Empty;
            using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
            {
                var oldP = db.Hazard_PatrolPlan.FirstOrDefault(x => x.HazardSelectedItemId == newDetail.HazardSelectedItemId && x.CheckDate == null);
                if (oldP != null)
                {
                    Model.Hazard_RoutingInspection newRoutingInspection = new Model.Hazard_RoutingInspection
                    {
                        RoutingInspectionId = SQLHelper.GetNewID(),
                        HazardSelectedItemId = newDetail.HazardSelectedItemId,
                        PatrolManId = newDetail.PatrolManId,
                        PatrolTime = Funs.GetNewDateTimeOrNow(newDetail.PatrolTime),
                        PatrolResult = Convert.ToInt32(newDetail.PatrolResult),
                        OldRiskLevel = db.Hazard_PatrolPlan.FirstOrDefault(x => x.HazardSelectedItemId == newDetail.HazardSelectedItemId && x.CheckDate == null).HazardLevel,
                        ControlMeasures = newDetail.ControlMeasures,
                        DealReason = newDetail.DealReason,
                        RiskManId = newDetail.RiskManId,
                        PatrolPlanId = db.Hazard_PatrolPlan.FirstOrDefault(x => x.HazardSelectedItemId == newDetail.HazardSelectedItemId && x.CheckDate == null).PatrolPlanId,
                    };
                    Model.Hazard_PatrolPlan p = BLL.Hazard_PatrolPlanService.GetPatrolPlanByPatrolPlanId(newRoutingInspection.PatrolPlanId);
                    db.Hazard_RoutingInspection.InsertOnSubmit(newRoutingInspection);
                    db.SubmitChanges();
                    ////保存附件
                    if (!string.IsNullOrEmpty(newDetail.AttachUrl))
                    {
                        UploadFileService.SaveAttachUrl(UploadFileService.GetSourceByAttachUrl(newDetail.AttachUrl, 10, null), newDetail.AttachUrl, Const.ProjectRiskControlMenuId, newRoutingInspection.RoutingInspectionId);
                    }
                    else
                    {
                        CommonService.DeleteAttachFileById(Const.ProjectRiskControlMenuId, newRoutingInspection.RoutingInspectionId);
                    }
                    p.CheckDate = newRoutingInspection.PatrolTime;
                    p.State = "1";   //已巡检
                    if (newRoutingInspection.PatrolTime > p.LimitCheckDate)
                    {
                        p.State = "2";   //超期巡检
                    }
                    BLL.Hazard_PatrolPlanService.UpdatePatrolPlan(p);
                    var ps = BLL.Hazard_PatrolPlanService.GetBeforePatrolPlansByCheckDate(newDetail.HazardSelectedItemId, p.CheckDate.Value);
                    Model.Hazard_HazardSelectedItem selectedItem = BLL.Hazard_HazardSelectedItemService.GetHazardSelectedItemByHazardSelectedItemId(p.HazardSelectedItemId);
                    foreach (var item in ps)
                    {
                        item.CheckDate = p.CheckDate;
                        item.State = "3";   //超期未巡检
                        BLL.Hazard_PatrolPlanService.UpdatePatrolPlan(item);
                    }
                    string str = string.Empty;
                    if (newDetail.PatrolResult == "0")   //原状态
                    {
                        //巡检计划
                        Model.Hazard_PatrolPlan plan = new Model.Hazard_PatrolPlan();
                        plan.PatrolPlanId = SQLHelper.GetNewID();
                        plan.HazardSelectedItemId = newDetail.HazardSelectedItemId;
                        plan.HazardLevel = p.HazardLevel;
                        plan.DutyPerson = newDetail.RiskManId;
                        plan.Days = p.Days;
                        plan.CheckStartDate = p.CheckStartDate;
                        plan.LimitCheckDate = p.LimitCheckDate.Value.AddDays(p.Days.Value);
                        plan.State = "0";
                        Model.Hazard_PatrolPlan oldPlan = BLL.Hazard_PatrolPlanService.GetPatrolPlanByHazardSelectedItemIdAndLimitCheckDate(newDetail.HazardSelectedItemId, plan.LimitCheckDate);
                        if (oldPlan == null)
                        {
                            BLL.Hazard_PatrolPlanService.AddPatrolPlan(plan);
                        }
                    }
                    else if (newDetail.PatrolResult == "1")  //二次评估
                    {
                        //二次评价记录
                        Model.Hazard_RiskEvaluationRecord record = new Model.Hazard_RiskEvaluationRecord();
                        record.LECItemRecordId = SQLHelper.GetNewID();
                        record.DataId = newDetail.HazardSelectedItemId;
                        record.DataType = "Project";
                        record.Evaluatorld = newDetail.RiskManId;
                        BLL.RiskEvaluationRecordService.AddRiskEvaluationRecord(record);
                        if (newDetail.RiskManId == newDetail.CurrUserId)
                        {
                            str = "1|" + newDetail.HazardSelectedItemId + "|" + record.LECItemRecordId;
                        }
                    }
                    else if (newDetail.PatrolResult == "2")  //下整改单
                    {
                        //巡检计划
                        Model.Hazard_PatrolPlan plan = new Model.Hazard_PatrolPlan();
                        plan.PatrolPlanId = SQLHelper.GetNewID();
                        plan.HazardSelectedItemId = newDetail.HazardSelectedItemId;
                        plan.HazardLevel = p.HazardLevel;
                        plan.DutyPerson = newDetail.RiskManId;
                        plan.Days = p.Days;
                        plan.CheckStartDate = p.CheckStartDate;
                        plan.LimitCheckDate = p.LimitCheckDate.Value.AddDays(p.Days.Value);
                        plan.State = "0";
                        Model.Hazard_PatrolPlan oldPlan = BLL.Hazard_PatrolPlanService.GetPatrolPlanByHazardSelectedItemIdAndLimitCheckDate(newDetail.HazardSelectedItemId, plan.LimitCheckDate);
                        if (oldPlan == null)
                        {
                            BLL.Hazard_PatrolPlanService.AddPatrolPlan(plan);
                        }
                        str = "2|" + newDetail.HazardSelectedItemId;
                    }
                    else if (newDetail.PatrolResult == "-1")  //消除
                    {
                        selectedItem.IsStart = false;
                        selectedItem.State = "0";
                        BLL.Hazard_HazardSelectedItemService.UpdateHazardSelectedItem(selectedItem);
                    }
                }
                else
                {
                    message = "尚未生成巡检计划!";
                }
            }
            return message;
        }
        #endregion

        #region 根据主键ID获取二次评估详细信息
        /// <summary>
        /// 根据主键ID获取二次评估详细信息
        /// </summary>
        /// <param name="hazardListId"></param>
        /// <returns></returns>
        public static List<Model.ReEvaluator> getReEvaluatorInfo(string LECItemRecordId)
        {
            using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
            {
                var getHazardList = from x in db.Hazard_RiskEvaluationRecord
                                    where x.LECItemRecordId == LECItemRecordId
                                    orderby x.DataId descending
                                    select new Model.ReEvaluator
                                    {
                                        LECItemRecordId = LECItemRecordId,
                                        HazardSelectedItemId = x.DataId,
                                        Evaluatorld = x.Evaluatorld,
                                    };
                return getHazardList.ToList();
            }
        }
        #endregion

        #region 保存二次评估明细项
        /// <summary>
        ///  保存二次评估明细项
        /// </summary>
        /// <param name="newDetail"></param>
        public static void SaveReEvaluator(Model.ReEvaluator newDetail)
        {
            using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
            {
                Model.Hazard_HazardSelectedItem item = BLL.Hazard_HazardSelectedItemService.GetHazardSelectedItemByHazardSelectedItemId(newDetail.HazardSelectedItemId);
                if (item != null)
                {
                    item.HazardJudge_L = newDetail.HazardJudge_L;
                    item.HazardJudge_E = newDetail.HazardJudge_E;
                    item.HazardJudge_C = newDetail.HazardJudge_C;
                    item.HazardJudge_D = newDetail.HazardJudge_D;
                    item.HazardLevel = newDetail.HazardLevel;
                    item.ControlMeasures = newDetail.ControlMeasures;
                    item.IsStart = newDetail.IsStart;
                    item.CheckStartDate = Funs.GetNewDateTime(newDetail.CheckStartDate);
                    if (!string.IsNullOrEmpty(newDetail.DutyPerson))
                    {
                        item.DutyPerson = newDetail.DutyPerson;
                    }
                    item.PlanExistDate = Funs.GetNewDateTime(newDetail.PlanExistDate);
                    item.State = "1";  //存在
                    if (!string.IsNullOrEmpty(newDetail.Position))
                    {
                        item.Position = newDetail.Position;
                    }
                    BLL.Hazard_HazardSelectedItemService.UpdateHazardSelectedItem(item);
                }

                var oldRecord = BLL.RiskEvaluationRecordService.GetRiskEvaluationRecordByDataIdAndEvaluatorDate(newDetail.HazardSelectedItemId);
                if (oldRecord != null)
                {
                    oldRecord.EvaluatorDate = DateTime.Now;
                    oldRecord.L = item.HazardJudge_L;
                    oldRecord.E = item.HazardJudge_E;
                    oldRecord.C = item.HazardJudge_C;
                    oldRecord.D = item.HazardJudge_D;
                    oldRecord.RiskLevel = item.HazardLevel;
                    oldRecord.ControlMeasures = item.ControlMeasures;
                    oldRecord.Remark = item.Remark;
                    BLL.RiskEvaluationRecordService.UpdateRiskEvaluationRecord(oldRecord);
                }
                else
                {
                    Model.Hazard_RiskEvaluationRecord record = new Model.Hazard_RiskEvaluationRecord();
                    record.LECItemRecordId = SQLHelper.GetNewID();
                    record.DataId = item.HazardSelectedItemId;
                    record.DataType = "Project";
                    record.Evaluatorld = newDetail.CurrUserId;
                    record.EvaluatorDate = DateTime.Now;
                    record.L = item.HazardJudge_L;
                    record.E = item.HazardJudge_E;
                    record.C = item.HazardJudge_C;
                    record.D = item.HazardJudge_D;
                    record.RiskLevel = item.HazardLevel;
                    record.ControlMeasures = item.ControlMeasures;
                    record.Remark = item.Remark;
                    BLL.RiskEvaluationRecordService.AddRiskEvaluationRecord(record);
                }
                if (item.IsStart == true)
                {
                    string[] personIds = newDetail.DutyPerson.Split(',');
                    foreach (var personId in personIds)
                    {
                        //巡检计划
                        Model.Hazard_PatrolPlan plan = new Model.Hazard_PatrolPlan();
                        plan.PatrolPlanId = SQLHelper.GetNewID();
                        plan.HazardSelectedItemId = newDetail.HazardSelectedItemId;
                        plan.HazardLevel = item.HazardLevel;
                        plan.DutyPerson = personId;
                        Model.Base_RiskLevel level = BLL.RiskLevelService.GetRiskLevel(item.HazardLevel);
                        if (level != null)
                        {
                            plan.Days = level.Days;
                        }
                        plan.CheckStartDate = item.CheckStartDate;
                        plan.LimitCheckDate = item.CheckStartDate.Value.AddDays(level.Days.Value);
                        plan.State = "0";
                        BLL.Hazard_PatrolPlanService.AddPatrolPlan(plan);
                    }
                }
            }
        }
        #endregion

        #region 根据projectId获取危险源辨识评价列表
        /// <summary>
        /// 根据projectId获取危险源辨识评价列表
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static List<Model.RoutingInspectionItem> getRoutingInspectionList(string projectId)
        {
            using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
            {
                var getHazardList = from x in db.Hazard_RoutingInspection
                                    join y in db.Hazard_HazardSelectedItem on x.HazardSelectedItemId equals y.HazardSelectedItemId
                                    join z in db.Hazard_HazardList on y.HazardListId equals z.HazardListId
                                    where z.ProjectId == projectId
                                    orderby x.PatrolTime descending
                                    select new Model.RoutingInspectionItem
                                    {
                                        RoutingInspectionId = x.RoutingInspectionId,
                                        WorkAreaName = z.WorkAreaName,
                                        WorkStageNames = WorkStageService.getWorkStageNamesWorkStageIds(z.WorkStage),
                                        HazardListType = db.Technique_HazardListType.First(e => e.HazardListTypeId == y.HazardListTypeId).HazardListTypeName,
                                        HazardItems = y.HazardItems,
                                        PatrolManName = db.Sys_User.First(e => e.UserId == x.PatrolManId).UserName,
                                        PatrolTime = string.Format("{0:yyyy-MM-dd}", x.PatrolTime),
                                        OldRiskLevelName = db.Base_RiskLevel.First(e => e.RiskLevelId == x.OldRiskLevel).RiskLevelName,
                                        RiskLevelName = db.Base_RiskLevel.First(e => e.RiskLevelId == y.HazardLevel).RiskLevelName,
                                        PatrolResultStr = ConvertPatrolResultStr(x.PatrolResult),
                                    };
                return getHazardList.ToList();
            }
        }

        private static string ConvertPatrolResultStr(int? PatrolResult)
        {
            if (PatrolResult != null)
            {
                if (PatrolResult == 0)
                {
                    return "原状态";
                }
                else if (PatrolResult == 1)
                {
                    return "二次评估";
                }
                else if (PatrolResult == 2)
                {
                    return "下整改单";
                }
                else
                {
                    return "消除";
                }
            }
            return "";
        }
        #endregion

        #region 根据主键ID获取已生成的风险巡检记录信息
        /// <summary>
        /// 根据主键ID获取已生成的风险巡检记录信息
        /// </summary>
        /// <param name="hazardListId"></param>
        /// <returns></returns>
        public static List<Model.RoutingInspectionItem> getRoutingInspection(string routingInspectionId)
        {
            using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
            {
                var getHazardList = from x in db.Hazard_RoutingInspection
                                    join y in db.Hazard_HazardSelectedItem on x.HazardSelectedItemId equals y.HazardSelectedItemId
                                    where x.RoutingInspectionId == routingInspectionId
                                    orderby x.PatrolTime descending
                                    select new Model.RoutingInspectionItem
                                    {
                                        RoutingInspectionId = x.RoutingInspectionId,
                                        HazardCode = db.Technique_HazardList.First(z => z.HazardId == y.HazardId).HazardCode,
                                        HazardSelectedItemId = x.HazardSelectedItemId,
                                        HazardItems = y.HazardItems,
                                        DefectsType = y.DefectsType,
                                        MayLeadAccidents = y.MayLeadAccidents,
                                        PatrolManId = db.Sys_User.First(z => z.UserId == x.PatrolManId).UserName,
                                        PatrolTime = string.Format("{0:yyyy-MM-dd}", x.PatrolTime),
                                        PatrolResult = x.PatrolResult.ToString(),
                                        ControlMeasures = x.ControlMeasures,
                                        DealReason = x.DealReason,
                                        RiskManId = db.Sys_User.First(z => z.UserId == x.RiskManId).UserName,
                                    };
                return getHazardList.ToList();
            }
        }
        #endregion
    }
}