using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using APT.Infrastructure.Api;
namespace APT.PF.WebApiControllers.Api.PF
{
    [Route("api/PF/FlowInstance")]
	public class FlowInstanceController : APTApiController<T_PF_FLOW_INSTANCE>
	{
		IPFFlowService FlowService { get; set; }
		public FlowInstanceController(IPFFlowService flowService)
		{
			this.FlowService = flowService;
		}



		/// <summary>
		/// 查询
		/// </summary>
		/// <param name="filter"></param>
		/// <returns></returns>
		[HttpPost, Route("Entities")]
		public JsonActionResult<IEnumerable<T_PF_FLOW_INSTANCE>> Entities([FromBody]KeywordFilter filter)
		{
			return WitEntities(null, filter);
		}
		/// <summary>
		/// 查询
		/// </summary>
		/// <param name="filter"></param>
		/// <returns></returns>
		/// 

		[HttpPost, Route("OrderEntities")]
		public JsonActionResult<IEnumerable<T_PF_FLOW_INSTANCE>> OrderEntities([FromBody]KeywordFilter filter)
		{
			return WitOrderEntities(null, filter);
		}
		/// <summary>
		/// 查询
		/// </summary>
		/// <param name="pageFilter"></param>
		/// <returns></returns>
		[HttpPost, Route("Paged")]
		public PagedActionResult<T_PF_FLOW_INSTANCE> Paged([FromBody]KeywordPageFilter pageFilter)
		{
			return WitPaged(null, pageFilter);
		}
		/// <summary>
		/// 查询
		/// </summary>
		/// <param name="pageFilter"></param>
		/// <returns></returns>
		[HttpPost, Route("OrderPaged")]
		public PagedActionResult<T_PF_FLOW_INSTANCE> OrderPaged([FromBody]KeywordPageFilter pageFilter)
		{
			return WitOrderPaged(null, pageFilter);
		}
		/// <summary>
		/// 删除
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[HttpGet, Route("Delete")]
		public JsonActionResult<bool> Delete(string id)
		{
			return WitDelete(id);
		}

		/// <summary>
		/// 更新
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[HttpPost, Route("Update")]
		public JsonActionResult<bool> Update([FromBody]T_PF_FLOW_INSTANCE entity)
		{
			return WitUpdate(entity);
		}

		/// <summary>
		/// 批量删除
		/// </summary>
		/// <param name="ids"></param>
		/// <returns></returns>
		[HttpGet, Route("BatchDelete")]
		public JsonActionResult<bool> BatchDelete(string ids)
		{
			return WitBatchDelete(ids);
		}


		/// <summary>
		/// 获得单条实体数据
		/// </summary>
		/// <param name="filter"></param>
		/// <returns></returns>
		[HttpPost, Route("Get")]
		public JsonActionResult<T_PF_FLOW_INSTANCE> Get([FromBody] KeywordFilter filter)
		{
			return WitEntity(null, filter);
		}

		[HttpPost, Route("Add")]
		public JsonActionResult<bool> Add([FromBody] JObject obj)
		{
			return SafeExecute<bool>(() =>
			{
				var org = this.GetEntity<T_FM_ORGANIZATION>(t => true);
				if (org == null)
					throw new Exception("设置组织");
				T_FM_USER user = new T_FM_USER();
				user.NAME = "测试" + DateTime.Now.ToString();
				user.CODE = DateTime.Now.ToString();
				user.ORG_ID = org.ID;
				//var entityService = ServiceUtils.GetCommonService<T_FM_USER>();
				this.AddEntity< T_FM_USER>(user);

				var flowInstance = obj.ToObject<T_PF_FLOW_INSTANCE>();
				SendFlowParam param = new SendFlowParam();
				if (flowInstance.InstanceSchemeId != null)
					param.FlowSchemeId = flowInstance.InstanceSchemeId.Value;
				param.OrgId = flowInstance.ORG_ID;
				param.EntityId = user.ID;
				param.Description = flowInstance.Description;
				this.FlowService.SendFlow<T_FM_USER>(param);
				return true;
			});
			 
		}


		[HttpPost, Route("GetFlow")]
		public JsonActionResult<FlowResponse> GetFlow([FromBody]KeywordFilter filter)
		{
			return SafeExecute<FlowResponse>(() =>
			{
				var flowService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFlowService>();
				return flowService.GetFlow(filter);
			});
		}

		[HttpPost, Route("PermitFlow")]
		public JsonActionResult<bool> PermitFlow([FromBody] VerificationReq request)
		{
			return SafeExecute<bool>(() =>
			{
				var fmFlowPermitService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IFMFlowPermitService>();
				PermitFlowParam param = new PermitFlowParam();
				if (!string.IsNullOrEmpty(request.FlowInstanceId))
					param.FlowId = new Guid(request.FlowInstanceId);
				else
					throw new Exception("流程ID 不允许为空");
				param.NodeRejectStep = request.NodeRejectStep;
				param.Description = request.VerificationOpinion;
				param.UserId = request.UserId;
				param.UserName = request.UserName;
				if (request.VerificationFinally == "3")
				{
					param.PermitStatus = (int)PPFlowPermitStatusEnum.驳回;
				}
				else if (request.VerificationFinally == "2")//表示不同意
				{
					param.PermitStatus = (int)PPFlowPermitStatusEnum.不同意;
				}
				else if (request.VerificationFinally == "1")//表示同意
				{
					param.PermitStatus = (int)PPFlowPermitStatusEnum.同意;
				}
				this.FlowService.PermitFlowSimple(param);
				fmFlowPermitService.AfterPermit(param.FlowId.ToString(), param.PermitStatus);

				return true;
			});
			 
		}


		[HttpPost, Route("PassFlowByBatch")]
		public JsonActionResult<bool> PassFlowByBatch([FromBody] VerificationPassBatchReq request)
		{
			return SafeExecute<bool>(() =>
			{
				if (request == null || string.IsNullOrEmpty(request.Ids)) return false;
				var arry = request.Ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
				if (arry == null || arry.Length == 0) return false;

				foreach(var item in arry)
				{
					PermitFlowParam param = new PermitFlowParam();
					param.FlowId = new Guid(item);
					param.Description = "批次审核通过";
					param.UserId = request.UserId;
					param.UserName = request.UserName;
					param.PermitStatus = (int)PPFlowPermitStatusEnum.同意;
					this.FlowService.PermitFlowSimple(param);
				}
				return true;
			});

		}


		/// <summary>
		/// 加载列表
		/// </summary>
		[HttpPost, Route("QueryFlowInstance")]
		public PagedActionResult<T_PF_FLOW_INSTANCE> QueryFlowInstance([FromBody]KeywordPageFilter pageFilter)
		{
			return SafeGetPagedData<T_PF_FLOW_INSTANCE>(result =>
		   {
			   var flowService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFlowService>();
			   var data=  flowService.QueryFlowInstance(pageFilter);
			   result.Data = data.Items;
			   result.TotalCount = data.TotalCount;
		   });
		}



		/// <summary>
		/// 查询操作日志
		/// </summary>
		/// <param name="filter"></param>
		/// <returns></returns>
		[HttpPost, Route("GetOperHistoryList")]
		public JsonActionResult<IEnumerable<T_PF_FLOW_INSTANCE_OPER_HIS>> GetOperHistoryList([FromBody]KeywordFilter filter)
		{
			return SafeExecute<IEnumerable<T_PF_FLOW_INSTANCE_OPER_HIS>>(() =>
			{
				return this.GetOrderEntities<T_PF_FLOW_INSTANCE_OPER_HIS>(null, filter);
			});
		}
		
		/// <summary>
		/// 加载自定人员
		/// </summary>
		/// <param name="filter"></param>
		/// <returns></returns>
		[HttpPost, Route("LoadUser")]
		public FlowLoadResult LoadUser([FromBody] KeywordFilter filter)
		{
			if (filter == null)
				filter = new KeywordFilter();
			var result = new FlowLoadResult();
			var list = this.GetEntities<T_FM_USER>(null, filter).ToList();
			result.count = list.Count;
			result.data = list;
			return result;
		}

		/// <summary>
		/// 加载自定角色
		/// </summary>
		/// <param name="filter"></param>
		/// <returns></returns>
		[HttpPost, Route("LoadRole")]
		public FlowLoadResult LoadRole([FromBody] KeywordFilter filter)
		{
			if (filter == null)
				filter = new KeywordFilter();
			var result = new FlowLoadResult();
			var list = this.GetEntities<T_FM_ROLE>(null, filter).ToList();
			result.count = list.Count;
			result.data = list;
			return result;
		}

		/// <summary>
		/// 加载自定组织
		/// </summary>
		/// <param name="filter"></param>
		/// <returns></returns>
		[HttpPost, Route("LoadOrg")]
		public FlowLoadResult LoadOrg([FromBody] KeywordFilter filter)
		{
			if (filter == null)
				filter = new KeywordFilter();
			var result = new FlowLoadResult();
			var list = this.GetEntities<T_FM_ORGANIZATION>(null, filter).ToList();
			result.count = list.Count;
			result.data = list;
			return result;
		}
	}
}
