using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Exceptions;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.FieldEnum;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.EsopRepository.Entities;
using Siger.Middlelayer.EsopRepository.Repositories.Interface;
using Siger.Middlelayer.EsopRepository.Request;
using Siger.Middlelayer.EsopRepository.Response;
using Siger.Middlelayer.Repository;

namespace Siger.ApiEsop.Controllers
{
    public class EsopDocumentCreateController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IEsopDocumentCreateRepository _createRepository;
        private readonly IEsopDocumentApproval _documentApproval;
        private readonly IEsopProcessRepository _processRepository;
        private readonly IEsopDocumentHistoryRepository _documentHistoryRepository;
        private readonly IEsopDocumentSetRepository _documentSetRepository;
        public EsopDocumentCreateController(IUnitOfWork unitOfWork, IEsopDocumentCreateRepository createRepository, IEsopDocumentApproval documentApproval,
            IEsopDocumentHistoryRepository documentHistoryRepository, IEsopDocumentSetRepository documentSetRepository,
            IEsopProcessRepository processRepository)
        {
            _unitOfWork = unitOfWork;
            _documentHistoryRepository = documentHistoryRepository;
            _documentSetRepository = documentSetRepository;
            _createRepository = createRepository;
            _documentApproval = documentApproval;
            _processRepository = processRepository;
        }

        [HttpGet]
        public IActionResult GetDocumentPagedList(string starttime, string endtime, int status, int type, string keyword, int page = 1, int pagesize = 10)
        {
            var data = _createRepository.GetDocumentPagedList(starttime, endtime, status, type, keyword, ProjectId, UserId,
                page, pagesize);

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

        /// <summary>
        /// 创建文档
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddDocument([FromBody]RequestAddDocumentCreate request)
        {
            var isExist = _createRepository.IsExist(q => q.name == request.name && q.project_id == ProjectId && q.status == (int)RowState.Valid);
            if (isExist)
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }
            if (request.default_display==1)
            {
                var res = _createRepository.GetList(q => q.product_id == request.product_id && q.project_id == ProjectId && q.status == (int)RowState.Valid);
                if (res.Any())
                {
                    var docIds = res.Select(s => s.id).ToList();
                    var his = _documentHistoryRepository.Get(q =>docIds.Contains( q.document_id) && q.default_display == 1 && q.status == (int)RowState.Valid);
                    if (his!=null)
                    {
                        throw new BadRequestException(RequestEnum.DefaultDisplayExists);
                    }
                }
            }
            var result = _createRepository.AddDocument(request, ProjectId, UserId);
            if (result)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 修改文档
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateDocument([FromBody]RequestUpdateDocumentCreate request)
        {
            var isExist = _createRepository.IsExist(q => q.name == request.name && q.project_id == ProjectId && q.status == (int)RowState.Valid
                                                         && q.id != request.id);
            if (isExist)
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }
            var entity = _createRepository.Get(request.id);
            if (entity == null || entity.status != (int)RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var docType = _documentSetRepository.Get(entity.type_id);
            //if (entity.approval_status != DocumentApprovalStatus.UnApproval)
            //{
            //    throw new BadRequestException(RequestEnum.CannotUpdate);
            //}
            if (docType.process_id!=0)
            {
                entity.approval_status = DocumentApprovalStatus.UnApproval; //审核后 允许修改，并重新审核
                var approval = _documentApproval.GetList(f => f.document_id == entity.id,"id").FirstOrDefault();
                if (approval != null)
                {
                    if (approval.approval_result == 1)
                    {
                        _documentApproval.Insert(new siger_project_esop_document_approval
                        {
                            approval_result = 0,
                            document_id = entity.id,
                            create_time = DateTime.Now,
                            creator_mid = UserId,
                            status = 1,
                            step_number = approval.step_number
                        });
                    }
                }
            }
            entity.name = request.name;
            entity.type_id = request.type_id;
            entity.machine_id = request.machine_id;
            entity.section_id = request.section_id;
            entity.product_id = request.product_id;
           
            entity.remark = request.remark;
          
            _createRepository.Update(entity);

            //修改文件
            var historylst = _documentHistoryRepository.GetList(q => q.document_id == entity.id && q.is_valid == 1 && q.status == (int)RowState.Valid);
            if (historylst.Any())
            {
                foreach (var history in historylst)
                {
                    history.file_name = request.file_name;
                    history.file_url = request.file_url;
                    history.default_display = request.default_display;
                    _documentHistoryRepository.Update(history);
                }
            }

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

        /// <summary>
        /// 撤回
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult RecallDocument(int id)
        {
            var entity = _createRepository.Get(id);
            if (entity == null || entity.status != (int)RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            //审核通过的不能撤回
            if (entity.approval_status == DocumentApprovalStatus.ApprovalPass)
            {
                throw new BadRequestException(RequestEnum.CannotRecall);
            }
            //只有创建人可以撤回
            if (entity.creator_mid != UserId)
            {
                throw new BadRequestException(RequestEnum.NoAuthorityRecall);
            }

            entity.approval_status = DocumentApprovalStatus.HasRecall;
            _createRepository.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 UpdateVersion([FromBody]RequestUpdateDocumentVersion request)
        {
            var entity = _createRepository.Get(request.id);
            var oldname = string.Empty;
            if (entity == null || entity.status != (int)RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var defautDisplay = 0;
            var his = _documentHistoryRepository.GetList(q => q.document_id == entity.id && q.status == (int)RowState.Valid).ToList();
            if (his.Any())
            {
                foreach (var history in his)
                {
                    if (history.is_valid != 0)
                    {
                        defautDisplay = history.default_display;
                        oldname = history.version_name;
                        history.is_valid = 0;
                        _documentHistoryRepository.Update(history);
                    }
                }
            }

            var newHis = new siger_project_esop_document_history
            {
                update_time = DateTime.Now,
                updator_mid = UserId,
                file_name = request.file_name,
                file_url = request.file_url,
                is_valid = 1,
                document_id = entity.id,
                version = his.Max(m => m.version) + 1,
                version_name = request.file_name,
                default_display= defautDisplay
            };

            _documentHistoryRepository.Insert(newHis);

            //修改文档状态为待审核
            var type = _documentSetRepository.Get(q => q.id == entity.type_id && q.project_id == ProjectId && q.status == (int)RowState.Valid);
            if (type?.process_id > 0)
            {
                entity.approval_status = DocumentApprovalStatus.UnApproval;
            }
            _createRepository.Update(entity);

            //清空审批记录
            _createRepository.ClearApprovalRecords(entity.id);

            if (_unitOfWork.Commit() > 0)
            {
                //update sensor
                if (!string.IsNullOrEmpty(oldname) && !string.IsNullOrEmpty(request.file_name))
                {
                    _documentHistoryRepository.UpdateSensorFile(ProjectId, oldname, request.file_name);
                }
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 获取文档记录
        /// </summary>
        /// <param name="document_id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllVersion(int document_id)
        {
            var his = _documentHistoryRepository.GetDocumentHistoryLists(document_id);

            return new ObjectResult(his.ToList());
        }

        /// <summary>
        /// 文档更新
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateValidVersion([FromBody]RequestUpdateValidVersion request)
        {
            var oldname = string.Empty;
            var histories = _documentHistoryRepository.GetList(q => q.document_id == request.document_id && q.status == (int)RowState.Valid);
            foreach (var history in histories.ToList())
            {
                if (history.is_valid == 1)
                {
                    oldname = history.version_name;
                }
                history.is_valid = 0;
                _documentHistoryRepository.Update(history);
            }

            var his = _documentHistoryRepository.Get(q => q.document_id == request.document_id && q.id == request.history_id);
            if (his != null)
            {
                if (!string.IsNullOrEmpty(request.version_name))
                {
                    var isExist = _documentHistoryRepository.Get(f => f.status != 0 && f.version_name == request.version_name);
                    if (isExist != null && isExist.id != request.history_id)
                    {
                        throw new BadRequestException(EsopEnum.FileVersionNameExist);
                    }
                }
                his.version_name = request.version_name;
                his.is_valid = 1;
            }
            _documentHistoryRepository.Update(his);
            if (_unitOfWork.Commit() > 0)
            {
                var newname = histories.FirstOrDefault(f => f.is_valid == 1)?.version_name ?? "";
                if (!string.IsNullOrEmpty(oldname) && !string.IsNullOrEmpty(newname))
                {
                    _documentHistoryRepository.UpdateSensorFile(ProjectId, oldname, newname);
                }
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 文档审批列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetDocumentAuditPagedList(int page = 1, int pagesize = 10)
        {
            var data = _createRepository.GetDocumentAuditPagedList(UserId, ProjectId, page, pagesize);

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

        /// <summary>
        ///文档审批
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ApprovalDocument([FromBody]RequestApprovalDocument request)
        {
            var entity = _createRepository.Get(request.id);
            if (entity == null || entity.status != (int)RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            if (entity.approval_status != DocumentApprovalStatus.InProcess &&
                entity.approval_status != DocumentApprovalStatus.UnApproval)
            {
                throw new BadRequestException(RequestEnum.CannotApprovalThisDocument);
            }

            //查看审批过程
            var type = _documentSetRepository.Get(q => q.id == entity.type_id && q.status == (int)RowState.Valid);
            if (type == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var processs = _processRepository.GetProcessFlows(type.process_id);
            if (!processs.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var result = _createRepository.ApprovalDocument(processs, entity.id, type.process_id, request.ispass, UserId);
            switch (result)
            {
                case EsopApprovalResult.HaveNoRight:
                    throw new BadRequestException(RequestEnum.HaveNoRightApprove);
                case EsopApprovalResult.CannotApprovalAgain:
                    throw new BadRequestException(RequestEnum.CannotApprovalAgain);
                case EsopApprovalResult.CurrentApprovalStepNotFound:
                    throw new BadRequestException(RequestEnum.CurrentApprovalStepNotFound);
            }

            return new ObjectResult(CommonEnum.Succefull);
        }

        /// <summary>
        /// 获取文档审批记录
        /// </summary>
        /// <param name="document_id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllApproval(int document_id)
        {
            var entity = _createRepository.Get(document_id);
            if (entity == null || entity.status != (int)RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            return new ObjectResult(_createRepository.GetApprovalLists(document_id).ToList());
        }

        /// <summary>
        /// 按照文档类型和名称搜索
        /// </summary>
        /// <param name="typeId"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetDocumentsByType(int typeId = 0, string name = "")
        {
            var documents = _createRepository.GetDocumentsByType(typeId, name, ProjectId);

            return new ObjectResult(documents);
        }

        /// <summary>
        /// 获取文档
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllDocumentSet(int productId)
        {
            var data = new ResponseFileSets();
            var list = new List<ResponseTypeFile>();
            var set = _createRepository.GetEsopFileSet(productId, ProjectId);
            if (set.Any())
            {
                var typeList = set.Select(q => q.typeid).Distinct();
                foreach (var item in typeList)
                {
                    var files = set.Where(q=>q.typeid== item);

                    var type = new ResponseTypeFile()
                    {
                        type = files.FirstOrDefault().type,
                        typeid=files.FirstOrDefault().typeid
                    };
                    list.Add(type);
                }
            }
            data.types = list;
            data.FileList = set;
            return new ObjectResult(data);
        }
    }
}