using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiDNC.Utility;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.DncRepository.Entities;
using Siger.Middlelayer.DncRepository.Repositories.Interface;
using Siger.Middlelayer.Redis.Repositories;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Extensions;
namespace Siger.ApiDNC.Controllers
{
    public class DNCController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectDncProgramRepository _sigerProjectDncProgram;

        public DNCController(IUnitOfWork unitOfWork, ISigerProjectDncProgramRepository sigerProjectDncProgram)
        {
            _unitOfWork = unitOfWork;
            _sigerProjectDncProgram = sigerProjectDncProgram;
        }
        [HttpGet]
        public IActionResult GetCurrentProgram(int machineid)
        {
            //查找当前设备的运行状态
            var machineState = new CNCEquipmentStateRepository(CompanyId, ProjectId);

            var state = machineState.GetCNCEquipmentState(machineid);
            if (state == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            
            //5分钟 没有数据判断为关机
            if (DateTime.Now.Subtract(DateTime.Parse(state.LastUpdateTime)).TotalMinutes > 5)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            
            return new ObjectResult(state.PN);
        }

        /// <summary>
        /// 获取NC程序内容
        /// </summary>
        /// <param name="machineid"></param>
        /// <param name="programcode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Getncvalue(int machineid, string programcode)
        {
            var ret = DNCHttpUtility.GetProgram(CompanyId,ProjectId,machineid, programcode);
            return new ObjectResult(ret);
        }
        /// <summary>
        /// 获取路卡号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTollGate(string gateno,int count)
        {
            Expression<Func<siger_project_dnc_program, bool>> funProject = f => f.projectid == ProjectId && f.status == (int)RowState.Valid;
            Expression<Func<siger_project_dnc_program, bool>> fungate = f => true;
            if (!string.IsNullOrEmpty(gateno))
            {
                fungate = f => f.toll_gate_code.Contains(gateno)&&f.toll_gate_code!="";
            }
            var predicates = funProject.And(fungate);

            var data = _sigerProjectDncProgram.GetPagedList(1, count, predicates);
            //var gateNo = data.Data.Select(s => s.toll_gate_code);

            var gateNo = data.Data;
            return new ObjectResult(gateNo);
        }
    }
}