using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore.Internal;
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.Common.ModuleEnum;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.TlmRepository.Entities;
using Siger.Middlelayer.TlmRepository.Repositories.Interface;
using Siger.Middlelayer.TlmRepository.Request;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Utility.ImportEntities;
using System.Linq;
using Siger.Middlelayer.TlmRepository.Response;
using Siger.Middlelayer.Repository.Repositories.Interface;

namespace Siger.ApiTLM.Controllers
{
    public class ToolTestController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IProjectToollifeDetectionRepository _toollifeDetectionRepository;
        private readonly IToolLifeToolRepository _toolLifeToolRepository;
        private readonly IProjectToollifeDetectionRecordRepository _toollifeDetectionRecordRepository;
        private readonly IProjectToollifeDetectionDetailRepository _toollifeDetectionDetailRepository;
        private readonly IProjectToollifeDetectionReturnRepository _toollifeDetectionReturnRepository;
        private readonly IProjectToollifeTestRepository _toollifeTestRepository;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly IToolLifeToolPackageRepository _packageRepository;
        private readonly IToolLifeToolInstallRepository _installRepository;

        public ToolTestController(IUnitOfWork unitOfWork, IProjectToollifeDetectionRepository toollifeDetectionRepository, IToolLifeToolRepository toolLifeToolRepository
            , IProjectToollifeDetectionRecordRepository toollifeDetectionRecordRepository, IProjectToollifeDetectionDetailRepository toollifeDetectionDetailRepository
            , IProjectToollifeDetectionReturnRepository toollifeDetectionReturnRepository, IProjectToollifeTestRepository toollifeTestRepository, ISigerProjectMachineRepository machineRepository,
            IToolLifeToolPackageRepository packageRepository, IToolLifeToolInstallRepository installRepository)
        {
            _unitOfWork = unitOfWork;
            _toollifeDetectionRepository = toollifeDetectionRepository;
            _toolLifeToolRepository = toolLifeToolRepository;
            _toollifeDetectionRecordRepository = toollifeDetectionRecordRepository;
            _toollifeDetectionDetailRepository = toollifeDetectionDetailRepository;
            _toollifeDetectionReturnRepository = toollifeDetectionReturnRepository;
            _toollifeTestRepository = toollifeTestRepository;
            _machineRepository = machineRepository;
            _packageRepository = packageRepository;
            _installRepository = installRepository;
        }
        /// <summary>
        /// 添加修改测试项目
        /// </summary>
        /// <param name="requests"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SetDetection([FromBody]List<RequestSetDetection> requests)
        {
            var pid = ProjectId;
            var uid = UserId;
            var now = DateTime.Now;
            //存在性校验
            if (requests.Select(s => s.Seq).Count() != requests.Count())
            {
                throw new BadRequestException(TlmEnum.RecordItemExist);
            }

            if (requests != null && requests.Any())
            {
                //重复校验
                if (requests.Select(s => s.Seq).Distinct().Count() != requests.Count())
                {
                    throw new BadRequestException(TlmEnum.RecordItemExist);
                }
                //Detection
                foreach (var req in requests)
                {
                    if (req.id == 0)
                    {
                        var temp = _toollifeDetectionRepository.Get(f => f.Seq == req.Seq && f.Status != 0 && f.ToolId == req.ToolId && f.Projectid == pid);
                        if (temp != null)
                        {
                            throw new BadRequestException(TlmEnum.RecordItemExist);
                        }
                        var data = Mapper<RequestSetDetection, ProjectToollifeDetectionEntity>.Map(req);
                        data.Creator = uid;
                        data.Editor = uid;
                        data.CreateTime = now;
                        data.Projectid = pid;
                        _toollifeDetectionRepository.Insert(data);
                    }
                    else
                    {
                        var model = _toollifeDetectionRepository.Get(f => f.Id == req.id && f.Status != 0 && f.Projectid == pid);
                        model.Seq = req.Seq;
                        model.Editor = uid;
                        model.Max = req.Max;
                        model.Mini = req.Mini;
                        model.StandardValues = req.StandardValues;
                        model.Type = req.Type;
                        model.Tools = req.Tools;
                        _toollifeDetectionRepository.Update(model);
                    }
                }
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 获取测试项目
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(ProjectToollifeDetectionEntity), 200)]
        public IActionResult GetDetection([FromBody]RequestProjectToollifeDetection request)
        {
            request.ProjectId = ProjectId;
            var entities = _toollifeDetectionRepository.GetPagedList(request);
            return new PagedObjectResult(entities.Data, entities.Total, request.Page, request.PageSize);
        }
        /// <summary>
        /// 删除测试项目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult DelDetection(int id)
        {
            var model = _toollifeDetectionRepository.Get(f => f.Id == id && f.Status != 0 && f.Projectid == ProjectId);
            if (model == null)
            {
                throw new BadRequestException(CommonEnum.DeleteFaild);
            }
            model.Status = 0;
            _toollifeDetectionRepository.Update(model);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 刀具检测列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(ResponeToollifeDetectionRecord), 200)]
        public IActionResult GetTestData([FromBody]RequestProjectToollifeDetectionRecord request)
        {
            request.ProjectId = ProjectId;
            var data = _toollifeDetectionRecordRepository.GetPagedList(request);
            return new PagedObjectResult(data.Data.OrderByDescending(o=>o.in_time), data.Total, request.Page, request.PageSize);
        }
        /// <summary>
        /// 检测项目
        /// </summary>
        /// <param name="requests"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SetTestData([FromBody]List<RequestSetToollifeDetectionRecord> requests)
        {
            var pid = ProjectId;
            var uid = UserId;
            var now = DateTime.Now;
            if (requests != null && requests.Any())
            {
                var mainResult = 1;
                var record = _toollifeDetectionRecordRepository.Get(f => f.OrderNumber == requests.First().OrderNumber);
                if (record == null)
                {
                    throw new BadRequestException(TlmEnum.RecordItemNotFound);
                }
                var tool = _toolLifeToolRepository.Get(f => f.id == record.ToolId);
                if (tool == null)
                {
                    throw new BadRequestException(TlmEnum.ToolNotFound);
                }
                //Detection
                foreach (var req in requests)
                {
                    var data = Mapper<RequestSetToollifeDetectionRecord, ProjectToollifeDetectionDetailEntity>.Map(req);
                    data.Creator = UserId;
                    data.Editor = UserId;
                    data.Projectid = pid;
                    data.result = 0;
                    data.CreateTime = now;
                    //str判断检测结果
                    if (data.ActualValue.ToUpper() == "OK")
                    {
                        data.result = 1;
                    }
                    else
                    {
                        data.result = 2;
                    }
                    //数值判断
                    var temp = 0d;
                    if ((data.Max != 0 || data.Mini != 0) && double.TryParse(data.ActualValue, out temp))
                    {
                        if (temp >= data.Mini && temp <= data.Max)
                        {
                            data.result = 1;
                        }
                        else
                        {
                            data.result = 2;
                        }
                    }
                    _toollifeDetectionDetailRepository.Insert(data);
                    if (data.result == 2)
                    {
                        mainResult = 2;
                    }
                }
                record.State = tool.need_test == 1 ? TlmDetectionState.WaitTest : TlmDetectionState.Inspected;
                record.result = mainResult;
                record.inspector = UserId;
                record.inspect_time = UnixTimeHelper.GetNow();
                _toollifeDetectionRecordRepository.Update(record);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 检测项目明细
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(ProjectToollifeDetectionDetailEntity), 200)]
        public IActionResult GetTestDetailData([FromBody]RequestProjectToollifeDetectionDetail request)
        {
            request.ProjectId = ProjectId;
            var entities = _toollifeDetectionDetailRepository.GetPagedList(request);
            return new PagedObjectResult(entities.Data, entities.Total, request.Page, request.PageSize);
        }
        /// <summary>
        /// 处理检测信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult HandleTestDetailData([FromBody]RequestHandleDetectionDetail request)
        {
            foreach (var item in request.data)
            {
                var record = _toollifeDetectionRecordRepository.Get(f => f.OrderNumber == item.OrderNumber);
                if (record == null)
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }
                if (!_toollifeDetectionRecordRepository.ChangeLocation(record.StockId, ProjectId, UserId, item.to))
                {
                    throw new BadRequestException(CommonEnum.Fail);
                }
                if (request.state == TlmDetectionState.InspectReturn || request.state == TlmDetectionState.TestReturn)//退货
                {
                    _toollifeDetectionReturnRepository.Insert(new ProjectToollifeDetectionReturnEntity
                    {
                        CreateTime = DateTime.Now,
                        Creator = UserId,
                        Editor = UserId,
                        order_number = item.OrderNumber,
                        Projectid = ProjectId,
                        reason = item.reason
                    });
                }
                record.State = request.state;
                _toollifeDetectionRecordRepository.Update(record);
                if (_unitOfWork.Commit() <= 0)
                {
                    throw new BadRequestException(CommonEnum.Fail);
                }
            }
            return new ObjectResult(CommonEnum.Succefull);

        }
        /// <summary>
        /// 提交刀具测试
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SubmitToolTest([FromBody]RequestTooTest request)
        {
            var pid = ProjectId;
            //是否装刀
            var packageTool = _packageRepository.Get(q => request.matterOrder.Contains(q.code) && q.status == (int)RowState.Valid
                                                && q.confirm_status == ChoiceStatus.HasApply);
            if (packageTool == null)
            {
                throw new BadRequestException(RequestEnum.NoPackageTools);
            }
            //是否安装设备
            var hasinstalls = _installRepository.GetList(q => q.machine_code == request.machinecode
            && q.cutter_number == request.knifePosition
            && q.project_id == ProjectId && q.install_category == InstallCategory.Install).ToList();
            if (hasinstalls.Any())
            {
                throw new BadRequestException(TlmEnum.ToolInstalled);
            }
            //是否存在检测记录
            var records = _toollifeDetectionRecordRepository.GetList(f => f.Projectid == pid && f.Status != 0 && request.matterOrder.Contains(f.serial_number));
            if (!records.Any(f => f.State == TlmDetectionState.WaitTest))
            {
                throw new BadRequestException(TlmEnum.TestRecordNotFound);
            }
            foreach (var serialNumber in request.matterOrder)
            {
                var record = _toollifeDetectionRecordRepository.Get(f => f.Projectid == pid && f.Status != 0 && f.serial_number == serialNumber);
                if (record != null && record.State == TlmDetectionState.WaitTest)
                {
                    record.State = TlmDetectionState.Tested;
                    _toollifeDetectionRecordRepository.Update(record);
                }
                var machine = _machineRepository.Get(f => f.code == request.machinecode && f.projectid == ProjectId && f.status != 0);
                var model = new ProjectToollifeTestEntity(UserId, ProjectId);
                model.MachineId = machine.id;
                model.Result = request.result;
                model.ToolId = record.ToolId;
                model.Location = request.knifePosition;
                model.OrderNumber = record.OrderNumber;
                _toollifeTestRepository.Insert(model);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}