using System;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.FieldEnum;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.TlmRepository.Repositories.Interface;
using Siger.Middlelayer.TlmRepository.Request;

namespace Siger.ApiTLM.Controllers
{
    public class ToolMeatureController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IToolLifeToolMeatureRepository _meatureRepository;
        private readonly IToolLifeTechnologyRepository _technologyRepository;
        private readonly IToolLifeWorkorderRepository _workorderRepository;
        private readonly IToolLifeToolPackageRepository _packageRepository;
        public ToolMeatureController(IUnitOfWork unitOfWork, IToolLifeToolMeatureRepository meatureRepository,
            IToolLifeToolChoiceRepository choiceRepository, IToolLifeTechnologyRepository technologyRepository,
            IToolLifeToolPackageRepository packageRepository, IToolLifeWorkorderRepository workorderRepository)
        {
            _unitOfWork = unitOfWork;
            _meatureRepository = meatureRepository;
            _technologyRepository = technologyRepository;
            _workorderRepository = workorderRepository;
            _packageRepository = packageRepository;
        }

        [HttpPost]
        public IActionResult GetPagedList([FromBody] RequestGetToolChoice request)
        {
            var technology = _technologyRepository.Get(q =>
                q.product_id == request.product_id.ToInt() && q.machine_type == request.machine_type.ToInt()
                                                           && q.drawcode == request.draw_code && q.status == (int)RowState.Valid
                                                           && q.project_id == ProjectId);
            if (technology == null)
            {
                throw new BadRequestException(RequestEnum.TechnologyNotFound);
            }

            var workOrder = _workorderRepository.Get(q =>
                q.workorder_code == request.workorder_code && q.technology_id == technology.id
                                                           && q.project_id == ProjectId && q.status == (int)RowState.Valid);

            if (workOrder == null)
            {
                throw new BadRequestException(RequestEnum.ToolWorkorderNotFound);
            }

            var datas = _meatureRepository.GetPagedList(workOrder.id, technology.id, request.page, request.pagesize, ProjectId);

            return new PagedObjectResult(datas.Data, datas.Total, request.page, request.pagesize);
        }

        //[HttpGet]
        //public IActionResult GetMeatureData(string handler_code)
        //{
        //    if (string.IsNullOrWhiteSpace(handler_code))
        //    {
        //        throw new BadRequestException(RequestEnum.ParameterError);
        //    }
        //    //读最新的测量文件
        //    var fileSetting = Config<FileSettings>.Get();
        //    if (fileSetting == null)
        //    {
        //        throw new BadRequestException(CommonEnum.GetCommCfgFailed);
        //    }

        //    var rootDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileSetting.FileSetting.PhysicalFolder, "toolmeature");
        //    if (!Directory.Exists(rootDir))
        //    {
        //        Directory.CreateDirectory(rootDir);
        //    }
        //    //取最新的文件
        //    var dir = new DirectoryInfo(rootDir);
        //    var file = dir.GetFiles().OrderByDescending(q => q.CreationTime).FirstOrDefault();
        //    if (file == null)
        //    {
        //        throw new BadRequestException(RequestEnum.ToolMeatureFileNotFound);
        //    }

        //    try
        //    {
        //        var content = System.IO.File.ReadAllText(file.FullName);
        //        var entity = XmlHelper.Deserialize<MASTERTOOL>(content);
        //        if (entity.KeyToolId == handler_code)
        //        {
        //            return new ObjectResult(entity.STAGE.Z);
        //        }
        //        throw new BadRequestException(RequestEnum.ToolMeatureFileNotFound);
        //    }
        //    catch (Exception e)
        //    {
        //        Logger.WriteLineError("tool meature file descrialize failed, error:"+ e);
        //        throw new BadRequestException(RequestEnum.ToolMeatureFileInValid);
        //    }
        //}

        [HttpPost]
        public IActionResult SubmitMeature([FromBody]RequestAddMeature request)
        {
            var package = _packageRepository.Get(q => q.id == request.id && q.project_id == ProjectId && q.status == (int)RowState.Valid
                                                       && q.confirm_status == ChoiceStatus.HasApply);
            if (package == null)
            {
                throw new BadRequestException(RequestEnum.NoPackageTools);
            }
            //如果没填伸出长，则任何值都是合格；
            //如果只填了伸出长，没填上下公差，则只要实测刀长大于伸出长度就是合格；
            //如果有上下公差，则在范围内算合格
            if (string.IsNullOrWhiteSpace(request.reach_length))
            {
                package.measure_status = MeasureResult.Qualified;
            }
            else if (string.IsNullOrWhiteSpace(request.down_tolerance) && string.IsNullOrWhiteSpace(request.upper_tolerance))
            {
                if (request.actual_length.ToDouble() >= request.reach_length.ToDouble())
                {
                    package.measure_status = MeasureResult.Qualified;
                }
                else
                {
                    package.measure_status = MeasureResult.UnQualified;
                }
            }
            else
            {
                var reach = request.reach_length.ToDouble();
                var down = reach + request.down_tolerance.ToDouble();
                var up = reach + request.upper_tolerance.ToDouble();
                var act = request.actual_length.ToDouble();
                if (act >= down && act <= up)
                {
                    package.measure_status = MeasureResult.Qualified;
                }
                else
                {
                    package.measure_status = MeasureResult.UnQualified;
                }
            }

            package.actual_length = request.actual_length.ToDouble();
            _packageRepository.Update(package);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}