using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.AccRepository.Request;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository;
using Siger.ApiCommon.Filters;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Common.Extensions;

namespace Siger.ApiACC.Controllers
{
    /// <summary>
    /// SKF装配，数采使用
    /// </summary>
    public class AssembController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISnListRepository _snList;
        private readonly ISigerTrAssembRepository _sigerTrAssembRepository;
        private readonly ISigerTrSnTraceRepository _sigerTrSnTrace;
        private readonly ISigerTrSnTraceDetailsRepository _sigerTrSnTraceDetails;
        private readonly ISigetTrAssemblyDetails _sigetTrAssemblyDetails;

        public AssembController(IUnitOfWork unitOfWork, ISigerTrAssembRepository sigerTrAssembRepository, ISigerTrSnTraceRepository sigerTrSnTrace, ISigerTrSnTraceDetailsRepository sigerTrSnTraceDetails,ISnListRepository snListRepository, ISigetTrAssemblyDetails sigetTrAssemblyDetails)
        {
            _unitOfWork = unitOfWork;
            _sigerTrAssembRepository = sigerTrAssembRepository;
            _sigerTrSnTrace = sigerTrSnTrace;
            _sigerTrSnTraceDetails = sigerTrSnTraceDetails;
            _snList = snListRepository;
            _sigetTrAssemblyDetails = sigetTrAssemblyDetails;
        }
        /// <summary>
        /// SKF 装配数据保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [NoTokenValidateFilter]
        public IActionResult Save([FromBody]RequestAssembObj request)
        {
            foreach (var it in request.items)
            {
                var obj = _sigerTrAssembRepository.Get(f => f.projectId == request.projectId && f.name == it.name);
                var SeqID = Guid.NewGuid().ToString();
                if (obj != null)
                    SeqID = obj.guid;

                _sigerTrAssembRepository.Insert(new siger_tr_assemb_details
                {
                    guid = SeqID,
                    projectId = request.projectId,
                    section = request.section,
                    ispart = it.ispart,
                    name = it.name,
                    sn = it.sn,
                    status = (int)RowState.Valid,
                    busidate = DateTime.Now
                });
                //成品装配
                if (it.ispart == 0)
                {
                    _sigerTrSnTrace.Insert(new SigerTrSnTrace
                    {
                        SeqID = SeqID,
                        projectId = request.projectId,
                        Station = request.section,
                        Position = request.section,
                        ProductID="",
                        UID = 0,
                        SN = it.sn,
                        TransDateTime = DateTime.Now,
                        LastUpdateTime = DateTime.Now,
                        Result = "OK",
                        status = (int)RowState.Valid
                    });
                    _sigerTrSnTraceDetails.Insert(new SigerTrSNTraceDetail
                    {
                        SeqID = SeqID,
                        Result = "OK",
                        SN = it.sn,
                        Item = "装配",
                        Value = it.name,
                        status = (int)RowState.Valid,
                        LastUpdateTime = DateTime.Now,
                        TransDateTime = DateTime.Now,
                        projectId = request.projectId,
                    });
                }
            }
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult Add([FromBody] RequestSingleAssembleProduct reqAssembleData)
        {
            var uid = UserId;

            if(reqAssembleData.userId!=0)
            {
                uid = reqAssembleData.userId;
            }

            var snData = _snList.Get(f => f.SN.Equals(reqAssembleData.sn) && f.projectId == ProjectId &&
                                                                f.status == (int)RowState.Valid);
            if (snData == null)
            {
                throw new BadRequestException(AccEnum.Busi_SN_Null);
            }
            var guid = Guid.NewGuid().ToString();
            
            var detail = new List<siger_tr_assemb_details>();
            var assembly = new siger_tr_assemb_details
            {
                busidate = DateTime.Now,
                guid = guid,
                projectId = ProjectId,
                section = reqAssembleData.SectionId,
                ispart = (int)ProductType.InPart,
                name = "",
                number = 1,
                sn = reqAssembleData.sn
            };

            uid = reqAssembleData.userId;

            detail.Add(assembly);

            foreach (var item in reqAssembleData.AccessoriesSn)
            {
                var assem = _sigetTrAssemblyDetails.GetList(q => q.sn == item.sn && q.projectId == ProjectId && q.status == (int)RowState.Valid).Sum(q => q.number);
                var mate = _sigetTrAssemblyDetails.GetNumber(item.sn, ProjectId).FirstOrDefault();
                var mateNumber = mate != null ? mate.number : 0;
                if (assem >= mateNumber && mateNumber != 0)
                {
                    throw new BadRequestException(AccEnum.AssembNumberOut);
                }

                assembly = new siger_tr_assemb_details
                {
                    busidate = DateTime.Now,
                    guid = guid,
                    projectId = ProjectId,
                    section = reqAssembleData.SectionId,
                    ispart = (int)ProductType.Part,
                    number = item.number,
                    sn = item.sn,
                    uid = reqAssembleData.userId
                };
                detail.Add(assembly);
            }
            _sigetTrAssemblyDetails.Insert(detail);

            var trance = new SigerTrSnTrace
            {
                WO = reqAssembleData.wo,
                LastUpdateTime = DateTime.Now,
                TransDateTime = DateTime.Now,
                Station = reqAssembleData.SectionId,
                UID = uid,
                SeqID = guid,
                projectId = ProjectId,
                ProductID = snData.ProductCode,
                SN = reqAssembleData.sn,
                ProductRoute = reqAssembleData.ProductRouteId.ToInt(),
                type = (int)TraceType.TraceBack,
                Result = EvenNoEnum.OK.ToString()
            };
            _sigerTrSnTrace.Insert(trance);

            foreach (var item in reqAssembleData.AccessoriesSn)
            {
                var traceDetail = new SigerTrSNTraceDetail
                {
                    SeqID = guid,
                    SN = reqAssembleData.sn,
                    Item = item.sn ?? "",
                    Value = item.number.ToString(),
                    projectId = ProjectId,
                    LastUpdateTime = DateTime.Now,
                    TransDateTime = DateTime.Now,
                    Result = EvenNoEnum.OK.ToString()
                };
                _sigerTrSnTraceDetails.Insert(traceDetail);
            }

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