using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.IMSRepository.Entities;
using Siger.Middlelayer.IMSRepository.Repositories.Interface;
using Siger.Middlelayer.IMSRepository.Request;
using Siger.Middlelayer.IMSRepository.Response;

namespace Siger.ApiIMS.Controllers
{
    public class ToolWorkorderController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IToolLifeWorkorderRepository _lifeWorkorderRepository;
        private readonly IToolLifeTechnologyRepository _technologyRepository;
        private readonly IToolLifeToolTechRepository _lifeToolTechRepository;
        private readonly IToolLifeToolChoiceRepository _toolChoiceRepository;
        private readonly IToolLifeToolChoiceSummaryRepository _toolChoiceSummaryRepository;
        private readonly IToolLifeToolRepository _toolLifeToolRepository;
        private readonly IProjectIMSToolConfigRepository _toolConfigRepository;

        public ToolWorkorderController(IUnitOfWork unitOfWork, IToolLifeWorkorderRepository workorderRepository,
            IToolLifeTechnologyRepository technologyRepository, IToolLifeToolTechRepository lifeToolTechRepository,
            IToolLifeToolChoiceRepository toolChoiceRepository, IToolLifeToolChoiceSummaryRepository toolChoiceSummaryRepository,
            IToolLifeToolRepository toolLifeToolRepository, IProjectIMSToolConfigRepository toolConfigRepository)
        {
            _unitOfWork = unitOfWork;
            _lifeWorkorderRepository = workorderRepository;
            _technologyRepository = technologyRepository;
            _lifeToolTechRepository = lifeToolTechRepository;
            _toolChoiceRepository = toolChoiceRepository;
            _toolChoiceSummaryRepository = toolChoiceSummaryRepository;
            _toolLifeToolRepository = toolLifeToolRepository;
            _toolConfigRepository = toolConfigRepository;
        }

        [HttpPost]
        public IActionResult GetPagedList([FromBody]RequestGetToolWorkorderList request)
        {
            var data = _lifeWorkorderRepository.GetPagedList(0, request.order_number, request.product_id.ToInt(), request.draw_code,
                request.machine_type.ToInt(),
                request.route, request.page, request.pagesize, ProjectId);

            var resList = new List<ResponseGetWorkorderList>();
            foreach (var lifework in data.Data)
            {
                var toolList = _lifeToolTechRepository.IsExist(q =>
                    q.technology_id == lifework.technology_id && q.status == (int)RowState.Valid);
                lifework.havetoollist = toolList ? 1 : 0;
                resList.Add(lifework);
            }

            return new PagedObjectResult(resList, data.Total, request.page, request.pagesize);
        }

        [HttpPost]
        public IActionResult Add([FromBody]RequestAddToolWorkorder request)
        {
            //有没有工艺
            var technology = _technologyRepository.Get(q =>
                q.product_id == request.product_id && q.route_id == request.route.ToInt() && q.status == (int)RowState.Valid
                                                   && q.project_id == ProjectId);
            if (technology == null)
            {
                throw new BadRequestException(RequestEnum.TechnologyNotFound);
            }
            var orderExist = _lifeWorkorderRepository.IsExist(q => q.workorder_code == request.order_number && q.status == (int)RowState.Valid
                                                   && q.project_id == ProjectId);
            if (orderExist)
            {
                throw new BadRequestException(RequestEnum.WorkOrderIsExsit);
            }

            var exist = _lifeWorkorderRepository.IsExist(q => q.workorder_code == request.order_number && q.status == (int)RowState.Valid
                                                              && q.project_id == ProjectId && q.technology_id == technology.id);
            if (exist)
            {
                throw new BadRequestException(RequestEnum.WorkOrderIsExsit);
            }
            var order = new siger_project_ims_workorder
            {
                count = request.count,
                create_time = DateTime.Now,
                need_time = DateTime.Parse(request.date),
                project_id = ProjectId,
                workorder_code = request.order_number,
                technology_id = technology.id,
                tool_code=request.tool_code
            };
            _lifeWorkorderRepository.Insert(order);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult AddRange([FromBody]RequestAddRangeToolWorkorder request)
        {
            if (request.workorders == null || !request.workorders.Any())
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
            foreach (var workorder in request.workorders)
            {
                //有没有工艺
                var technology = _technologyRepository.Get(q =>
                    q.id == workorder.technology_id && q.status == (int)RowState.Valid
                                                            && q.project_id == ProjectId);
                if (technology == null)
                {
                    throw new BadRequestException(RequestEnum.TechnologyNotFound);
                }
                //var orderExist = _lifeWorkorderRepository.IsExist(q =>
                //    q.workorder_code == workorder.order_number && q.status == (int) RowState.Valid
                //                                               && q.project_id == ProjectId);
                //if (orderExist)
                //{
                //    throw new BadRequestException(RequestEnum.WorkOrderIsExsit);
                //}

                //var exist = _lifeWorkorderRepository.IsExist(q =>
                //    q.workorder_code == workorder.order_number && q.status == (int) RowState.Valid
                //                                               && q.project_id == ProjectId &&
                //                                               q.technology_id == workorder.technology_id);
                //if (exist)
                //{
                //    throw new BadRequestException(RequestEnum.WorkOrderIsExsit);
                //}
                var order = new siger_project_ims_workorder
                {
                    count = workorder.count,
                    create_time = DateTime.Now,
                    need_time = DateTime.Parse(workorder.date),
                    project_id = ProjectId,
                    workorder_code = "",
                    technology_id = workorder.technology_id,
                    tool_code= workorder.tool_code
                };
                _lifeWorkorderRepository.Insert(order);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult Edit([FromBody]RequestEditToolWorkorder request)
        {
            //有没有工艺            
            var entity = _lifeWorkorderRepository.Get(q =>
                q.id == request.id && q.project_id == ProjectId && q.status == (int)RowState.Valid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            entity.count = request.count;
            entity.need_time = DateTime.Parse(request.date);
            _lifeWorkorderRepository.Update(entity);

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

        [HttpPost]
        public IActionResult Delete(int id)
        {
            var entity = _lifeWorkorderRepository.Get(q =>
                q.id == id && q.project_id == ProjectId && q.status == (int)RowState.Valid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            entity.status = (int)RowState.Invalid;
            _lifeWorkorderRepository.Update(entity);

            var choices = _toolChoiceRepository.GetList(t => t.workorder_id == entity.id && t.project_id == ProjectId && t.status == (int)RowState.Valid).ToList();
            foreach (var choice in choices)
            {
                choice.status = (int)RowState.Invalid;
                _toolChoiceRepository.Update(choice);
            }
            var summarys = _toolChoiceSummaryRepository.GetList(t => t.workorder_id == entity.id && t.project_id == ProjectId && t.status == (int)RowState.Invalid).ToList();
            foreach (var summary in summarys)
            {
                summary.status = (int)RowState.Invalid;
                _toolChoiceSummaryRepository.Update(summary);
            }

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

        [HttpGet]
        public IActionResult GetWorkOrderList()
        {
            var entities = _lifeWorkorderRepository
                .GetList(q => q.project_id == ProjectId && q.status == (int)RowState.Valid)
                .Select(m => new
                {
                    m.id,
                    m.workorder_code
                }).ToList();

            return new ObjectResult(entities);
        }

        [HttpGet]
        public IActionResult GetProductList(int workorder_id)
        {
            var list = _lifeWorkorderRepository.GetProductIdTitles(workorder_id, ProjectId);

            return new ObjectResult(list);
        }

        /// <summary>
        /// 获取刀具清单列表
        /// </summary>
        /// <param name="productid"></param>
        /// <param name="machineid"></param>
        /// <param name="routeid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTechList(string productid, string machineid, string routeid)
        {
            var techs = _technologyRepository.GetDataList(productid.ToInt(), routeid, machineid, ProjectId).ToList();
            var res = new List<ResponseToolWorkOrder>();
            foreach (var tech in techs)
            {
                var toolList = _lifeToolTechRepository.GetList(t =>
                    t.technology_id == tech.id && t.status == (int)RowState.Valid && t.project_id == ProjectId).ToList();
                if (!toolList.Any())
                {
                    continue;
                }
                foreach (var item in toolList)
                {
                    var toolIds = _toolConfigRepository.GetList(f => f.Projectid == ProjectId && f.Status != 0 && f.Code == item.tool_code).Select(s => s.ToolId).ToList();
                    if (res.Select(s => s.cutter_number).Contains(item.cutter_number))
                    {
                        continue;
                    }
                    res.Add(new ResponseToolWorkOrder
                    {
                        id = tech.id,
                        route = tech.route,
                        havetoollist = toolList != null ? 1 : 0,
                        machineType_name = tech.machineType_name,
                        tool_code = item.tool_code,
                        cutter_number = item.cutter_number,
                        boom = _toolLifeToolRepository.GetList(f => toolIds.Contains(f.id)).Select(s => new ResponseBoomData
                        {
                            categoryName = s.category_name,
                            category = s.category_id.ToStr(),
                            code =
                            s.number,
                            name = s.name
                        }).ToList()
                    });
                }
            }
            return new ObjectResult(res);
        }
    }
}