using System;
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.IMSRepository.Repositories.Interface;
using Siger.Middlelayer.IMSRepository.Request;

namespace Siger.ApiIMS.Controllers
{
    public class ToolScrapController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IToolLifeToolScrapRepository _scrapRepository;
        public ToolScrapController(IUnitOfWork unitOfWork, IToolLifeToolScrapRepository scrapRepository)
        {
            _unitOfWork = unitOfWork;
            _scrapRepository = scrapRepository;
        }

        [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 = _scrapRepository.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);
        }

        [HttpPost]
        public IActionResult AuditToolScrap([FromBody]AuditToolScrap request)
        {
            if (request.status != (int)ToolScrapStatus.Reject && request.status != (int)ToolScrapStatus.Aduited)
            {
                throw new BadRequestException(RequestEnum.InputValueError);
            }
            var scrap = _scrapRepository.Get(t =>
                t.id == request.id && t.status == (int) RowState.Valid && t.project_id == ProjectId);
            if (scrap == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            scrap.status = request.status;
            scrap.review_remark = request.remark;
            scrap.review_mid = UserId;
            scrap.review_time = UnixTimeHelper.GetNow();
            _scrapRepository.Update(scrap);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }

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