using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using Siger.ApiCNC.Result;
using Siger.ApiCommon.Filters;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.CncRepository.Entities;
using Siger.Middlelayer.CncRepository.Repositories.Interface;
using Siger.Middlelayer.CncRepository.Request;
using Siger.Middlelayer.CncRepository.Response;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Dapper;
using Siger.Middlelayer.Dapper.SearchCondition;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Redis;
using Siger.Middlelayer.Redis.Repositories;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Response;
using Siger.Middlelayer.Utility.Helpers;

namespace Siger.ApiCNC.Controllers
{
    public class MachineAlarmController : BaseController
    {
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly ISigerProjectMachineTypeRepository _machineTypeRepository;
        private readonly IMachineFaultTypeRepository _faultTypeRepository;
        private readonly IDashboardCombPageConditionTwoRepository _combPageConditionRepository;
        private readonly ISigerProjectLevelSectionRepository _levelSectionRepository;
        private readonly IUnitOfWork _unitOfWork;
        public MachineAlarmController(ISigerProjectMachineRepository machineRepository, ISigerProjectMachineTypeRepository machineTypeRepository,
            IMachineFaultTypeRepository faultTypeRepository, IUnitOfWork unitOfWork, IDashboardCombPageConditionTwoRepository combPageConditionRepository,
            ISigerProjectLevelSectionRepository levelSectionRepository)
        {
            _machineRepository = machineRepository;
            _machineTypeRepository = machineTypeRepository;
            _faultTypeRepository = faultTypeRepository;
            _unitOfWork = unitOfWork;
            _combPageConditionRepository = combPageConditionRepository;
            _levelSectionRepository = levelSectionRepository;
        }

        //生产参数监控 - 参数异常列表
        [HttpPost]
        public IActionResult GetAbnormalList([FromBody] RequestGetAbnormalList request)
        {
            if (request.toexcel != 0)
            {
                request.pagesize = 999999999;
            }
            try
            {
                var cncExceptionRepository = new ExceptionParamsSateRepository(CompanyId, ProjectId);
                var pageInfo = new Pagination(request.page, request.pagesize);
                var condition = new ExceptionParamCondition();
                if (request.sectionID != 0)
                {
                    condition.MachinIds = _machineRepository.GetAttributionMachineIds(request.sectionID, ProjectId);
                }

                condition.BigSmall = request.big_small.ToInt();
                condition.BigSmallSpan = request.big_small_span.ToInt();
                condition.StartTime = request.startTime;
                condition.EndTime = request.endTime;
                condition.ErrType = request.errType.ToInt();

                var exceptions = cncExceptionRepository.GetPagedCncExceptionParamsSates(pageInfo, condition);
                var result = new List<ResponseGetAbnormalList>();

                var validMachines = _machineRepository.GetNCLevelSectionNames(0, ProjectId);
                foreach (var exception in exceptions.Value)
                {
                    var section = validMachines.FirstOrDefault(q => q.machine_id == exception.MachineID);
                    var entity = new ResponseGetAbnormalList
                    {
                        Downlimit = exception.Downlimit,
                        Uplimit = exception.Uplimit,
                        end_time = (int)UnixTimeHelper.ConvertDataTimeLong(exception.EndTime),
                        exception_type = exception.Type,
                        machineid = exception.MachineID,
                        spindleid = exception.Spindle,
                        start_time = (int)UnixTimeHelper.ConvertDataTimeLong(exception.StartTime),
                        //time_span = UnixTimeHelper.GetTimeBySecond((int)(exception.EndTime - exception.StartTime).TotalSeconds),
                        time_span = (exception.EndTime - exception.StartTime).TotalSeconds.ToString(),
                        //stas = string.Join('-', _machineRepository.GetLevelSectionTitlesByMachineId(exception.MachineID, ProjectId))
                        stas = section == null ? "" : section.lastSecondSectionTitle + "-" + section.lastSectionTitle
                    };
                    result.Add(entity);
                }
                if (request.toexcel == 0)
                {
                    return new PagedObjectResult(result, exceptions.Key.TotalItemCount, request.page, request.pagesize);
                }
                var machines = _machineRepository.GetProjectLanguage(ProjectId);
                return ExportAbnormalList(result, machines);
            }
            catch (Exception e)
            {
                Logger.WriteLineError("get GetAbnormalList failed, error:" + e);
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
        }

        //生产参数监控-参数异常列表
        [HttpPost]
        public IActionResult GetLook([FromBody] RequestGetLock request)
        {
            var result = new GetLookResult
            {
                yData1 = request.Downlimit,
                yData2 = request.Uplimit,
            };

            //var startRow = $"{request.MachineID}_{UnixTimeHelper.ConvertIntDateTimeToStr(request.Stime)}";
            //var endRow = $"{request.MachineID}_{UnixTimeHelper.ConvertIntDateTimeToStr(request.Etime)}";
            //var dataSource = GetRawLowData(startRow, endRow, request.Spindle, request.Type);
            //foreach (var rawLow in dataSource)
            //{
            //    result.xName.Add(rawLow.Time);
            //    result.yData3.Add(rawLow.Value);
            //}

            return result;
        }

        //private IList<ResponseRawLow> GetRawLowData(string startRow, string endRow, int spindle, int type)
        //{
        //    try
        //    {
        //        var dbConfig = RedisCache.Instance.GetDbName(CompanyId, ProjectId);

        //        var dataSoure = ThriftHelper.Instance.GetRawLowData(startRow, endRow, spindle, type, dbConfig.HBaseDbName);

        //        return dataSoure;
        //    }
        //    catch (Exception e)
        //    {
        //        Logger.WriteLineError("GetRawLowData failed, error:" + e.Message);
        //        return new List<ResponseRawLow>();
        //    }
        //}

        //生产参数监控-参数异常统计
        [HttpPost]
        public IActionResult ListExceptionTimesByDay([FromBody] RequestListExceptionTimesByDay request)
        {
            //xID - 0:时间 1：层级 2：异常类型
            //yID - 0:次数 1：时长
            //patchID - xID=0时 0:天 1：周 2：月；xID=1时 patchID为levelID；xID=2时，pactchid为errorID
            var dtStart = DateTime.Parse(request.startTime);
            var dtEnd = DateTime.Parse(request.endTime);
            if (dtStart > dtEnd)
            {
                throw new ServerException(100158);
            }

            var time = dtEnd.AddDays(1).ToString(ParameterConstant.DateFormat);
            var condition = new ExceptionParamCondition
            {
                StartTime = request.startTime,
                EndTime = time, //request.endTime,
                ErrType = request.errType.ToInt(),
            };
            var sectionId = request.sectionID.ToInt();
            if (sectionId != 0)
            {
                condition.MachinIds = _machineRepository.GetNCLevelSectionMachineIds(sectionId, ProjectId);
            }
            var cncExceptionRepository = new ExceptionParamsSateRepository(CompanyId, ProjectId);
            var exceptions = cncExceptionRepository.GetNoPagedCncExceptionParamsSates(condition);

            var result = new ListExceptionTimesByDayResult();
            var xid = request.xID.ToInt();
            var yid = request.yID.ToInt();
            var patchId = request.patchID.ToInt();
            if (xid == 0)
            {
                var type = 0;
                if (patchId == 1)
                {
                    type = 11;
                }
                else if (patchId == 2)
                {
                    type = 12;
                }
                else
                {
                    type = patchId;
                }
                result.xData = DateTimeHelper.GetStrDateTimes(dtStart, dtEnd, type);
                DateTimeHelper.GetDateTimes(dtStart, dtEnd, type).ForEach(q =>
                {
                    result.xData2.Add(q.ToString(UnixTimeHelper.DateFormat));
                });
                var interal = DateTimeHelper.GetInteral(patchId);
                for (var i = 1; i <= result.xData2.Count; i++)
                {
                    DateTime start;
                    DateTime end;
                    if (patchId == 0)
                    {
                        start = DateTime.Parse(result.xData2[i - 1]);
                        end = DateTime.Parse(result.xData2[i - 1]).AddDays(interal).AddSeconds(-1);
                    }
                    else if (patchId == 1)
                    {
                        var weekStart = DateTimeHelper.GetWeekRangeStart(result.xData[i - 1]);
                        var weekEnd = DateTimeHelper.GetWeekRangeEnd(result.xData[i - 1]);
                        start = dtStart > weekStart ? dtStart : weekStart;
                        end = dtEnd < weekEnd ? dtEnd.AddDays(1).AddSeconds(-1) : weekEnd.AddDays(1).AddSeconds(-1);
                    }
                    else
                    {
                        start = DateTime.Parse(result.xData2[i - 1]);
                        var dts = start.AddMonths(1);
                        dts = dts.AddDays(0 - dts.Day).AddDays(1).AddSeconds(-1);
                        end = dts > dtEnd ? dtEnd.AddDays(1).AddSeconds(-1) : dts; //到月底
                    }

                    if (yid == 0)
                    {
                        result.yData[result.xData[i - 1]] = exceptions.Count(q => q.StartTime >= start && q.EndTime <= end).ToString();
                    }

                    if (yid == 1)
                    {
                        var total = exceptions.Where(q => q.StartTime >= start && q.EndTime <= end).Sum(q => q.TotalSecond);
                        result.yData[result.xData[i - 1]] = Math.Round((double)total / 60, 2).ToString();
                    }
                }
            }

            if (xid == 1)
            {
                //patchId 为levelId
                //取sectionID下面的设备
                var sections = _machineRepository.GetNCLevelSections(request.sectionID.ToInt(), ProjectId);
                var levels = sections.Where(q => q.levelid == patchId).ToList();
                if (levels.Any())
                {
                    result.xData = levels.Select(m => m.title).ToList();
                    var i = 0;
                    foreach (var levelSection in levels)
                    {
                        var machineIds = _machineRepository.GetNCLevelSectionMachineIds(levelSection.id, ProjectId);
                        if (yid == 0)
                        {
                            result.yData[result.xData[i]] = exceptions.Count(q => machineIds.Contains(q.MachineID)).ToString();
                        }

                        if (yid == 1)
                        {
                            result.yData[result.xData[i]] = exceptions.Where(q => machineIds.Contains(q.MachineID)).Sum(q => q.TotalSecond / 60).ToString();
                        }

                        i++;
                    }
                }
                else //最后一级
                {
                    var machine = _machineRepository.GetNCMachineBySectionId(sectionId, ProjectId);
                    result.xData = new List<string> { machine.name };
                    var machineIds = _machineRepository.GetNCLevelSectionMachineIds(sectionId, ProjectId);
                    if (yid == 0)
                    {
                        result.yData[result.xData[0]] = exceptions.Count(q => machineIds.Contains(q.MachineID)).ToString();
                    }

                    if (yid == 1)
                    {
                        result.yData[result.xData[0]] = exceptions.Where(q => machineIds.Contains(q.MachineID)).Sum(q => q.TotalSecond / 60).ToString();
                    }
                }
            }

            if (xid == 2)
            {
                result.xData = new List<string> { "500054", "500055", "500049" };
                for (var i = 1; i <= result.xData.Count; i++)
                {
                    if (yid == 0)
                    {
                        result.yData[result.xData[i - 1]] = exceptions.Count(q => q.Type == i).ToString();
                    }

                    if (yid == 1)
                    {
                        result.yData[result.xData[i - 1]] = exceptions.Where(q => q.Type == i).Sum(q => q.TotalSecond / 60).ToString();
                    }
                }
            }

            if (request.toexcel == 0)
            {
                return result;
            }

            var responses = new List<ResponseGetAlarmDataForAnalysis>();
            foreach (var data in result.yData)
            {
                responses.Add(new ResponseGetAlarmDataForAnalysis
                {
                    Abscissa = data.Key,
                    Ordinate = data.Value.ToDouble()
                });
            }
            var machines = _machineRepository.GetProjectLanguage(ProjectId);
            if (yid == 0)
            {
                switch (xid)
                {
                    case 0:
                        return ExportBarChart(responses, machines, (int)XTypes.Date);
                    case 1:
                        return ExportBarChart(responses, machines, (int)XTypes.Section);
                    default:
                        return ExportBarChart(responses, machines, (int)XTypes.OtherType);
                }
            }

            if (yid == 1)
            {
                switch (xid)
                {
                    case 0:
                        return ExportBarChart(responses, machines, (int)XTypes.Dates);
                    case 1:
                        return ExportBarChart(responses, machines, (int)XTypes.Sections);
                    default:
                        return ExportBarChart(responses, machines, (int)XTypes.OtherType);
                }
            }
            return ExportBarChart(responses, machines, (int)XTypes.OtherType);
        }

        //getFault3 设备报警分析 - 报警记录查询
        [HttpPost]
        public IActionResult GetMachineAlarmList([FromBody] RequestGetMachineAlarmList request)
        {
            if (request.toexcel != 0)
            {
                request.pagesize = 999999999;
            }
            try
            {
                var cncExceptionRepository = new AlarmAnalysResultRepository(CompanyId, ProjectId);
                var pageInfo = new Pagination(request.page, request.pagesize);
                var condition = new CncAlarmAnalysResultCondition
                {
                    MachinIds = _machineRepository.GetNCLevelSectionMachineIds(request.SectionID.ToInt(), ProjectId),
                    STime = request.Start,
                    ETime = request.End,
                    AlarmCode = request.AlarmCode,
                    AlarmContent = request.AlarmContent
                };

                var result = new List<ResponseGetMachineAlarmList>();

                var exceptions = cncExceptionRepository.GetPagedAlarmAnalysResults(pageInfo, condition);
                var machineIds = exceptions.Value.Select(m => m.machineId).Distinct();

                var stations = _machineRepository.GetNCMachinSectionInfos(machineIds, ProjectId).ToList();
                foreach (var exception in exceptions.Value)
                {
                    var machineStation = stations.FirstOrDefault(q => q.machineId == exception.machineId);
                    if (machineStation == null)
                    {
                        continue;
                    }
                    var entity = new ResponseGetMachineAlarmList
                    {
                        id = exception.id,
                        MachineCode = machineStation.section_name + "-" + machineStation.station_name,
                        Code = exception.code,
                        Message = exception.message,
                        //Duration = UnixTimeHelper.GetTimeBySecond((int)(exception.Etime - exception.Stime).TotalSeconds),
                        Duration = (exception.Etime - exception.Stime).TotalSeconds.ToString(),
                        Active = exception.status,
                        StartTime = exception.Stime.ToString(ParameterConstant.DateTimeFormat),
                        EndTime = exception.Etime.ToString(ParameterConstant.DateTimeFormat),
                        FaultContent = exception.FaultContent,
                        FaultSolution = exception.FaultSolution,
                        FaultReason = exception.FaultReason,
                        IsFault = exception.IsFault
                    };

                    result.Add(entity);
                }
                
                if (request.toexcel == 0)
                {
                    return new PagedObjectResult(result, exceptions.Key.TotalItemCount, request.page, request.pagesize);
                }
                var machines = _machineRepository.GetProjectLanguage(ProjectId);
                return ExportMachineAlarmList(result, machines);
            }
            catch (Exception e)
            {
                Logger.WriteLineError("get GetMachineAlarmList failed, error:" + e);
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
        }

        //getFault2 设备报警分析 报警数据分析
        [HttpPost]
        public IActionResult GetStatusList([FromBody] RequestGetStatusList request)
        {
            try
            {
                var cncExceptionRepository = new AlarmAnalysResultRepository(CompanyId, ProjectId);
                var pageInfo = new Pagination(request.page, request.pagesize);
                var condition = new CncAlarmAnalysResultCondition();
                var sectionId = request.sectionID.ToInt();
                if (sectionId != 0)
                {
                    condition.MachinIds = _machineRepository.GetNCLevelSectionMachineIds(sectionId, ProjectId);
                }

                condition.STime = request.startTime;
                condition.ETime = request.endTime;

                var result = new List<ResponseGetMachineAlarmStatusList>();

                var exceptions = cncExceptionRepository.GetPagedAlarmAnalysResults(pageInfo, condition);
                var machineIds = exceptions.Value.Select(m => m.machineId).Distinct().ToList();
                var validMachineSections = _machineRepository.GetNCLevelSectionNames(0, ProjectId);
                var machineTypes = _machineTypeRepository.GetMachineTypes(machineIds, ProjectId);
                foreach (var exception in exceptions.Value)
                {
                    var machine = validMachineSections.FirstOrDefault(q => q.machine_id == exception.machineId);
                    var machineType = machineTypes.FirstOrDefault(q => q.MachineId == exception.machineId);
                    var entity = new ResponseGetMachineAlarmStatusList
                    {
                        id = exception.id,
                        MachineCode = machine == null ? "" : machine.lastSecondSectionTitle + "-" + machine.lastSectionTitle,
                        MachineTitle = machineType == null ? "" : machineType.MachineType,
                        Code = exception.code,
                        Message = exception.message,
                        Active = exception.status,
                        Stime = UnixTimeHelper.GetUnixByShortDate(exception.Stime.ToString()),
                        Etime = UnixTimeHelper.GetUnixByShortDate(exception.Etime.ToString()),
                        FaultContent = exception.FaultContent ?? "",
                        FaultSolution = exception.FaultSolution ?? "",
                        FaultReason = exception.FaultReason ?? "",
                    };

                    result.Add(entity);
                }
                return new PagedObjectResult(result, exceptions.Key.TotalItemCount, request.page, request.pagesize);
            }
            catch (Exception e)
            {
                Logger.WriteLineError("get GetStatusList failed, error:" + e);
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
        }

        //GetAlarmInfoFromMiddle 设备报警分析 报警代码管理
        [HttpPost]
        public IActionResult GetAlarmInfoForEdit([FromBody] RequestGetAlarmInfoForEdit request)
        {
            if (request.toexcel != 0)
            {
                request.pageSize = 999999999;
            }
            if (request.machineID == null || !request.machineID.Any())
            {
                return new PagedObjectResult(null, 0, request.page, request.pageSize);
            }
            var condition = new CncAlarmAnalysResultCondition
            {
                MachinIds = request.machineID,
                AlarmCode = request.code,
                Status = request.status
            };
            var result = new List<ResponseGetMachineAlarmListForEdit>();

            var cncExceptionRepository = new AlarmAnalysResultRepository(CompanyId, ProjectId);
            var exceptions = cncExceptionRepository.GetPagedAlarmAnalysResultsForEdit(new Pagination(request.page, request.pageSize), condition);

            var machineIds = exceptions.Value.Select(m => m.machineId).Distinct().ToList();
            var machineTypes = _machineTypeRepository.GetMachineTypes(machineIds, ProjectId);
            var stations = _machineRepository.GetNCLevelSectionNames(machineIds, ProjectId).ToList();
            foreach (var exception in exceptions.Value)
            {
                var machineType = machineTypes.FirstOrDefault(q => q.MachineId == exception.machineId);
                var station = stations.FirstOrDefault(q => q.machine_id == exception.machineId);
                var entity = new ResponseGetMachineAlarmListForEdit
                {
                    id = exception.machineId,
                    fault_code = exception.code,
                    fault_content = exception.FaultContent ?? "",
                    fault_solution = exception.FaultSolution ?? "",
                    fault_reason = exception.FaultReason ?? "",
                    remark = exception.Remark ?? "",
                    error_msg = exception.message ?? "",
                    alarm_times = exception.AlertTimes,
                    machine_code = station != null ? station.machine_code : "",
                    machine_type = machineType == null ? "" : machineType.MachineType,
                    machine_location = station == null ? "" : station.lastSecondSectionTitle + "-" + station.lastSectionTitle,
                    isFault = exception.IsFault,
                    markTime = exception.MarkTime?.ToString(ParameterConstant.DateTimeFormat) ?? ""
                };
                result.Add(entity);
            }
            if (request.toexcel == 0)
            {
                return new PagedObjectResult(result, exceptions.Key.TotalItemCount, request.page, request.pageSize);
            }
            var machines = _machineRepository.GetProjectLanguage(ProjectId);
            return ExportAlarmInfoForEdit(result, machines);
        }

        //设备报警分析 修改报警代码
        [HttpPost]
        public IActionResult UpdateAlarm([FromBody] RequestUpdateAlarm request)
        {
            if (request.ids == null || !request.ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }

            var content = string.Empty;//手动录入
            if (string.IsNullOrWhiteSpace(request.faulttype))
            {
                if (string.IsNullOrWhiteSpace(request.inputtype))
                {
                    throw new BadRequestException(RequestEnum.ParameterError);
                }
                content = request.inputtype;
                //如果不存在，则插入数据库
                var isexist = _faultTypeRepository.Get(q => q.fault_name == request.inputtype && q.project_id == ProjectId && q.status == (int)RowState.Valid);
                if (isexist == null)
                {
                    var entity = new siger_project_machine_fault_type
                    {
                        fault_name = request.inputtype,
                        create_time = DateTime.Now,
                        creator_mid = UserId,
                        project_id = ProjectId
                    };
                    _faultTypeRepository.Insert(entity);
                    _unitOfWork.Commit();
                }
            }
            else
            {
                var fault = _faultTypeRepository.Get(q => q.id == request.faulttype.ToInt() && q.project_id == ProjectId && q.status == (int)RowState.Valid);
                if (fault != null)
                {
                    content = fault.fault_name;
                }
            }

            var cncExceptionRepository = new AlarmAnalysResultRepository(CompanyId, ProjectId);
            var setFaultRepository = new AlarmRulesConfigRepository(CompanyId, ProjectId, false);

            foreach (var alarmCode in request.ids)
            {
                cncExceptionRepository.UpdateFaults(alarmCode.id.ToInt(), alarmCode.code, content,
                    request.faultReason, request.faultSolution, request.remark, request.isfault.ToInt());

                //如果是非故障类型，则添加到redis
                if (request.isfault.ToInt() == 2)
                {
                    setFaultRepository.SetFaultCode(alarmCode.id.ToInt(), alarmCode.code, 0);
                }
                else
                {
                    setFaultRepository.SetFaultCode(alarmCode.id.ToInt(), alarmCode.code, 1);
                }
            }
            setFaultRepository.Dispose();

            return new ObjectResult(CommonEnum.Succefull);
        }

        [HttpGet]
        public IActionResult GetMachineFaultTypes()
        {
            var list = _faultTypeRepository.GetList(q => q.project_id == ProjectId && q.status == (int)RowState.Valid);
            var responses = new List<ResponseIdName>();
            foreach (var faultType in list.ToList())
            {
                responses.Add(new ResponseIdName
                {
                    id = faultType.id,
                    name = faultType.fault_name
                });
            }
            return new ObjectResult(responses);
        }

        //getFault2 设备报警分析 报警数据分析
        [HttpPost]
        public IActionResult GetAlarmDataForAnalysis([FromBody] RequestListExceptionTimesByDay request)
        {
            //xID - 0:时间 1：层级 2：故障代码
            //yID - 0:次数 1：时长
            //patchID - xID=0时 0:天 1：周 2：月；xID=4时 patchID为levelID；xID=5时，pactchid为errorCode；xID=5时，按照故障类型
            if (!DateTime.TryParse(request.startTime, out var dtStart))
            {
                throw new ServerException(500146);
            }

            if (!DateTime.TryParse(request.endTime, out var dtEnd))
            {
                throw new ServerException(500146);
            }

            if (dtStart > dtEnd)
            {
                throw new ServerException(100158);
            }

            var time = request.endTime.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss");
            var condition = new CncAlarmAnalysResultCondition
            {
                STime = request.startTime,
                ETime = request.endTime,
            };
            var sectionId = request.sectionID.ToInt();
            if (sectionId != 0)
            {
                condition.MachinIds = _machineRepository.GetNCLevelSectionMachineIds(sectionId, ProjectId);
            }

            var cncExceptionRepository = new AlarmAnalysResultRepository(CompanyId, ProjectId);
            var exceptions = cncExceptionRepository.GetNoPagedCncExceptionParamsSates(condition);

            var result = new List<ResponseGetAlarmDataForAnalysis>();
            var responses = new List<ResponseGetAlarmDataForAnalysis>();
            var xid = request.xID.ToInt();
            var yid = request.yID.ToInt();
            var patchId = request.patchID.ToInt();
            //处理柏拉图数据
            var times = dtEnd.AddDays(1).AddSeconds(-1);
            var all = yid == 0
                ? exceptions.Count(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                : exceptions.Where(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                    .Sum(q => (q.Etime - q.Stime).TotalSeconds);
            double rate = 0;
            if (xid == 0)
            {
                var type = 0;
                if (patchId == 1)
                {
                    type = 11;
                }
                else if (patchId == 2)
                {
                    type = 12;
                }
                else
                {
                    type = patchId;
                }
                var interal = DateTimeHelper.GetInteral(patchId);
                var dates = DateTimeHelper.GetDateTimes(dtStart, dtEnd, type);
                var xData = DateTimeHelper.GetStrDateTimes(dtStart, dtEnd, type);
                for (int i = 0; i < dates.Count; i++)
                {
                    var response = new ResponseGetAlarmDataForAnalysis();
                    DateTime start;
                    DateTime end;
                    if (patchId == 0)
                    {
                        start = dates[i];
                        end = dates[i].AddDays(interal);
                        response.Abscissa = start.ToString(ParameterConstant.DateFormat);
                    }
                    else if (patchId == 1)
                    {
                        response.Abscissa = xData[i];
                        var weekStart = DateTimeHelper.GetWeekRangeStart(response.Abscissa);
                        var weekEnd = DateTimeHelper.GetWeekRangeEnd(response.Abscissa);
                        start = dtStart > weekStart ? dtStart : weekStart;
                        end = dtEnd < weekEnd ? dtEnd : weekEnd.AddDays(1).AddSeconds(-1);
                    }
                    else
                    {
                        start = dates[i];
                        var dts = start.AddMonths(1);
                        dts = dts.AddDays(0 - dts.Day).AddDays(1).AddSeconds(-1);
                        end = dts > dtEnd ? dtEnd.AddDays(1).AddSeconds(-1) : dts; //到月底
                        response.Abscissa = end.ToString("yyyy-MM");
                    }

                    if (yid == 0)
                    {
                        response.Ordinate = (int)exceptions.Count(q => q.Stime >= start && q.Stime <= end);
                    }

                    if (yid == 1)
                    {
                        response.Ordinate = (int)exceptions.Where(q => q.Stime >= start && q.Stime <= end)
                            .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                    }

                    response.Rate = rate + response.Ordinate / all;
                    rate += response.Ordinate / all;
                    responses.Add(response);
                }
            }

            if (xid == 4)
            {
                //patchId 为levelId
                //取sectionID下面的设备
                try
                {
                    var allresult = 0.0;
                    var sections = _machineRepository.GetNCLevelSections(sectionId, ProjectId);
                    var levels = sections.Where(q => q.levelid == patchId).ToList();
                    if (levels.Any())
                    {
                        foreach (var levelSection in levels)
                        {
                            var response = new ResponseGetAlarmDataForAnalysis();
                            response.Abscissa = levelSection.title;
                            var machineIds = _machineRepository.GetNCLevelSectionMachineIds(levelSection.id, ProjectId);
                            condition.MachinIds = machineIds;
                            var results = cncExceptionRepository.GetNoPagedCncExceptionParamsSates(condition);
                            allresult += yid == 0
                                ? results.Count(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                                : results.Where(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                                    .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                            if (yid == 0)
                            {
                                response.Ordinate = results.Count(q => machineIds.Contains(q.machineId));
                            }

                            if (yid == 1)
                            {
                                response.Ordinate = (int)results.Where(q => machineIds.Contains(q.machineId))
                                    .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                            }

                            result.Add(response);
                        }
                    }
                    else //最后一级
                    {
                        var machine = _machineRepository.GetNCMachineBySectionId(sectionId, ProjectId);
                        var response = new ResponseGetAlarmDataForAnalysis();
                        response.Abscissa = machine != null ? machine.name : "";
                        var machineIds = _machineRepository.GetNCLevelSectionMachineIds(sectionId, ProjectId);
                        condition.MachinIds = machineIds;
                        var results = cncExceptionRepository.GetNoPagedCncExceptionParamsSates(condition);
                        allresult += yid == 0
                            ? results.Count(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                            : results.Where(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                                .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                        if (yid == 0)
                        {
                            response.Ordinate = exceptions.Count(q => machineIds.Contains(q.machineId));
                        }

                        if (yid == 1)
                        {
                            response.Ordinate = (int)exceptions.Where(q => machineIds.Contains(q.machineId))
                                .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                        }

                        result.Add(response);
                    }

                    foreach (var analysis in result.OrderByDescending(q => q.Ordinate).ToList())
                    {
                        var response = new ResponseGetAlarmDataForAnalysis
                        { Abscissa = analysis.Abscissa, Ordinate = analysis.Ordinate };
                        response.Rate = rate + analysis.Ordinate / allresult;
                        rate += analysis.Ordinate / allresult;
                        responses.Add(response);
                    }
                }
                catch
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }
            }

            if (xid == 5)
            {
                var codes = exceptions.Select(m => m.code).Distinct();
                foreach (var code in codes)
                {
                    var response = new ResponseGetAlarmDataForAnalysis { Abscissa = code };
                    if (yid == 0)
                    {
                        response.Ordinate = (int)exceptions.Count(q => q.code == code);
                    }

                    if (yid == 1)
                    {
                        response.Ordinate = (int)exceptions.Where(q => q.code == code)
                            .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                    }

                    result.Add(response);
                }

                foreach (var analysis in result.OrderByDescending(q => q.Ordinate).ToList())
                {
                    var response = new ResponseGetAlarmDataForAnalysis
                    { Abscissa = analysis.Abscissa, Ordinate = analysis.Ordinate };
                    response.Rate = rate + analysis.Ordinate / all;
                    rate += analysis.Ordinate / all;
                    responses.Add(response);
                }
            }

            if (xid == 6)
            {
                var allresult = 0.0;
                var codes = exceptions.Select(m => m.FaultContent).Distinct();
                foreach (var code in codes)
                {
                    if (string.IsNullOrWhiteSpace(code))
                    {
                        continue;
                    }

                    var response = new ResponseGetAlarmDataForAnalysis { Abscissa = code };
                    if (yid == 0)
                    {
                        response.Ordinate = (int)exceptions.Count(q => q.FaultContent == code);
                    }

                    if (yid == 1)
                    {
                        response.Ordinate = (int)exceptions.Where(q => q.FaultContent == code)
                            .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                    }

                    allresult += response.Ordinate;
                    result.Add(response);
                }

                foreach (var analysis in result.OrderByDescending(q => q.Ordinate).ToList())
                {
                    var response = new ResponseGetAlarmDataForAnalysis
                    { Abscissa = analysis.Abscissa, Ordinate = analysis.Ordinate };
                    response.Rate = rate + analysis.Ordinate / allresult;
                    rate += analysis.Ordinate / allresult;
                    responses.Add(response);
                }
            }

            if (request.toexcel == 0)
            {
                return new ObjectResult(responses);
            }
            var machines = _machineRepository.GetProjectLanguage(ProjectId);
            if (yid == 0)
            {
                switch (xid)
                {
                    case 0:
                        return ExportBarChart(responses, machines, (int)XTypes.DateType);
                    case 4:
                        return ExportBarChart(responses, machines, (int)XTypes.SectionType);
                    case 5:
                        return ExportBarChart(responses, machines, (int)XTypes.FaultCodeType);
                    case 6:
                        return ExportBarChart(responses, machines, (int)XTypes.FaultType);
                    default:
                        return ExportBarChart(responses, machines, (int)XTypes.OtherType);
                }
            }

            if (yid == 1)
            {
                switch (xid)
                {
                    case 0:
                        return ExportBarChart(responses, machines, (int)XTypes.DateTypes);
                    case 4:
                        return ExportBarChart(responses, machines, (int)XTypes.SectionTypes);
                    case 5:
                        return ExportBarChart(responses, machines, (int)XTypes.FaultCodeTypes);
                    case 6:
                        return ExportBarChart(responses, machines, (int)XTypes.FaultTypes);
                    default:
                        return ExportBarChart(responses, machines, (int)XTypes.OtherType);
                }
            }

            return ExportBarChart(responses, machines, (int)XTypes.OtherType);

        }

        //getFault2 设备报警分析 报警数据分析
        [HttpPost]
        public IActionResult GetAlarmDataForAnalysisCl([FromBody] RequestListExceptionTimesByDaycl request)
        {
            //xID - 0:时间 1：层级 2：故障代码
            //yID - 0:次数 1：时长
            //patchID - xID=0时 0:天 1：周 2：月；xID=4时 patchID为levelID；xID=5时，pactchid为errorCode；xID=5时，按照故障类型
            if (!DateTime.TryParse(request.startTime, out var dtStart))
            {
                throw new ServerException(500146);
            }

            if (!DateTime.TryParse(request.endTime, out var dtEnd))
            {
                throw new ServerException(500146);
            }

            if (dtStart > dtEnd)
            {
                throw new ServerException(100158);
            }

            var time = request.endTime.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss");
            var condition = new CncAlarmAnalysResultCondition
            {
                STime = request.startTime,
                ETime = request.endTime,
            };
            var sectionId = request.sectionID.ToInt();
            if (sectionId != 0)
            {
                condition.MachinIds = _machineRepository.GetNCLevelSectionMachineIds(sectionId, ProjectId);
            }

            var cncExceptionRepository = new AlarmAnalysResultRepository(CompanyId, ProjectId);
            var exceptions = cncExceptionRepository.GetNoPagedCncExceptionParamsSates(condition);

            var result = new List<ResponseGetAlarmDataForAnalysisNew>();
            var responses = new List<ResponseGetAlarmDataForAnalysisNew>();
            var xid = 0;
            //var yid = request.yID.ToInt();
            var patchId = 0;
            //处理柏拉图数据
            var times = dtEnd.AddDays(1).AddSeconds(-1);

            var allNumber = exceptions.Count(q => q.Stime >= dtStart && q.Stime <= dtEnd);

            var allTime = exceptions.Where(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                    .Sum(q => (q.Etime - q.Stime).TotalSeconds);

            double rate = 0;
            double ratecl = 0;
            if (xid == 0)
            {
                var type = 0;
                if (patchId == 1)
                {
                    type = 11;
                }
                else if (patchId == 2)
                {
                    type = 12;
                }
                else
                {
                    type = patchId;
                }
                var interal = DateTimeHelper.GetInteral(patchId);
                var dates = DateTimeHelper.GetDateTimes(dtStart, dtEnd, type);
                var xData = DateTimeHelper.GetStrDateTimes(dtStart, dtEnd, type);
                for (int i = 0; i < dates.Count; i++)
                {
                    var response = new ResponseGetAlarmDataForAnalysisNew();
                    DateTime start;
                    DateTime end;
                    DateTime startTime;
                    DateTime endTime;
                    if (patchId == 0)
                    {
                        start = dates[i];
                        end = dates[i].AddDays(interal);
                        startTime = dates[i];
                        endTime = dates[i].AddDays(interal);
                        response.Abscissa = start.ToString(ParameterConstant.DateFormat);
                        response.Abscissacl = start.ToString(ParameterConstant.DateFormat);
                    }
                    else if (patchId == 1)
                    {
                        response.Abscissa = xData[i];
                        response.Abscissacl = xData[i];

                        var weekStart = DateTimeHelper.GetWeekRangeStart(response.Abscissa);
                        var weekEnd = DateTimeHelper.GetWeekRangeEnd(response.Abscissa);
                        var weekStartTime = DateTimeHelper.GetWeekRangeStart(response.Abscissacl);
                        var weekEndTime = DateTimeHelper.GetWeekRangeEnd(response.Abscissacl);
                        startTime = dtStart > weekStart ? dtStart : weekStartTime;
                        start = dtStart > weekStart ? dtStart : weekStart;
                        endTime = dtEnd < weekEnd ? dtEnd : weekEndTime.AddDays(1).AddSeconds(-1);
                        end = dtEnd < weekEnd ? dtEnd : weekEnd.AddDays(1).AddSeconds(-1);
                    }
                    else
                    {
                        start = dates[i];
                        startTime = dates[i];

                        var dts = start.AddMonths(1);
                        var dtsTime = startTime.AddMonths(1);
                        dtsTime = dtsTime.AddDays(0 - dtsTime.Day).AddDays(1).AddSeconds(-1);
                        endTime = dtsTime > dtEnd ? dtEnd.AddDays(1).AddSeconds(-1) : dtsTime; //到月底
                        dts = dts.AddDays(0 - dts.Day).AddDays(1).AddSeconds(-1);
                        end = dts > dtEnd ? dtEnd.AddDays(1).AddSeconds(-1) : dts; //到月底
                        response.Abscissa = end.ToString("yyyy-MM");
                        response.Abscissacl = endTime.ToString("yyyy-MM");
                    }

                    response.Ordinate = (int)exceptions.Count(q => q.Stime >= start && q.Stime <= end);
                    response.Ordinatecl = (int)exceptions.Where(q => q.Stime >= start && q.Stime <= end)
                        .Sum(q => (q.Etime - q.Stime).TotalSeconds);

                    response.Rate = rate + response.Ordinate / allNumber;
                    rate += response.Ordinate / allNumber;
                    response.Ratecl = ratecl + response.Ordinatecl / allTime;
                    ratecl += response.Ordinatecl / allTime;
                    responses.Add(response);
                }
            }
            return new ObjectResult(responses);        
        }

        /// <summary>
        /// 长江润发
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        //getFault2 设备报警分析 报警数据分析
        [HttpPost]
        public IActionResult GetAlarmDataForAnalysisCJ([FromBody] RequestListExceptionTimesByDay request)
        {
            //xID - 0:时间 1：层级 2：故障代码
            //yID - 0:次数 1：时长
            //patchID - xID=0时 0:天 1：周 2：月；xID=4时 patchID为levelID；xID=5时，pactchid为errorCode；xID=5时，按照故障类型
            if (!DateTime.TryParse(request.startTime, out var dtStart))
            {
                throw new ServerException(500146);
            }

            if (!DateTime.TryParse(request.endTime, out var dtEnd))
            {
                throw new ServerException(500146);
            }
            dtEnd = dtEnd > DateTime.Now ? DateTime.Now : dtEnd;
            if (dtStart > dtEnd)
            {
                throw new ServerException(100158);
            }
            
            var time = request.endTime.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss");
            var condition = new CncAlarmAnalysResultCondition
            {
                STime = request.startTime,
                ETime = request.endTime,
            };
            var sectionId = request.sectionID.ToInt();
            if (sectionId != 0)
            {
                condition.MachinIds = _machineRepository.GetNCLevelSectionMachineIds(sectionId, ProjectId);
            }

            var cncExceptionRepository = new AlarmAnalysResultRepository(CompanyId, ProjectId);
            var exceptions = cncExceptionRepository.GetNoPagedCncExceptionParamsSates(condition);

            var result = new List<ResponseGetAlarmDataForAnalysis>();
            var responses = new List<ResponseGetAlarmDataForAnalysis>();
            var xid = request.xID.ToInt();
            var yid = request.yID.ToInt();
            var patchId = request.patchID.ToInt();
            //处理柏拉图数据
            var times = dtEnd.AddDays(1).AddSeconds(-1);
            var all = yid == 0
                ? exceptions.Count(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                : exceptions.Where(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                    .Sum(q => (q.Etime - q.Stime).TotalSeconds);
            double rate = 0;
            if (xid == 0)
            {
                var type = 0;
                if (patchId == 1)
                {
                    type = 11;
                }
                else if (patchId == 2)
                {
                    type = 12;
                }
                else
                {
                    type = patchId;
                }
                var interal = DateTimeHelper.GetInteral(patchId);
                var dates = DateTimeHelper.GetDateTimes(dtStart, dtEnd, type);
                var xData = DateTimeHelper.GetStrDateTimes(dtStart, dtEnd, type);
                //跨度超过七周，去掉第一周
                if (dates.Count() > 7)
                {
                    dates.RemoveAt(0);
                    xData.RemoveAt(0);
                }
                for (int i = 0; i < dates.Count; i++)
                {
                    var response = new ResponseGetAlarmDataForAnalysis();
                    DateTime start;
                    DateTime end;
                    if (patchId == 0)
                    {
                        start = dates[i];
                        end = dates[i].AddDays(interal);
                        response.Abscissa = start.ToString(ParameterConstant.DateFormat);
                    }
                    else if (patchId == 1)
                    {
                        response.Abscissa = xData[i];
                        var weekStart = DateTimeHelper.GetWeekRangeStart(response.Abscissa);
                        var weekEnd = DateTimeHelper.GetWeekRangeEnd(response.Abscissa);
                        start = dtStart > weekStart ? dtStart : weekStart;
                        end = dtEnd < weekEnd ? dtEnd : weekEnd.AddDays(1).AddSeconds(-1);
                    }
                    else
                    {
                        start = dates[i];
                        var dts = start.AddMonths(1);
                        dts = dts.AddDays(0 - dts.Day).AddDays(1).AddSeconds(-1);
                        end = dts > dtEnd ? dtEnd.AddDays(1).AddSeconds(-1) : dts; //到月底
                        response.Abscissa = end.ToString("yyyy-MM");
                    }

                    if (yid == 0)
                    {
                        response.Ordinate = (int)exceptions.Count(q => q.Stime >= start && q.Stime <= end);
                    }

                    if (yid == 1)
                    {
                        response.Ordinate = (int)exceptions.Where(q => q.Stime >= start && q.Stime <= end)
                            .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                    }

                    response.Rate = rate + response.Ordinate / all;
                    rate += response.Ordinate / all;
                    responses.Add(response);
                }
            }

            if (xid == 4)
            {
                //patchId 为levelId
                //取sectionID下面的设备
                try
                {
                    var allresult = 0.0;
                    var sections = _machineRepository.GetNCLevelSections(sectionId, ProjectId);
                    var levels = sections.Where(q => q.levelid == patchId).ToList();
                    if (levels.Any())
                    {
                        foreach (var levelSection in levels)
                        {
                            var response = new ResponseGetAlarmDataForAnalysis();
                            response.Abscissa = levelSection.title;
                            var machineIds = _machineRepository.GetNCLevelSectionMachineIds(levelSection.id, ProjectId);
                            condition.MachinIds = machineIds;
                            var results = cncExceptionRepository.GetNoPagedCncExceptionParamsSates(condition);
                            allresult += yid == 0
                                ? results.Count(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                                : results.Where(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                                    .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                            if (yid == 0)
                            {
                                response.Ordinate = results.Count(q => machineIds.Contains(q.machineId));
                            }

                            if (yid == 1)
                            {
                                response.Ordinate = (int)results.Where(q => machineIds.Contains(q.machineId))
                                    .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                            }

                            result.Add(response);
                        }
                    }
                    else //最后一级
                    {
                        var machine = _machineRepository.GetNCMachineBySectionId(sectionId, ProjectId);
                        var response = new ResponseGetAlarmDataForAnalysis();
                        response.Abscissa = machine != null ? machine.name : "";
                        var machineIds = _machineRepository.GetNCLevelSectionMachineIds(sectionId, ProjectId);
                        condition.MachinIds = machineIds;
                        var results = cncExceptionRepository.GetNoPagedCncExceptionParamsSates(condition);
                        allresult += yid == 0
                            ? results.Count(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                            : results.Where(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                                .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                        if (yid == 0)
                        {
                            response.Ordinate = exceptions.Count(q => machineIds.Contains(q.machineId));
                        }

                        if (yid == 1)
                        {
                            response.Ordinate = (int)exceptions.Where(q => machineIds.Contains(q.machineId))
                                .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                        }

                        result.Add(response);
                    }

                    foreach (var analysis in result.OrderByDescending(q => q.Ordinate).ToList())
                    {
                        var response = new ResponseGetAlarmDataForAnalysis
                        { Abscissa = analysis.Abscissa, Ordinate = analysis.Ordinate };
                        response.Rate = rate + analysis.Ordinate / allresult;
                        rate += analysis.Ordinate / allresult;
                        responses.Add(response);
                    }
                }
                catch
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }
            }

            if (xid == 5)
            {
                var codes = exceptions.Select(m => m.code).Distinct();
                foreach (var code in codes)
                {
                    var response = new ResponseGetAlarmDataForAnalysis { Abscissa = code };
                    if (yid == 0)
                    {
                        response.Ordinate = (int)exceptions.Count(q => q.code == code);
                    }

                    if (yid == 1)
                    {
                        response.Ordinate = (int)exceptions.Where(q => q.code == code)
                            .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                    }

                    result.Add(response);
                }

                foreach (var analysis in result.OrderByDescending(q => q.Ordinate).ToList())
                {
                    var response = new ResponseGetAlarmDataForAnalysis
                    { Abscissa = analysis.Abscissa, Ordinate = analysis.Ordinate };
                    response.Rate = rate + analysis.Ordinate / all;
                    rate += analysis.Ordinate / all;
                    responses.Add(response);
                }
            }

            if (xid == 6)
            {
                var allresult = 0.0;
                var codes = exceptions.Select(m => m.FaultContent).Distinct();
                foreach (var code in codes)
                {
                    if (string.IsNullOrWhiteSpace(code))
                    {
                        continue;
                    }

                    var response = new ResponseGetAlarmDataForAnalysis { Abscissa = code };
                    if (yid == 0)
                    {
                        response.Ordinate = (int)exceptions.Count(q => q.FaultContent == code);
                    }

                    if (yid == 1)
                    {
                        response.Ordinate = (int)exceptions.Where(q => q.FaultContent == code)
                            .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                    }

                    allresult += response.Ordinate;
                    result.Add(response);
                }

                foreach (var analysis in result.OrderByDescending(q => q.Ordinate).ToList())
                {
                    var response = new ResponseGetAlarmDataForAnalysis
                    { Abscissa = analysis.Abscissa, Ordinate = analysis.Ordinate };
                    response.Rate = rate + analysis.Ordinate / allresult;
                    rate += analysis.Ordinate / allresult;
                    responses.Add(response);
                }
            }

            if (request.toexcel == 0)
            {
                return new ObjectResult(responses);
            }
            var machines = _machineRepository.GetProjectLanguage(ProjectId);

            if (yid == 0)
            {
                switch (xid)
                {
                    case 0:
                        return ExportBarChart(responses, machines, (int)XTypes.DateType);
                    case 4:
                        return ExportBarChart(responses, machines, (int)XTypes.SectionType);
                    case 5:
                        return ExportBarChart(responses, machines, (int)XTypes.FaultCodeType);
                    case 6:
                        return ExportBarChart(responses, machines, (int)XTypes.FaultType);
                    default:
                        return ExportBarChart(responses, machines, (int)XTypes.OtherType);
                }
            }

            if (yid == 1)
            {
                switch (xid)
                {
                    case 0:
                        return ExportBarChart(responses, machines, (int)XTypes.DateTypes);
                    case 4:
                        return ExportBarChart(responses, machines, (int)XTypes.SectionTypes);
                    case 5:
                        return ExportBarChart(responses, machines, (int)XTypes.FaultCodeTypes);
                    case 6:
                        return ExportBarChart(responses, machines, (int)XTypes.FaultTypes);
                    default:
                        return ExportBarChart(responses, machines, (int)XTypes.OtherType);
                }
            }
            return ExportBarChart(responses, machines, (int)XTypes.OtherType);

        }

        //getFault2 设备报警分析 报警数据分析  //大屏展示
        [HttpGet]
        public IActionResult GetAlarmDataForAnalysList(string patial_code, string page_id, int projectid)
        {
            var yID = "1";
            var sectionID = 0;
            var patchId = 0;
            var startTime = DateTime.Now.ToString(ParameterConstant.DateFormat);
            var endTime = DateTime.Now.ToString(ParameterConstant.DateTimeFormat);
            var pageId = page_id.ToInt();
            if (pageId == 0)
            {
                throw new ServerException(500195);
            }
            var res = _combPageConditionRepository.Get(q => q.comb_page_id == page_id && q.page_patial_code == patial_code);
            sectionID = res.condition.ToInt();
            var patch = _levelSectionRepository.Get(q => q.parentid == sectionID && q.projectid == projectid);
            if (patch != null)
            {
                sectionID = patch.id;
                while (sectionID > 0)
                {
                    var patchs = _levelSectionRepository.GetList(q => q.parentid == sectionID && q.projectid == projectid).ToList();
                    if (patchs.Any())
                    {
                        sectionID = patchs.FirstOrDefault().id;
                    }
                    else
                    {
                        var patches = _levelSectionRepository.Get(q => q.id == sectionID && q.projectid == projectid);
                        patchId = patches.levelid;
                        sectionID = 0;
                    }
                }
            }
            else
            {
                var patches = _levelSectionRepository.Get(q => q.id == sectionID && q.projectid == projectid);
                patchId = patches.levelid;
            }


            //xID - 0:时间 1：层级 2：故障代码
            //yID - 0:次数 1：时长
            //patchID - xID=0时 0:天 1：周 2：月；xID=4时 patchID为levelID；xID=5时，pactchid为errorCode；xID=5时，按照故障类型
            if (!DateTime.TryParse(startTime, out var dtStart))
            {
                throw new ServerException(500146);
            }

            if (!DateTime.TryParse(endTime, out var dtEnd))
            {
                throw new ServerException(500146);
            }

            if (dtStart > dtEnd)
            {
                throw new ServerException(100158);
            }

            var time = endTime.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss");
            var condition = new CncAlarmAnalysResultCondition
            {
                STime = startTime,
                ETime = endTime,
            };
            var sectionId = res != null ? res.condition.ToInt() : 0;
            if (sectionId != 0)
            {
                condition.MachinIds = _machineRepository.GetNCLevelSectionMachineIds(sectionId, projectid);
            }

            var cncExceptionRepository = new AlarmAnalysResultRepository(CompanyId, projectid);
            var exceptions = cncExceptionRepository.GetNoPagedCncExceptionParamsSates(condition);

            var result = new List<ResponseGetAlarmDataForAnalysis>();
            var responses = new List<ResponseGetAlarmDataForAnalysis>();
            var yid = yID.ToInt();
            //处理柏拉图数据
            var times = dtEnd.AddDays(1).AddSeconds(-1);
            var all = yid == 0
                ? exceptions.Count(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                : exceptions.Where(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                    .Sum(q => (q.Etime - q.Stime).TotalSeconds);
            double rate = 0;
            //patchId 为levelId
            //取sectionID下面的设备
            try
            {
                var allresult = 0.0;
                var sections = _machineRepository.GetNCLevelSections(sectionId, projectid);
                var levels = sections.Where(q => q.levelid == patchId).ToList();
                if (levels.Any())
                {
                    foreach (var levelSection in levels)
                    {
                        var response = new ResponseGetAlarmDataForAnalysis();
                        response.Abscissa = levelSection.title;
                        var machineIds = _machineRepository.GetNCLevelSectionMachineIds(levelSection.id, projectid);
                        condition.MachinIds = machineIds;
                        var results = cncExceptionRepository.GetNoPagedCncExceptionParamsSates(condition);
                        allresult += yid == 0
                            ? results.Count(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                            : results.Where(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                                .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                        response.Ordinate = (int)results.Where(q => machineIds.Contains(q.machineId))
                            .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                        result.Add(response);
                    }
                }
                else //最后一级
                {
                    var machine = _machineRepository.GetNCMachineBySectionId(sectionId, projectid);
                    var response = new ResponseGetAlarmDataForAnalysis();
                    response.Abscissa = machine != null ? machine.name : "";
                    var machineIds = _machineRepository.GetNCLevelSectionMachineIds(sectionId, projectid);
                    condition.MachinIds = machineIds;
                    var results = cncExceptionRepository.GetNoPagedCncExceptionParamsSates(condition);
                    allresult += yid == 0
                        ? results.Count(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                        : results.Where(q => q.Stime >= dtStart && q.Stime <= dtEnd)
                            .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                    response.Ordinate = (int)exceptions.Where(q => machineIds.Contains(q.machineId))
                        .Sum(q => (q.Etime - q.Stime).TotalSeconds);
                    result.Add(response);
                }

                foreach (var analysis in result.OrderByDescending(q => q.Ordinate).ToList())
                {
                    var response = new ResponseGetAlarmDataForAnalysis
                    { Abscissa = analysis.Abscissa, Ordinate = analysis.Ordinate };
                    response.Rate = rate + analysis.Ordinate / allresult;
                    rate += analysis.Ordinate / allresult;
                    responses.Add(response);
                }
            }
            catch
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            return new ObjectResult(responses);
        }

        [HttpGet]
        public IActionResult SelectMachineIDArr(int levelID, string typeID)
        {
            return new ObjectResult(_machineRepository.GetNCMachinIdsBySectionId(levelID, typeID.ToInt(), ProjectId));
        }
    }
}