using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon;
using Siger.ApiCommon.Exceptions;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Entities;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Request;
using Siger.ApiCommon.Filters;
namespace Siger.ApiTPM.Controllers
{
    public class FaultTypeController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly IFaultTypeRepository _faultTypeRepository;
        public FaultTypeController(IUnitOfWork unitOfWork, IFaultTypeRepository faultTypeRepository, ISigerProjectMachineRepository machineRepository)
        {
            _unitOfWork = unitOfWork;
            _faultTypeRepository = faultTypeRepository;
            _machineRepository = machineRepository;
        }

        [HttpGet]
        public IActionResult GetAllFaultTypes()
        {
            var query = _faultTypeRepository.GetList(q =>
                    q.parentid == 0 && q.status == (int)RowState.Valid &&
                    q.projectid == ProjectId)
                    .Select(q =>
                        new
                        {
                            q.title,
                            q.id
                        }
                    ).ToList();
            return new ObjectResult(query);
        }

        [HttpGet]
        public IActionResult GetInvalidModesByTypeId(int faultTypeId)
        {
            var query = _faultTypeRepository.GetList(q =>
                    q.parentid == faultTypeId && q.status == (int)RowState.Valid &&
                    q.projectid == ProjectId)
                .Select(q =>
                    new
                    {
                        q.title,
                        q.id
                    }
                ).ToList();
            return new ObjectResult(query);
        }

        [HttpGet]
        public IActionResult GetFaultTypeListByMachineId(int machineid, int faulttype = 1)
        {
            var machine = _machineRepository.Get(q => q.id == machineid && q.projectid == ProjectId && q.status == (int)RowState.Valid);
            if (machine == null)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }
            Expression<Func<siger_project_machine_fault, bool>> funcFault = f => true;
            if (faulttype != 0)
            {
                funcFault = f => f.fault_type.Equals(faulttype);
            }
            Expression<Func<siger_project_machine_fault, bool>> funcCommon = q =>
                q.typeid == machine.typeid && q.parentid == 0 && q.status == (int)RowState.Valid &&
                q.projectid == ProjectId;
            var predicate = funcFault.And(funcCommon);
            var query = _faultTypeRepository.GetList(predicate).Select(q =>
                new
                {
                    faulttype = q.title,
                    q.description,
                    q.fault_type,
                    q.id
                }).ToList();
            return new ObjectResult(query);
        }

        [HttpGet]
        public IActionResult GetFaultTypeListByType(int type)
        {
            var query = _faultTypeRepository.GetList(q =>
                    q.fault_type == type && q.parentid == 0 && q.status == (int)RowState.Valid &&
                    q.projectid == ProjectId)
                    .Select(q =>
                        new
                        {
                            faulttype = q.title,
                            q.description,
                            q.fault_type,
                            q.id
                        }
                    ).ToList();
            return new ObjectResult(query);
        }

        [HttpGet]
        public IActionResult GetFaultTypeList(int machinetypeid)
        {
            var query = _faultTypeRepository.GetList(q =>
                    q.typeid == machinetypeid && q.parentid == 0 && q.status == (int)RowState.Valid &&
                    q.projectid == ProjectId)
                    .Select(q =>
                        new
                        {
                            faulttype = q.title,
                            q.description,
                            q.fault_type,
                            q.id
                        }
                    ).ToList();
            return new ObjectResult(query);
        }

        [HttpGet]
        public IActionResult GetFaultList(int typeid, int faulttype, int page, int pagesize)
        {
            Expression<Func<siger_project_machine_fault, bool>> funcFault = f => true;
            if (faulttype != 0)
            {
                funcFault = f => f.fault_type.Equals(faulttype);
            }
            Expression<Func<siger_project_machine_fault, bool>> funcCommon = q =>
                    q.typeid == typeid && q.parentid == 0 && q.status == (int)RowState.Valid &&
                    q.projectid == ProjectId;
            var predicate = funcFault.And(funcCommon);
            var query = _faultTypeRepository.GetPagedList(page, pagesize, predicate, "id");
            return new PagedObjectResult(query.Data, query.Total, page, pagesize);
        }

        [HttpGet]
        public IActionResult GetFailureModeList(int machinetypeid, int page, int pagesize)
        {
            var data = _faultTypeRepository.GetPagedInvalidMode(machinetypeid, ProjectId, page, pagesize);
            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }
        /// <summary>
        /// skf故障代码添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddFaultType([FromBody]RequestAddFaultType request)
        {
            var isExist = _faultTypeRepository.Get(q =>
                q.projectid == ProjectId && q.parentid == 0 && q.status == (int)RowState.Valid
                && q.title == request.title && q.typeid == request.typeid && q.fault_type.Equals(request.fault_type));
            if (isExist != null)
            {
                throw new ServerException(1192);
            }

            var entity = new siger_project_machine_fault
            {
                create_mid = UserId,
                create_ip = ServerIpAddress,
                title = request.title,
                typeid = request.typeid,
                parentid = 0,
                projectid = ProjectId,
                description = request.description,
                fault_type = request.fault_type
            };
            _faultTypeRepository.Insert(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult EditFaultType([FromBody]RequestAddFaultType request)
        {
            var entity = _faultTypeRepository.Get(q =>
                q.projectid == ProjectId && q.status == (int)RowState.Valid
                && q.id == request.id);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            entity.title = request.title;
            entity.fault_type = request.fault_type;
            entity.description = request.description;
            _faultTypeRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult EditInvalidMode([FromBody]RequestEditInvalidMode request)
        {
            var isExist = _faultTypeRepository.Get(q =>
                q.projectid == ProjectId && q.title == request.faulttype && q.id != request.faultcontentid.ToInt());
            if (isExist != null)
            {
                throw new BadRequestException(RequestEnum.TitleHasExist);
            }

            var entity = _faultTypeRepository.Get(q => q.id == request.faultcontentid.ToInt());
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            entity.title = request.faultcontent;
            entity.status = request.status.ToInt();

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

        /// <summary>
        /// 删除故障类型
        /// </summary>
        /// <param name="typeid"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DeleteFaultType(int typeid)
        {
            var entity = _faultTypeRepository.Get(q => q.id == typeid && q.status == (int)RowState.Valid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            entity.status = (int)RowState.Invalid;
            _faultTypeRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 批量删除故障模式
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DeleteFaultTypeByIds([FromBody]RequestIdsArry request )
        {
            if (!request.ids.Any())
                throw new BadRequestException(RequestEnum.ParameterMiss);
            foreach (var id in request.ids)
            {
                var entity = _faultTypeRepository.Get(q => q.id == id );
                if (entity == null)
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }

                entity.status = (int)RowState.Invalid;
                _faultTypeRepository.Update(entity);
            }
           
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 删除失效模式
        /// </summary>
        /// <param name="contentid"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DeleteInvalidMode(int contentid)
        {
            var entity = _faultTypeRepository.Get(contentid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

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