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

namespace Siger.ApiTLM.Controllers
{
    public class ToolGrindController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IToolLifeToolGrindRepository _grindRepository;
        private readonly IToolLifeToolRepository _toolRepository;
        public ToolGrindController(IUnitOfWork unitOfWork, IToolLifeToolGrindRepository grindRepository, IToolLifeToolRepository toolRepository)
        {
            _unitOfWork = unitOfWork;
            _grindRepository = grindRepository;
            _toolRepository = toolRepository;
        }

        [HttpPost]
        public IActionResult GetPagedList([FromBody]RequestGetToolGrind request)
        {
            var stime = (int)UnixTimeHelper.ConvertDataTimeLong(DateTime.Parse(request.starttime));
            var etime = (int)UnixTimeHelper.ConvertDataTimeLong(DateTime.Parse(request.endtime));
            var data = _grindRepository.GetPagedList(request.material.ToInt(), request.status.ToInt(), stime, etime, request.page,
                request.pagesize, ProjectId, 0);
            return new PagedObjectResult(data.Data, data.Total, request.page, request.pagesize);
        }

        [HttpGet]
        public IActionResult GetGrindInfo(string serial_number)
        {
            var materialId = 0;
            var stock = _toolRepository.GetStockTrace(serial_number, 0, ProjectId);
            if (stock == null)
            {
                var grind = _grindRepository.Get(t => t.stock_number == serial_number);
                if (grind == null)
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }
                materialId = grind.material_id;
            }
            else
            {
                materialId = stock.material_id;
            }
            var tool = _toolRepository.Get(t =>
                t.material_id == materialId && t.status == (int) RowState.Valid && t.project_id == ProjectId);
            if (tool == null)
            {
                throw new BadRequestException(RequestEnum.ToolNotFound);
            }
            var material = _grindRepository.GetMaterial(tool.material_id, tool.part_no, ProjectId);
            if (material == null)
            {
                throw new BadRequestException(RequestEnum.MaterialNotExist);
            }
            var grindCount = _grindRepository.GetList(t =>
                (t.status == (int)ToolGrindStatus.Completed || t.status == (int)ToolGrindStatus.Apply)
                && t.project_id == ProjectId && t.material_id == tool.material_id).Count();

            var res = new ResponseGetToolGrind
            {
                id = tool.id,
                serial_number = serial_number,
                part_no = tool.part_no,
                material_name = material.name,
                grind_count = grindCount,
                grind_type = tool.grind_type,
                remain_times = tool.grind_times - grindCount > 0 ? tool.grind_times - grindCount : 0
            };
            return new ObjectResult(res);
        }

        [HttpPost]
        public IActionResult EditGrindInfo([FromBody]EditToolGrind request)
        {
            var grind = _grindRepository.Get(t => t.id == request.id && t.status == (int)RowState.Valid && t.project_id == ProjectId);
            if (grind == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            //TODO修模报废待做
            if (grind.remain_times == 0)
            {

            }
            if (request.serial_number != grind.stock_number)
            {
                throw new BadRequestException(RequestEnum.SerialNumberError);
            }
            //var stock = _toolRepository.GetStockTrace(request.serial_number, 0, ProjectId);
            //if (stock == null)
            //{
            //    throw new BadRequestException(RequestEnum.StockNotExist);
            //}
            var tool = _toolRepository.Get(t =>
                t.material_id == grind.material_id && t.status == (int)ToolGrindStatus.UnGrind && t.project_id == ProjectId 
                && t.category == TlmSettingCategory.Cutter);
            if (tool == null)
            {
                throw new BadRequestException(RequestEnum.ToolNotFound);
            }

            var grindCount = _grindRepository.GetList(t =>
                (t.status == (int)ToolGrindStatus.Completed || t.status == (int)ToolGrindStatus.Apply)
                && t.project_id == ProjectId && t.material_id == tool.material_id).Count();
            var remain_count = tool.grind_times - grindCount > 0 ? tool.grind_times - grindCount : 0;
            var time = UnixTimeHelper.GetNow();
            if (grind != null)
            {
                if (tool.grind_type == (int) GrindTypeStatus.Assist)
                {
                    grind.status = (int) ToolGrindStatus.Apply;
                    grind.apply_time = time;
                }
                else
                {
                    grind.status = (int) ToolGrindStatus.Completed;
                    grind.grind_time = time;
                }

                
                grind.remain_times = remain_count > 0 ? remain_count - 1 : 0;                

                _grindRepository.Update(grind);
                if (_unitOfWork.Commit()>0)
                {
                    return new ObjectResult(CommonEnum.Succefull);
                }
            }
            else
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}