using System;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.AccRepository.Request;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository;
using Siger.ApiCommon.Filters;
namespace Siger.ApiACC.Controllers
{
    public class PackageController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerTrPackage _sigerTrPackage;
        private readonly ISigerTrPackageDetials _sigerTrPackageDetials;

        public PackageController(IUnitOfWork unitOfWork, ISigerTrPackage sigerTrPackage, ISigerTrPackageDetials sigerTrPackageDetials)
        {
            _unitOfWork = unitOfWork;
            _sigerTrPackage = sigerTrPackage;
            _sigerTrPackageDetials = sigerTrPackageDetials;
        }
        /// <summary>
        /// SKF 保存打包信息，数采使用
        /// </summary>
        /// <param name="package"></param>
        /// <returns></returns>
        [NoTokenValidateFilter]
        [HttpPost]
        public IActionResult Save([FromBody]RequestPackage package)
        {
            double.TryParse(package.weight, out double _weight);
            _sigerTrPackage.Insert(new siger_tr_package
            {
                section=package.section,
                boxid=package.boxid,
                busidate=package.busidate,
                productcode=package.productCode,
                partno=package.partno,
                count=package.count,
                weight= _weight,
                supplier=package.supplier,
                lastupdate=DateTime.Now,
                batch=package.batch,
                send_ch=package.send_cn,
                send_en=package.send_en,
                recive_ch=package.recive_cn,
                recive_en=package.recive_en,
                projectId= package.projectId,
                open=package.open,
                send_barcode=package.send_barcode,
                status=(int)RowState.Valid
            });
            foreach(var dts in package.details)
            {
                _sigerTrPackageDetials.Insert(new siger_tr_package_details { 
                 projectId=package.projectId,
                 boxid=package.boxid,
                 sn=dts.sn,
                 status=(int)RowState.Valid
                });
            }

            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                throw new BadRequestException(CommonEnum.Fail);

        }

        /// <summary>
        /// 获取明细
        /// </summary>
        /// <param name="boxId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Details(string boxId)
        {
            var data = _sigerTrPackageDetials.GetList(f => f.projectId == ProjectId && f.boxid == boxId);
            return new ObjectResult(data);
        }

    }
}
