using Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.App;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository.Domain;
using System.Text;
using OpenAuth.App.BaseApp.Base;

namespace OpenAuth.WebApi.Controllers
{
    /// <summary>
    /// 流程模版基本信息
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WFSchemeInfoController : ControllerBase
    {
        WFSchemeInfoApp schemeInfoApp;
        public WFSchemeInfoController(WFSchemeInfoApp schemeInfoApp)
        {
            this.schemeInfoApp = schemeInfoApp;
        }

        #region 查询

        #region 实例
        /// <summary>
        /// 获取流程模板数据
        /// </summary>
        /// <param name="code">流程编码</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<WFSchemeDto>> Get(string code)
        {
            var dto = new Response<WFSchemeDto>
            {
                Result = new WFSchemeDto(),
                Message = "success"
            };
            dto.Result.Schemeinfo = await schemeInfoApp.GetInfoEntityByCode(code);
            if (dto.Result.Schemeinfo == null)
            {
                return dto;
            }

            dto.Result.Scheme = await schemeInfoApp.GetSchemeEntity(dto.Result.Schemeinfo.SchemeId);
            dto.Result.SchemeAuthList = await schemeInfoApp.GetAuthList(dto.Result.Schemeinfo.Id);
            return dto;
        }
        #endregion

        #region 模版分页数据
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="PageReq">分页参数</param>
        /// <param name="category">分类</param>
        /// <param name="ids">主键数据</param>
        /// <returns></returns> 
        [HttpGet]
        public async Task<Response<PageInfo<List<WFSchemeInfo>>>> LoadPage([FromQuery] PageReq pageReq, string category, string ids)
        {
            var pageInfo = await schemeInfoApp.LoadPage(pageReq, category, ids);
            return new Response<PageInfo<List<WFSchemeInfo>>>
            {
                Result = pageInfo,
                Message = "success"
            };
        }
        #endregion

        #region 可用模版集合
        /// <summary>
        /// 可用模版集合
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<List<WFSchemeInfo>>> Load()
        {
            var data = await schemeInfoApp.Load();
            return new Response<List<WFSchemeInfo>>
            {
                Result = data,
                Message = "success"
            };
        }
        #endregion

        #region 获取自定义流程列表(后续可能权限用)
        /// <summary>
        /// 获取自定义流程列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<List<WFSchemeInfo>>> GetInfoList()
        {
            var data = await schemeInfoApp.GetInfoList();
            return new Response<List<WFSchemeInfo>>
            {
                Result = data,
                Message = "success"
            };
        }
        #endregion

        #endregion

        #region 新增
        /// <summary>
        /// 新增流程模板
        /// </summary>
        /// <param name="nWFSchemeDto">提交参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> Add(WFSchemeDto nWFSchemeDto)
        {
            var result = new Response<bool>();
            try
            {
                // 验证流程编码是否重复
                var schemeInfoEntityTmp = await schemeInfoApp.GetInfoEntityByCode(nWFSchemeDto.Schemeinfo.Code);
                if (schemeInfoEntityTmp != null)
                {
                    throw new Exception("流程编码重复");

                }
                result = await schemeInfoApp.SaveEntity(string.Empty, nWFSchemeDto.Schemeinfo, nWFSchemeDto.Scheme, nWFSchemeDto.SchemeAuthList);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }
        #endregion

        #region 修改
        /// <summary>
        /// 更新流程模板
        /// </summary>
        /// <param name="id">流程主键</param>
        /// <param name="nWFSchemeDto">提交参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> Update(string id, WFSchemeDto nWFSchemeDto)
        {
            var result = new Response<bool>();
            try
            {
                // 验证流程编码是否重复
                var schemeInfoEntityTmp = await schemeInfoApp.GetInfoEntityByCode(nWFSchemeDto.Schemeinfo.Code);
                if (schemeInfoEntityTmp != null && schemeInfoEntityTmp.Id != id)
                {
                    throw new Exception("流程编码重复");

                }
                result = await schemeInfoApp.SaveEntity(id, nWFSchemeDto.Schemeinfo, nWFSchemeDto.Scheme, nWFSchemeDto.SchemeAuthList);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }
            return result;
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除模板数据
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> Delete(string id)
        {
            var result = new Response<bool>();
            try
            {
                result = await schemeInfoApp.DeleteEntity(id);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }
        #endregion

        #region 更新流程模板版本
        /// <summary>
        /// 更新流程模板版本
        /// </summary>
        /// <param name="id">流程模板主键</param>
        /// <param name="schemeId">历史记录主键</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> UpdateScheme(string id, string schemeId)
        {
            var result = new Response<bool>();
            try
            {
                result = await schemeInfoApp.UpdateScheme(id, schemeId);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }
        #endregion

        #region 启用/停用流程
        /// <summary>
        /// 启用/停用流程
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="state">状态1启用0禁用</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> UpdateState(string id, int state)
        {
            var result = new Response<bool>();
            try
            {
                result = await schemeInfoApp.UpdateState(id, state);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }
        #endregion      

        #region 导入导出【暂时不做】
        /// <summary>
        /// 导出流程模板数据
        /// </summary>
        /// <param name="code">流程编码</param>
        /// <returns></returns>
        //[HttpGet("workflow/scheme/download/{code}")]
        //[AllowAnonymous]
        //[ProducesResponseType(typeof(FileContentResult), 200)]
        //public async Task<IActionResult> ExportScheme(string code)
        //{
        //    WFSchemeInfoEntity schemeInfoEntity = await _nWFSchemeIBLL.GetInfoEntityByCode(code);
        //    if (schemeInfoEntity != null)
        //    {
        //        WFSchemeEntity schemeEntity = await _nWFSchemeIBLL.GetSchemeEntity(schemeInfoEntity.F_SchemeId);
        //        var nWFSchemeAuthList = await _nWFSchemeIBLL.GetAuthList(schemeInfoEntity.F_Id);
        //        var jsonData = new
        //        {
        //            info = schemeInfoEntity,
        //            scheme = schemeEntity,
        //            authList = nWFSchemeAuthList
        //        };

        //        string data = jsonData.ToJson();
        //        byte[] arr = Encoding.UTF8.GetBytes(data);
        //        return File(arr, "application/octet-stream", schemeInfoEntity.F_Name + ".lrwf");
        //    }
        //    else
        //    {
        //        return File(Encoding.UTF8.GetBytes("{}"), "application/octet-stream", schemeInfoEntity.F_Name + ".lrwf");
        //    }
        //}
        /// <summary>
        /// 导入流程模板（暂定）
        /// </summary>
        /// <param name="fileId">文件主键</param>
        /// <param name="chunks">分片数</param>
        /// <param name="ext">文件扩展名</param>
        /// <returns></returns>
        //[HttpPost("workflow/scheme/upload")]
        //[AllowAnonymous]
        //[ProducesResponseType(typeof(ResponseDto), 200)]
        //public async Task<IActionResult> ExecuteImportScheme(string fileId, int chunks, string ext)
        //{
        //    string path = _annexesFileIBLL.SaveAnnexes(fileId, fileId + "." + ext, chunks);
        //    if (!string.IsNullOrEmpty(path))
        //    {
        //        // 读取导入文件
        //        string data = System.IO.File.ReadAllText(path);
        //        // 删除临时文件
        //        System.IO.File.Delete(path);
        //        if (!string.IsNullOrEmpty(data))
        //        {
        //            WFSchemeDto nWFSchemeModel = data.ToObject<WFSchemeDto>();
        //            // 验证流程编码是否重复
        //            WFSchemeInfoEntity schemeInfoEntityTmp = await _nWFSchemeIBLL.GetInfoEntityByCode(nWFSchemeModel.Schemeinfo.F_Code);
        //            if (schemeInfoEntityTmp != null)
        //            {
        //                nWFSchemeModel.Schemeinfo.F_Code = Guid.NewGuid().ToString();
        //            }
        //            await _nWFSchemeIBLL.SaveEntity("", nWFSchemeModel.Schemeinfo, nWFSchemeModel.Scheme, nWFSchemeModel.SchemeAuthList);
        //        }
        //        return SuccessInfo("导入成功");
        //    }
        //    else
        //    {
        //        return Fail("导入模板失败!");
        //    }
        //}
        #endregion

        #region 注释掉内容
        /// <summary>
        /// 获取流程模板数据
        /// </summary>
        /// <param name="code">流程编码</param>
        /// <returns></returns>
        //[HttpGet("workflow/scheme/{code}")]
        //public async Task<Response<WFSchemeDto>> GetFormData(string code)
        //{
        //    var dto = new Response<WFSchemeDto>
        //    {
        //        Result = new WFSchemeDto(),
        //        Message = "success"
        //    };
        //    dto.Result.Schemeinfo = await schemeInfoApp.GetInfoEntityByCode(code);
        //    if (dto.Result.Schemeinfo == null)
        //    {
        //        return dto;
        //    }

        //    dto.Result.Scheme = await schemeInfoApp.GetSchemeEntity(dto.Result.Schemeinfo.SchemeId);
        //    dto.Result.SchemeAuthList = await schemeInfoApp.GetAuthList(dto.Result.Schemeinfo.Id);
        //    return dto;
        //}


        /// <summary>
        /// 获取模板分页数据
        /// </summary>
        /// <param name="paginationInputDto">分页参数</param>
        /// <param name="id">流程模板信息主键</param>
        /// <returns></returns>
        //[HttpGet("workflow/scheme/history/page/{id}")]
        //public async Task<Response<PageInfo<List<WFScheme>>>> GetSchemePageList(string id, [FromQuery] PageReq pageReq)
        //{
        //    var pageInfo = await schemeInfoApp.GetSchemePageList(pageReq, id);
        //    return new Response<PageInfo<List<WFScheme>>>
        //    {
        //        Result = pageInfo,
        //        Message = "success"
        //    };
        //}


        /// <summary>
        /// 获取模板分页数据
        /// </summary>
        /// <param name="paginationInputDto">分页参数</param>
        /// <param name="id">流程模板信息主键</param>
        /// <returns></returns>
        //[HttpGet("workflow/scheme/historys/{id}")]
        //public async Task<Response<List<WFScheme>>> GetSchemeList(string id)
        //{
        //    var data = await schemeInfoApp.GetSchemeList(id);
        //    return new Response<List<WFScheme>>
        //    {
        //        Result = data,
        //        Message = "success"
        //    };
        //}

        /// <summary>
        /// 获取流程模板数据
        /// </summary>
        /// <param name="id">模板主键</param>
        /// <returns></returns>
        //[HttpGet("workflow/scheme/history/{id}")]
        //public async Task<Response<WFScheme>> GetScheme(string id)
        //{
        //    var data = await schemeInfoApp.GetScheme(id);
        //    return new Response<WFScheme>
        //    {
        //        Result = data,
        //        Message = "success"
        //    };
        //}
        #endregion
    }
}
