using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCNC.Result;
using Siger.Middlelayer.CncRepository.Entities;
using Siger.Middlelayer.CncRepository.Repositories.Interface;
using Siger.Middlelayer.CncRepository.Response;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Dapper;
using Siger.Middlelayer.Dapper.ResultData;
using Siger.Middlelayer.Dapper.Utilities.Machine;
using Siger.Middlelayer.Dapper.Utilities.Oee;
using Siger.Middlelayer.Dapper.Utilities.Slice;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Redis.RedisEntities;
using Siger.Middlelayer.Redis.Repositories;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Share.Models;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Repository.Entities;
using System.Net.Http;
using Siger.ApiCommon.Filters;
using Newtonsoft.Json;
using System.Text;
using Siger.Middlelayer.Common.Configuration;
using Siger.Middlelayer.Repository.Response;

namespace Siger.ApiCNC.Controllers
{
    public class MachineController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly IMachineParamAlarmRepository _machineParamAlarmRepository;
        private readonly IProductionBeatSetRepository _beatSetRepository;
        private readonly IDashboardCombPageConditionTwoRepository _combPageConditionRepository;
        private readonly IProductionTimeRepository _timeRepository;
        private readonly ISigerProjectLevelRepository _levelRepository;
        private readonly ISigerProjectLevelSectionRepository _levelSectionRepository;
        private readonly ISigerProjectDashboardFixpathRepository _dashboardFixpathRepository;
        private readonly ISigerProjectBoxRepository _boxRepository;
        private readonly ISigerProjectRepository _projectRepository;
        private readonly ISigerCompanyRepository _companyRepository;
        private readonly IProductionTimeAllocationRepository _timeAllocationRepository;
        public MachineController(ISigerProjectMachineRepository machineRepository, IProductionTimeAllocationRepository timeAllocationRepository, IDashboardCombPageConditionTwoRepository combPageConditionRepository,
            IMachineParamAlarmRepository machineParamAlarmRepository, IProductionBeatSetRepository beatSetRepository, ISigerProjectBoxRepository boxRepository,
            IProductionTimeRepository timeRepository, ISigerProjectLevelRepository levelRepository, IUnitOfWork unitOfWork, ISigerProjectRepository projectRepository,
            ISigerProjectLevelSectionRepository levelSectionRepository, ISigerProjectDashboardFixpathRepository dashboardFixpathRepository, ISigerCompanyRepository companyRepository)
        {
            _machineRepository = machineRepository;
            _machineParamAlarmRepository = machineParamAlarmRepository;
            _beatSetRepository = beatSetRepository;
            _timeRepository = timeRepository;
            _levelRepository = levelRepository;
            _levelSectionRepository = levelSectionRepository;
            _combPageConditionRepository = combPageConditionRepository;
            _dashboardFixpathRepository = dashboardFixpathRepository;
            _unitOfWork = unitOfWork;
            _boxRepository = boxRepository;
            _projectRepository = projectRepository;
            _companyRepository = companyRepository;
            _timeAllocationRepository = timeAllocationRepository;
        }

        [HttpPost]
        public IActionResult GetMachineCode4()
        {
            var validMachines = _machineRepository.GetNCLevelSectionNames(0, ProjectId);
            var machineDatas = validMachines.ToList();
            if (!machineDatas.Any())
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }

            var result = new MachineRunningStateResult { iszy = "dev" };
            try
            {
                var machineIds = machineDatas.Select(m => m.machine_id);
                var machineAlarms = _machineParamAlarmRepository.GetList(q => machineIds.Contains(q.machine_id) && q.status == (int)RowState.Valid).ToList();

                var redisRepository = new CNCEquipmentStateRepository(CompanyId, ProjectId);
                var machineStates = redisRepository.GetCNCEquipmentStates(machineIds);
                foreach (var machine in machineDatas)
                {
                    var alarm = machineAlarms.FirstOrDefault(q => q.machine_id == machine.machine_id);
                    if (alarm != null)
                    {
                        var alarmReturn = Mapper<siger_project_machine_param_alarm, MachineAlarm>.Map(alarm);
                        result.listAll.Add(machine.machine_id, alarmReturn);
                    }
                    else
                    {
                        result.listAll.Add(machine.machine_id, new ArrayList());
                    }

                    var machineState = machineStates.FirstOrDefault(q => q.MachineId == machine.machine_id);
                    if (machineState != null)
                    {
                        var machineReturn = Mapper<CNCEquipmentState, MachineState>.Map(machineState);
                        machineReturn.Staus = machineState.Status;
                        if (DateTime.Now.Subtract(DateTime.Parse(machineState.LastUpdateTime)).TotalMinutes > CommonConst.MachineShutDownThreshold)
                        {
                            machineReturn.Staus = 0; //关机
                            machineReturn.FeedRatio = 0;
                            machineReturn.FeedSpeed = 0;
                            machineReturn.SpindleSpeed1 = 0;
                            machineReturn.SpindleRatio = 0;
                            machineReturn.PN = "";
                            machineReturn.SPN = "";
                        }

                        machineReturn.section_id = machine.section_id;
                        machineReturn.machineTitle = machine.lastSectionTitle; // 最后一级产线名称
                        machineReturn.title = machine.lastSecondSectionTitle; // 最后二级产线名称
                        result.last_data.data.Add(machineReturn);
                    }
                    else
                    {
                        var machineReturn = new MachineState
                        {
                            section_id = machine.section_id,
                            MachineId = machine.machine_id,
                            machineTitle = machine.lastSectionTitle,
                            title = machine.lastSecondSectionTitle
                        };
                        result.last_data.data.Add(machineReturn);
                    }
                }
            }
            catch (Exception e)
            {
                result.last_data.msg = CommonEnum.Fail;
                result.last_data.ret = 0;
                Logger.WriteLineError("GetMachineCode4 failed, error :" + e);
            }

            result.last_data.msg = CommonEnum.Succefull;
            result.last_data.ret = 1;
            return result;
        }

        [HttpGet]
        public async Task<IActionResult> GetMachineCode2(int id)
        {
            //var ProjectId = 171;
            //var CompanyId = 171;
            var machines = _machineRepository.GetNCLevelSectionNames(id, ProjectId).ToList();

            var state = await MachineManager.GetMachineRunningStatesResultAsync(CompanyId, ProjectId, machines);

            return Mapper<MachineRunningState, MachineRunningStateListResult>.Map(state);
        }

        /// <summary>
        /// 报警状态一览
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult MachineAlarmDetail()
        {
            var result = new MachineAlarmDetailResult();

            var machines = _machineRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.category == (int)MachineCategory.NC);
            var machineIds = machines.Select(m => m.id).ToList();

            IEnumerable<CncAlarmAnalysResult> exceptions = null;
            try
            {
                var cncExceptionRepository = new AlarmAnalysResultRepository(CompanyId, ProjectId);
                exceptions = cncExceptionRepository.GetCncAlarmAnalysResults(machineIds);
            }
            catch (Exception e)
            {
                Logger.WriteLineError("get CncAlarmAnalysResult failed, error:" + e);
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var exceptionMachines = exceptions.Select(m => m.machineId).Distinct();
            foreach (var machine in machines)
            {
                if (exceptionMachines.Contains(machine.id))
                {
                    result.exceptionCount++;
                }
                else
                {
                    result.normalCount++;
                }
            }
            var stations = _machineRepository.GetMachineStationInfos(machineIds, ProjectId).ToList();
            var stationIds = stations.Select(m => m.id).Distinct();
            foreach (var stationId in stationIds)
            {
                var station = stations.FirstOrDefault(q => q.id == stationId);
                if (station == null)
                {
                    continue;
                }

                var list = new List<MachineAlarmDetailInfo>();

                var stationMachineIds = stations.Where(m => m.id == station.id).Select(m => m.machineId);

                var excep = exceptions.Where(q => stationMachineIds.Contains(q.machineId));

                foreach (var exception in excep)
                {
                    var rowCount = excep.Count();
                    var firstRow = list.Select(m => m.section_id).Contains(station.id) == false;
                    var machineStation = stations.FirstOrDefault(q => q.machineId == exception.machineId);
                    if (machineStation == null)
                    {
                        continue;
                    }
                    var entity = new MachineAlarmDetailInfo
                    {
                        StartTime = exception.Stime.ToString(ParameterConstant.DateTimeFormat),
                        row_count = firstRow ? rowCount : 0,
                        section_id = machineStation.id,
                        station_name = machineStation.station_name,
                        section_name = machineStation.section_name,
                        AlarmCode = exception.code,
                        AlarmContent = exception.message,
                        MachineId = exception.machineId,
                        fault_content = exception.FaultContent ?? "",
                        fault_reason = exception.FaultReason ?? "",
                        fault_solution = exception.FaultSolution ?? "",
                        //time_span = UnixTimeHelper.GetTimeBySecond((int)(exception.Etime - exception.Stime).TotalSeconds),
                        time_span = (exception.Etime - exception.Stime).TotalSeconds.ToString(),
                        active = exception.status.ToString(),
                        isfault = exception.IsFault
                    };
                    list.Add(entity);

                    result.ProductionParameterLis[station.id] = list;
                }
            }

            return new ObjectResult(result);
        }

        /// <summary>
        ///  获取具体设备报警状态一览 APP
        /// </summary>
        /// <param name="machineId"></param>
        /// <returns></returns>
        [HttpGet]
   
        public IActionResult MachineAlarmDetailBySection(int machineId)
        {
            IEnumerable<CncAlarmAnalysResult> exceptions = null;
            try
            {
                var cncExceptionRepository = new AlarmAnalysResultRepository(CompanyId, ProjectId);
                exceptions = cncExceptionRepository.GetCncAlarmAnalysResults(new List<int> { machineId });
            }
            catch (Exception e)
            {
                Logger.WriteLineError("get CncAlarmAnalysResult failed, error:" + e);
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            if (!exceptions.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var exception = exceptions.FirstOrDefault();
            var result = new MachineAlarmDetailInfo
            {
  
                AlarmCode = exception.code,
                AlarmContent = exception.message,
                MachineId = exception.machineId,
                fault_content = exception.FaultContent ?? "",
                fault_reason = exception.FaultReason ?? "",
                fault_solution = exception.FaultSolution ?? "",
                time_span = (exception.Etime - exception.Stime).TotalSeconds.ToString(),
                active = exception.status.ToString(),
                isfault = exception.IsFault
            };
            return new ObjectResult(result);

        }
        /// <summary>
        /// cnc1.5功能，设备当天运行情况
        /// </summary>
        /// <param name="machineId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMachineTodayDetail(int machineId)
        {
            var response = new ResponseGetMachineTodayDetail();
            var machine = _machineRepository.Get(q => q.id == machineId && q.projectid == ProjectId && q.status == (int)RowState.Valid && q.category == (int)MachineCategory.NC);
            if (machine == null)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }

            var startTime = DateTime.Now.ToString(ParameterConstant.DateFormat);
            var endTime = DateTime.Now.ToString(ParameterConstant.DateTimeFormat);

            //设备名称
            response.machine_name = machine.title;

            var stateRepository = new CNCEquipmentStateRepository(CompanyId, ProjectId);
            var machineState = stateRepository.GetCNCEquipmentState(machineId);
            if (machineState == null)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }

            var yieldRepository = new ProductRepository(CompanyId, ProjectId);

            var rate = 1;
            var beat = _beatSetRepository.Get(q =>
                q.machineID == machineId && q.process_number == machineState.PN && q.projectID == ProjectId &&
                q.status == (int)RowState.Valid && q.start_time <= DateTime.Now && q.end_time >= DateTime.Now);
            if (beat != null)
            {
                response.product_name = beat.product_name_text;
                response.route_name = beat.route_name;
                rate = beat.yieldrate;
            }

            //产量
            var yields = yieldRepository.GetYieldByMachine(machineId, startTime, endTime);
            var totalYields = 0;
            foreach (var productYield in yields)
            {
                totalYields += productYield.yield * rate;
            }
            response.today_yield = totalYields.ToStr();

            //稼动率
            var sliceRepositoey = new SliceSateRepository(CompanyId, ProjectId);
            //var times = _timeRepository.GetRestTimesByMachine(new List<int> { machineId }, ProjectId);
            var times = _timeAllocationRepository.GetRestTimesByMachine(new List<int> { machineId }, ProjectId);
            var sliceSates = sliceRepositoey.GetCncSliceSates(new List<int> { machineId }, startTime, endTime);
            if (sliceSates.Any())
            {
                var oee = OeeManager.GetOeeByTime(DateTime.Parse(startTime), DateTime.Parse(endTime),
                    sliceSates, new List<int> { machineId }, null, times);
                response.privitity = Math.Round(oee.OEE1, 2).ToStr();
            }

            //程序号产量列表
            var lastProgramNos = yieldRepository.GetLastProgramNos(machineId, startTime, endTime);
            var beats = _beatSetRepository.GetList(q =>
                q.machineID == machineId && lastProgramNos.Contains(q.process_number) && q.projectID == ProjectId &&
                q.status == (int)RowState.Valid && q.start_time <= DateTime.Now && q.end_time >= DateTime.Now).ToList();

            if (lastProgramNos.Any())
            {
                foreach (var lastProgramNo in lastProgramNos)
                {
                    var proBeat = beats.FirstOrDefault(q => q.process_number == lastProgramNo);
                    var proYield = yields.FirstOrDefault(q => q.programCode == lastProgramNo);
                    var output = new MachineOutput
                    {
                        program_no = lastProgramNo,
                        product_name = proBeat != null ? proBeat.product_name_text : "",
                        yield = proYield == null ? 0 : proYield.yield * (proBeat != null ? proBeat.yieldrate : 1)
                    };
                    response.outputs.Add(output);
                }
            }

            //状态列表
            var dayStatus = SliceManager.GetMachineStatusHold(new List<int> { machineId }, DateTime.Parse(startTime), DateTime.Parse(endTime), sliceSates);
            if (dayStatus.Any())
            {
                double total = 0;
                foreach (var time in dayStatus)
                {
                    total += time.TimeSpan;
                }

                foreach (var time in dayStatus)
                {
                    var status = new MachineStatusSummary
                    {
                        status = (int)time.Status,
                        time = Math.Round(time.TimeSpan / 60, 1), //分钟
                        percent = total > 0 ? Math.Round(time.TimeSpan / total * 100, 1) + "%" : "NA"
                    };
                    response.machinestatus.Add(status);
                }

                var lastStaus = dayStatus.FirstOrDefault(q => (int)q.Status == machineState.Status);
                response.status_range = lastStaus == null ? 0 : Math.Round(lastStaus.TimeSpan / 60, 0);
            }
            //设备报警代码
            var alarmRepository = new AlarmAnalysResultRepository(CompanyId, ProjectId);
            var code = alarmRepository.MachineLastAlarmCode(machineId);
            if (!string.IsNullOrWhiteSpace(code))
            {
                response.alarm_code = code;
            }

            return new ObjectResult(response);
        }

        /// <summary>
        /// 大屏展示设备状态动态数据
        /// </summary>
        /// <param name="patial_code"></param>
        /// <param name="page_id"></param>
        /// <param name="projectid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMachineCodeTwo(string patial_code, string page_id, int projectid)
        {

            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);
            var sectionID = res != null ? res.condition.ToInt() : 0;
            var sectionids = GetLevelLists(sectionID);
            var section = new List<int>();
            var validMachines = _machineRepository.GetNCLevelSectionNames(sectionID, projectid);
            var machineDatas = validMachines.ToList();
            var result = new MachineRunningStateResult { iszy = "dev" };
            if (!machineDatas.Any())
            {              
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }
            try
            {
                var machineIds = machineDatas.Select(m => m.machine_id);
                var machineAlarms = _machineParamAlarmRepository.GetList(q => machineIds.Contains(q.machine_id) && q.status == (int)RowState.Valid).ToList();

                var redisRepository = new CNCEquipmentStateRepository(CompanyId, projectid);
                var machineStates = redisRepository.GetCNCEquipmentStates(machineIds);
                foreach (var machine in machineDatas)
                {
                    var alarm = machineAlarms.FirstOrDefault(q => q.machine_id == machine.machine_id);
                    if (alarm != null)
                    {
                        var alarmReturn = Mapper<siger_project_machine_param_alarm, MachineAlarm>.Map(alarm);
                        result.listAll.Add(machine.machine_id, alarmReturn);
                    }
                    else
                    {
                        result.listAll.Add(machine.machine_id, new ArrayList());
                    }

                    var machineState = machineStates.FirstOrDefault(q => q.MachineId == machine.machine_id);
                    var list = new List<MachineStatusSummarys>();

                    var fix = _dashboardFixpathRepository.Get(q => q.stationid == machine.section_id && q.guid == res.guid && q.status == (int)RowState.Valid);
                    if (machine.machine_id > 0)
                    {
                        //稼动率
                        var sliceRepositoey = new SliceSateRepository(CompanyId, ProjectId);
                        //var times = _timeRepository.GetRestTimesByMachine(new List<int> { machine.machine_id }, ProjectId);
                        var times = _timeAllocationRepository.GetRestTimesByMachine(new List<int> { machine.machine_id }, ProjectId);
                        var sliceSates = sliceRepositoey.GetCncSliceSates(new List<int> { machine.machine_id }, startTime, endTime);
                        //状态列表
                        if (sliceSates != null && sliceSates.Any())
                        {
                            var dayStatus = SliceManager.GetMachineStatusHold(new List<int> { machine.machine_id }, DateTime.Parse(startTime), DateTime.Parse(endTime), sliceSates);
                            if (dayStatus != null && dayStatus.Any())
                            {
                                double total = 0;
                                foreach (var time in dayStatus)
                                {
                                    total += time.TimeSpan;
                                }

                                foreach (var time in dayStatus)
                                {
                                    var status = new MachineStatusSummarys
                                    {
                                        status = (int)time.Status,
                                        time = Math.Round(time.TimeSpan / 60, 1), //分钟
                                        percent = total > 0 ? Math.Round(time.TimeSpan / total * 100, 1) + "%" : "NA"
                                    };
                                    list.Add(status);
                                }
                            }
                        }
                    }
                    if (machineState != null)
                    {
                        var machineReturn = Mapper<CNCEquipmentState, MachineState>.Map(machineState);
                        machineReturn.Staus = machineState.Status;
                        if (DateTime.Now.Subtract(DateTime.Parse(machineState.LastUpdateTime)).TotalMinutes > CommonConst.MachineShutDownThreshold)
                        {
                            machineReturn.Staus = 0; //关机
                            machineReturn.FeedRatio = 0;
                            machineReturn.FeedSpeed = 0;
                            machineReturn.SpindleSpeed1 = 0;
                            machineReturn.SpindleRatio = 0;
                            machineReturn.PN = "";
                            machineReturn.SPN = "";
                        }

                        machineReturn.MachineId = machine.machine_id;
                        machineReturn.x = fix != null ? fix.x : 0;
                        machineReturn.y = fix != null ? fix.y : 0;
                        machineReturn.machinestatus = list;
                        machineReturn.section_id = machine.section_id;
                        machineReturn.machineTitle = machine.lastSectionTitle; // 最后一级产线名称
                        machineReturn.title = machine.lastSecondSectionTitle; // 最后二级产线名称
                        result.last_data.data.Add(machineReturn);
                    }
                    else
                    {
                        var machineReturn = new MachineState();
                        machineReturn.Staus = 0; //关机
                        machineReturn.FeedRatio = 0;
                        machineReturn.FeedSpeed = 0;
                        machineReturn.SpindleSpeed1 = 0;
                        machineReturn.SpindleRatio = 0;
                        machineReturn.PN = "";
                        machineReturn.SPN = "";
                        machineReturn.MachineId = machine.machine_id;
                        machineReturn.x = fix != null ? fix.x : 0;
                        machineReturn.y = fix != null ? fix.y : 0;
                        machineReturn.machinestatus = list;
                        machineReturn.section_id = machine.section_id;
                        machineReturn.machineTitle = machine.lastSectionTitle; // 最后一级产线名称
                        machineReturn.title = machine.lastSecondSectionTitle; // 最后二级产线名称
                        result.last_data.data.Add(machineReturn);
                    }
                }
            }
            catch (Exception e)
            {
                result.last_data.msg = CommonEnum.Fail;
                result.last_data.ret = 0;
                Logger.WriteLineError("GetMachineCode4 failed, error :" + e);
            }

            result.last_data.msg = CommonEnum.Succefull;
            result.last_data.ret = 1;
            result.lampStatus = res != null ? res.lampStatus : 0;
            result.layout = res != null ? res.layout : "";
            return result;
        }

        /// <summary>
        /// 大屏展示报警一览
        /// </summary>
        /// <param name="patial_code"></param>
        /// <param name="page_id"></param>
        /// <param name="projectid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult MachineAlarmDetailTwo(string patial_code, string page_id, int projectid)
        {
            var res = _combPageConditionRepository.Get(q => q.comb_page_id == page_id && q.page_patial_code == patial_code);
            var sectionId = res != null ? res.condition.ToInt() : 0;



            var result = new MachineAlarmDetailResult();

            var machines = _machineRepository.GetList(q => q.projectid == projectid && q.status == (int)RowState.Valid && q.category == (int)MachineCategory.NC);
            //var machineIds = machines.Select(m => m.id).ToList();
            var machineIds = _machineRepository.GetNCLevelSectionMachineIds(sectionId, projectid);

            IEnumerable<CncAlarmAnalysResult> exceptions = null;
            try
            {
                var cncExceptionRepository = new AlarmAnalysResultRepository(CompanyId, projectid);
                exceptions = cncExceptionRepository.GetCncAlarmAnalysResults(machineIds);
            }
            catch (Exception e)
            {
                Logger.WriteLineError("get CncAlarmAnalysResult failed, error:" + e);
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var exceptionMachines = exceptions.Select(m => m.machineId).Distinct();
            foreach (var machine in machines)
            {
                if (exceptionMachines.Contains(machine.id))
                {
                    result.exceptionCount++;
                }
                else
                {
                    result.normalCount++;
                }
            }
            var stations = _machineRepository.GetMachineStationInfos(machineIds, projectid).ToList();
            var stationIds = stations.Select(m => m.id).Distinct();
            foreach (var stationId in stationIds)
            {
                var station = stations.FirstOrDefault(q => q.id == stationId);
                if (station == null)
                {
                    continue;
                }

                var list = new List<MachineAlarmDetailInfo>();

                var stationMachineIds = stations.Where(m => m.id == station.id).Select(m => m.machineId);

                var excep = exceptions.Where(q => stationMachineIds.Contains(q.machineId));

                foreach (var exception in excep)
                {
                    var rowCount = excep.Count();
                    var firstRow = list.Select(m => m.section_id).Contains(station.id) == false;
                    var machineStation = stations.FirstOrDefault(q => q.machineId == exception.machineId);
                    if (machineStation == null)
                    {
                        continue;
                    }
                    var entity = new MachineAlarmDetailInfo
                    {
                        StartTime = exception.Stime.ToString(ParameterConstant.DateTimeFormat),
                        row_count = firstRow ? rowCount : 0,
                        section_id = machineStation.id,
                        station_name = machineStation.station_name,
                        section_name = machineStation.section_name,
                        AlarmCode = exception.code,
                        AlarmContent = exception.message,
                        MachineId = exception.machineId,
                        fault_content = exception.FaultContent ?? "",
                        fault_reason = exception.FaultReason ?? "",
                        fault_solution = exception.FaultSolution ?? "",
                        //time_span = UnixTimeHelper.GetTimeBySecond((int)(exception.Etime - exception.Stime).TotalSeconds),
                        time_span = (exception.Etime - exception.Stime).TotalSeconds.ToString(),
                        active = exception.status.ToString(),
                        isfault = exception.IsFault
                    };
                    list.Add(entity);

                    result.ProductionParameterLis[station.id] = list;
                }
            }

            return new ObjectResult(result);
        }
        /// <summary>
        /// 获取所有设备信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetMachine([FromBody] MachineProjectId request)
        {
            var machineList = new List<AllMachine>();
            var machines = new List<siger_project_machine>();
            if (request.projectId > 0)
            {
                machines = _machineRepository.GetList(q => q.status == (int)RowState.Valid && q.projectid == request.projectId).ToList();
            }
            else
            {
                machines = _machineRepository.GetList(q => q.status == (int)RowState.Valid).ToList();
            }
            foreach (var item in machines)
            {
                var company = new siger_company();
                var project = _projectRepository.Get(q => q.id == item.projectid);
                if (project != null)
                {
                    company = _companyRepository.Get(q => q.id == project.companyid.ToInt());
                }
                var list = new AllMachine
                {
                    id = item.id,
                    pid = item.projectid,
                    pname = project != null ? project.title : "",
                    cid = project != null ? project.companyid.ToInt() : 0,
                    cname = company != null ? company.chinesename : "",
                    mid = item.mid,
                    model = item.model,
                    code = item.code,
                };
                machineList.Add(list);
            }
            return new ObjectResult(machineList);
        }

        /// <summary>
        /// 获取数采盒子
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [NoTokenValidateFilter]
        public IActionResult AddBox([FromBody] MachineAddBox request)
        {
            var boxList = _boxRepository.Get(q => q.boxcode == request.boxCode);
            if (boxList != null)
            {
                boxList.program_version = request.program_version;
                _boxRepository.Update(boxList);
            }
            else
            {
                var box = new siger_project_box();
                box.boxcode = request.boxCode;
                box.system = request.system;
                box.program_version = request.program_version;
                box.usage_status = 1;
                box.mandateType = 0;
                _boxRepository.Insert(box);
            }

            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }
        /// <summary>
        /// 获取盒子详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult MachineBox([FromBody] MachineGetBox request)
        {
            var boxList = _boxRepository.GetPageMachineGetBox(request);
            return new PagedObjectResult(boxList.Data, boxList.Total, request.page, request.pagesize);
        }

        /// <summary>
        /// 修改盒子状态
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [NoTokenValidateFilter]
        public IActionResult UpdateBox([FromBody] MachineBoxStatus request)
        {
            var box = _boxRepository.Get(q => q.boxcode == request.boxCode && q.status == (int)RowState.Valid);
            if (box != null)
            {
                box.usage_status = request.usageStatus;
                _boxRepository.Update(box);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }

        /// <summary>
        /// 获取所有项目
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetProject()
        {
            var machines = _machineRepository.GetProjectList();
            return new ObjectResult(machines);
        }

        /// <summary>
        /// 盒子授权
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult MandateUpdateBox([FromBody] MachineMandateBox request)
        {
            var Interface = ConfigManager.GetValue("BoxSetting", "Interface", string.Empty);
            var res = new MachineMandate();
            res.boxNo = request.boxCode;
            res.cid = request.cid;
            res.pid = request.pid;
            res.mid = request.mid;
            res.startDate = request.enableTime.ToDateTime();
            res.validDays = request.mandatedays;
            if (request.mandatetype == 1)
            {
                res.validDays = -1;
            }
            var param = JsonConvert.SerializeObject(res);
            try
            {
                var ret = HttpHelper.HttpPost($"{Interface}", "application/json", param);
                var result = (ResponseGetValue)JsonConvert.DeserializeObject(ret, typeof(ResponseGetValue));
                if (result.ret != 0)
                {
                    Logger.WriteLineError($"UploadProgram failed, result : {result.ret}");
                    throw new BadRequestException(RequestEnum.UploadError);
                }
                if (result.ret == 0)
                {
                    var box = _boxRepository.Get(q => q.boxcode == request.boxCode && q.status == (int)RowState.Valid);
                    if (box != null)
                    {
                        box.pid = request.pid;
                        box.cid = request.cid;
                        box.enableTime = request.enableTime.ToDateTime();
                        box.machineid = request.mid;
                        box.mandate_days = request.mandatedays;
                        box.usage_status = 0;
                        box.mandateType = request.mandatetype;
                        _boxRepository.Update(box);
                    }
                    if (_unitOfWork.Commit() > 0)
                    {
                        return new ObjectResult(CommonEnum.Succefull);
                    }
                    else
                    {
                        throw new BadRequestException(CommonEnum.Fail);
                    }
                }
                throw new BadRequestException(CommonEnum.Fail);
            }
            catch (Exception e)
            {
                Logger.WriteLineError($"UploadProgram failed, error: {e}");
                throw new BadRequestException(RequestEnum.MandateIsFill);
            }
        }


        /// <summary>
        /// 修改绑定设备
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateMachineBox([FromBody] UpdateMachine request)
        {
            var machineList = new AllMachine();
            var Interface = ConfigManager.GetValue("BoxSetting", "Interface", string.Empty);
            var box = _boxRepository.Get(q => q.id == request.id && q.status == (int)RowState.Valid);
            if (box != null)
            {
                var machine = _machineRepository.Get(q => q.status == (int)RowState.Valid && q.id == request.machineid);
                var project = _projectRepository.Get(q => q.id == machine.projectid);
                var list = new AllMachine
                {
                    id = machine.id,
                    pid = machine.projectid,
                    cid = project != null ? project.companyid.ToInt() : 0,
                };
                var res = new MachineMandate();
                res.boxNo = box.boxcode;
                res.cid = list.cid;
                res.pid = list.pid;
                res.mid = list.id;
                res.startDate = box.enableTime;
                res.validDays = box.mandate_days;
                if (box.mandateType == 1)
                {
                    res.validDays = -1;
                }
                var param = JsonConvert.SerializeObject(res);
                try
                {
                    var ret = HttpHelper.HttpPost($"{Interface}", "application/json", param);
                    var result = (ResponseGetValue)JsonConvert.DeserializeObject(ret, typeof(ResponseGetValue));
                    if (result.ret != 0)
                    {
                        Logger.WriteLineError($"UploadProgram failed, result : {result.ret}");
                        throw new BadRequestException(RequestEnum.UploadError);
                    }
                    if (result.ret == 0)
                    {
                        box.machineid = request.machineid;
                        box.pid = list.pid;
                        box.cid = list.cid;
                        _boxRepository.Update(box);
                        if (_unitOfWork.Commit() > 0)
                        {
                            return new ObjectResult(CommonEnum.Succefull);
                        }
                    }
                    throw new BadRequestException(CommonEnum.Fail);
                }
                catch (Exception e)
                {
                    Logger.WriteLineError($"UploadProgram failed, error: {e}");
                    throw new BadRequestException(RequestEnum.MandateIsFill);
                }
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 登陆长江润发
        /// </summary>
        /// <returns></returns>
        private string Login()
        {
            var logins = ConfigManager.GetValue("ChangjiangrunfaSetting", "login", string.Empty);
            var loginName = ConfigManager.GetValue("ChangjiangrunfaSetting", "loginName", string.Empty);
            var passWord = ConfigManager.GetValue("ChangjiangrunfaSetting", "passWord", string.Empty);
            var login = new getToken();
            login.loginName = loginName != null ? loginName : "";
            login.passWord = passWord != null ? passWord : "";
            var param = JsonConvert.SerializeObject(login);
            try
            {

                var ret = HttpHelper.HttpPosts($"{logins}", "application/json", param);
                if (ret.Item1)
                {
                    var result = (ResponseGetValue)JsonConvert.DeserializeObject(ret.Item2, typeof(ResponseGetValue));
                    return result.data;
                }
                else
                {
                    Logger.WriteLineError($"UploadProgram failed, result : {ret.Item2}");
                    return "";
                }
            }
            catch (Exception e)
            {
                Logger.WriteLineError($"UploadProgram failed, error: {e}");
                return "";
            }
        }
        /// <summary>
        /// 获取设备列表
        /// </summary>
        /// <returns></returns>
        private List<machineStatus> MachineList()
        {
            var machinelist = ConfigManager.GetValue("ChangjiangrunfaSetting", "machinelist", string.Empty);
            var list = new List<machineStatus>();
            var heads = Login();
            Dictionary<string, string> head = new Dictionary<string, string>();
            head.Add("token", heads);
            var parameter = new List<KeyValuePair<string, string>>
            {
            };
            try
            {
                if (heads != null && heads != "")
                {
                    var ret = HttpHelper.Gets($"{machinelist}", "application/json", parameter, head);
                    if (ret.Item1)
                    {
                        var result = (ResponseGetValues)JsonConvert.DeserializeObject(ret.Item2, typeof(ResponseGetValues));
                        list = result.data;
                        return list.ToList();
                    }
                }
                return list;
            }
            catch (Exception e)
            {
                Logger.WriteLineError($"UploadProgram failed, error: {e}");
                return list;
            }
        }
        /// <summary>
        /// 获取设备状态详情
        /// </summary>
        /// <returns></returns>
        private List<MachineState> VariateStatus()
        {
            var res = new List<MachineState>();
            var variateStatus = ConfigManager.GetValue("ChangjiangrunfaSetting", "variateStatus", string.Empty);
            var all = new List<machinesLists>();
            List<machineStatus> list = MachineList().ToList();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    var machineList = new machineList();
                    var status = new machinesLists();
                    machineList.machineCode = item.machineCode;
                    machineList.startTime = DateTime.Now.Date.ToString(ParameterConstant.DateTimeFormat);
                    machineList.endTime = DateTime.Now.ToString(ParameterConstant.DateTimeFormat);
                    status.runStatus = item.runStatus;
                    status.machineList = new List<machineList>();
                    status.machineList.Add(machineList);
                    status.machineId = item.machineId;
                    all.Add(status);
                }
            }
            try
            {
                var heads = Login();
                var results = new LastData();
                var lisras = new List<ResponseGetStatus>();
                if (all.Any())
                {
                    foreach (var item in all)
                    {
                        var param = JsonConvert.SerializeObject(item.machineList[0]);
                        Dictionary<string, string> head = new Dictionary<string, string>();
                        head.Add("token", heads);
                        var ret = HttpHelper.HttpPosts($"{variateStatus}", "application/json", param, null, head);
                        if (ret.Item1)
                        {
                            Logger.WriteLineError($"13 : {ret.Item1}");
                            var resp = (ResponseCommonStatus)JsonConvert.DeserializeObject(ret.Item2, typeof(ResponseCommonStatus));
                            if (resp.code == 1)
                            {
                                continue;
                            }
                            var result = (ResponseGetStatus)JsonConvert.DeserializeObject(ret.Item2, typeof(ResponseGetStatus));
                            lisras.Add(result);
                            MachineState machine = _machineParamAlarmRepository.GetMachine(item, result,ProjectId);
                            if (machine != null)
                            {
                                res.Add(machine);
                            }
                        }
                    }
                    var machineList = new List<int>();
                    //设备2082  永远关机  2087  永远运行
                    machineList.Add(2082);
                    machineList.Add(2087);
                    foreach (var item in machineList)
                    {
                        MachineState machine = _machineParamAlarmRepository.GetMachines(item, ProjectId);
                        if (machine != null)
                        {
                            res.Add(machine);
                        }
                    }
                    //
                    var machineLists = new List<int>();
                    machineLists.Add(2096);
                    machineLists.Add(2105);
                    foreach (var item in machineLists)
                    {
                        MachineState machine = _machineParamAlarmRepository.GetMachines(item, ProjectId);
                        if (item == 2096)
                        {
                            var mac = res.Where(q => q.MachineId == 2097).FirstOrDefault();
                            machine.Staus = mac.Staus;
                            machine.machinestatus = mac.machinestatus;
                        }

                        if (item == 2105)
                        {
                            var mac = res.Where(q => q.MachineId == 2089).FirstOrDefault();
                            machine.Staus = mac.Staus;
                            machine.machinestatus = mac.machinestatus;
                        }
                        if (machine != null)
                        {
                            res.Add(machine);
                        }
                    }

                }
                return res;
            }
            catch (Exception e)
            {
                Logger.WriteLineError($"UploadProgram failed, error: {e}"+e.ToString());
                return res;
            }
        }

        /// <summary>
        /// 获取所有工站
        /// </summary>
        /// <param name="lineid"></param>
        /// <returns></returns>
        private List<ResponseGetLevelTwo> GetLevelLists(int lineid)
        {
            var sectionID = 0;
            var patchId = 0;
            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 = -1;
                }
            }
            var responses = new List<ResponseGetLevelTwo>();
            var query = _levelSectionRepository.Getline(ProjectId, lineid).ToList();
            if (query != null)
            {
                foreach (var items in query)
                {
                    if (items.levelid != patchId)
                    {
                        continue;
                    }
                    var response = new ResponseGetLevelTwo
                    {
                        section_id = items.id
                    };
                    responses.Add(response);
                }
            }
            return responses;
        }
    }
}
