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

namespace Siger.ApiConfig.Controller
{
    public class DocumentController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IMachineDocumentRepository _documentRepository;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly ISigerProjectMachineTypeRepository _machineTypeRepository;
        private readonly ISigerProjectLevelSectionRepository _sectionRepository;
        private readonly IMachineDocumentTypeRepository _machineDocumentTypeRepository;
        public DocumentController(IUnitOfWork unitOfWork, IMachineDocumentRepository documentRepository,
            ISigerProjectMachineRepository machineRepository, ISigerProjectMachineTypeRepository machineTypeRepository,
            ISigerProjectLevelSectionRepository sectionRepository, IMachineDocumentTypeRepository machineDocumentTypeRepository)
        {
            _unitOfWork = unitOfWork;
            _documentRepository = documentRepository;
            _machineRepository = machineRepository;
            _machineTypeRepository = machineTypeRepository;
            _sectionRepository = sectionRepository;
            _machineDocumentTypeRepository = machineDocumentTypeRepository;
        }

        [HttpPost]
        public IActionResult GetMachineDocInfo([FromBody] RequestGetPagedDocument request)
        {
            var machineIds = new List<int>();
            if (request.machinetype2.ToInt() != 0)
            {
                machineIds = _machineRepository.GetList(q =>
                        q.typeid == request.machinetype2.ToInt() && q.projectid == ProjectId && q.status == (int) RowState.Valid)
                    .Select(m => m.id).ToList();
            }
            else if (request.machinetype1.ToInt() != 0)
            {
                var machineTypeids = _machineTypeRepository.GetList(q => q.parentid == request.machinetype1.ToInt() && q.status == (int) RowState.Valid)
                    .Select(m => m.id).ToList();

                machineIds = _machineRepository.GetList(q =>
                        machineTypeids.Contains(q.typeid) && q.projectid == ProjectId && q.status == (int)RowState.Valid)
                    .Select(m => m.id).ToList();
            }
            else
            {
                machineIds = _machineRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid)
                    .Select(m => m.id).ToList();
            }

            if (!machineIds.Any())
            {
                return new PagedObjectResult(new List<ResponseGetMachineDocumentList>(), 0, request.page, request.pagesize);
            }

            var startTime = 0;
            var endTime = 0;
            if (!string.IsNullOrWhiteSpace(request.doc_time))
            {
                var times = request.doc_time.Split(new[] {'-'}, StringSplitOptions.RemoveEmptyEntries);
                startTime = UnixTimeHelper.GetUnixByDate(times[0]);
                endTime = UnixTimeHelper.GetUnixByDate(times[1]);
            }

            var data = _documentRepository.GetPagedList(machineIds, request.doc_type.ToInt(),
                request.machine_life.ToInt(), request.doc_name, startTime, endTime, ProjectId,request.page, request.pagesize);
           
            var responses = new List<ResponseGetMachineDocumentList>();
            foreach (var document in data.Data)
            {
                var doc = Mapper<ResponseGetMachineDocumentList, ResponseGetMachineDocumentList>.Map(document);
                doc.time = UnixTimeHelper.ConvertIntDateTime(document.create_time);
                var docType = _machineDocumentTypeRepository.Get(f => f.id == doc.doc_type && f.projectid==ProjectId && f.status==(int)RowState.Valid);
                doc.doc_type_name = docType != null ? docType.title : "";
                if (document.machine_id != 0)
                {
                    var machine = _machineRepository.Get(document.machine_id);
                    if (machine != null)
                    {
                        doc.machine_name = machine.title;
                    }
                }
                else if (document.machineType_id != 0)
                {
                    var type = _machineTypeRepository.Get(document.machineType_id);
                    if (type != null)
                    {
                        doc.machine_name = type.title;
                    }
                }
                else
                {
                    doc.machine_name = "";
                }
                responses.Add(doc);
            }

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

        [HttpPost]
        public IActionResult AddMachineDocment([FromBody]RequestAddDocument request)
        {
            if (string.IsNullOrWhiteSpace(request.title))
            {
                throw new BadRequestException(RequestEnum.NameIsEmpty);
            }
            if (string.IsNullOrWhiteSpace(request.url))
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }
            var entity = new siger_project_machine_documentmanagement
            {
                machineid = request.sectionid.ToInt(),
                create_time = UnixTimeHelper.GetNow(),
                create_mid = UserId,
                machinetypeid = request.machinetypeid.ToInt(),
                projectid = ProjectId,
                remark = request.remark,
                type = request.type,
                url = request.url,
                title = request.title
            };
            _documentRepository.Insert(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetMachineDocForEdit(int id)
        {
            var entity = _documentRepository.Get(q => q.id == id && q.status == (int)RowState.Valid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var doc = Mapper<siger_project_machine_documentmanagement, ResponseGetMachineDocumentList>.Map(entity);
            doc.doc_type = entity.type;
            doc.doc_name = entity.title;
            if (entity.machineid != 0)
            {
                var machine = _machineRepository.Get(entity.machineid);
                if (machine != null)
                {
                    doc.machine_name = machine.title;
                }
            }
            else if (entity.machinetypeid != 0)
            {
                var type = _machineTypeRepository.Get(entity.machinetypeid);
                if (type != null)
                {
                    doc.machine_name = type.title;
                }
            }
            else
            {
                doc.machine_name = "";
            }

            return new ObjectResult(doc);
        }

        [HttpPost]
        public IActionResult EditMachineDoc([FromBody] RequestUpdateDocument request)
        {
            var entity = _documentRepository.Get(q => q.id == request.id && q.status == (int)RowState.Valid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            entity.title = request.title;
            entity.type = request.type;
            entity.remark = request.remark;
            entity.url = string.IsNullOrWhiteSpace(request.url) ? entity.url : request.url;

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

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

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

        /// <summary>
        /// 获取设备文档类型
        /// </summary>
        /// <param name="title">文档类型名称</param>
        /// <param name="page">页码不等于0开启分页</param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMachineDocTypes(string title, int page = PageIndex, int pagesize = PageSize)
        {
            Expression<Func<siger_project_machine_documenttype, bool>> funcCommon = f => f.projectid == ProjectId && f.status != 0;
            Expression<Func<siger_project_machine_documenttype, bool>> funcName = f => true;
            if (!string.IsNullOrEmpty(title))
            {
                funcName = f => f.title.Contains(title);
            }
            var predicates = funcCommon.And(funcName);
            if (page == 0)
            {
                return new ObjectResult(_machineDocumentTypeRepository.GetList(predicates));
            }
            else
            {
                var query = _machineDocumentTypeRepository.GetPagedList(page, pagesize, predicates);
                return new PagedObjectResult(query.Data, query.Total, page, pagesize);
            }
        }
        /// <summary>
        /// 修改添加设备文档类型
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesResponseType(typeof(RequestDocumentType), 200)]
        [HttpPost]
        public IActionResult SetMachineDocType([FromBody] RequestDocumentType request)
        {
            if (request.id == 0)
            {
                var model = _machineDocumentTypeRepository.Get(f => f.projectid == ProjectId && f.status != 0 && f.title == request.title);
                if (model != null)
                {
                    throw new BadRequestException(CommonEnum.RecordExits);
                }
                _machineDocumentTypeRepository.Insert(new siger_project_machine_documenttype
                {
                    create_time = DateTime.Now,
                    title = request.title,
                    creator = UserId,
                    editor = UserId,
                    projectid = ProjectId,
                });
            }
            else
            {
                var model = _machineDocumentTypeRepository.Get(f => f.projectid == ProjectId && f.status != 0 && f.id == request.id);
                if (model == null)
                {
                    throw new BadRequestException(CommonEnum.NoData);
                }
                model.title = request.title;
                model.editor = UserId;
                _machineDocumentTypeRepository.Update(model);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 删除设备文档类型
        /// </summary>
        /// <param name="ids">要删除的ids</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult DelMachineDocType(string ids)
        {
            var idList = ids.Split(',');
            if (!idList.Any())
            {
                throw new BadRequestException(CommonEnum.NoData);
            }
            foreach (var id in idList)
            {
                var model = _machineDocumentTypeRepository.Get(f => f.projectid == ProjectId && f.status != 0 && f.id == id.ToInt());
                if (model == null)
                {
                    throw new BadRequestException(CommonEnum.NoData);
                }
                var doc = _documentRepository.Get(f => f.status != 0 && f.projectid == ProjectId && f.type == model.id);
                if (doc != null)
                {
                    throw new BadRequestException(CommonEnum.Fail);
                }
                model.status = (int)RowState.Invalid;
                _machineDocumentTypeRepository.Update(model);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}