using Learun.Application.Base.SystemModule;
using Learun.Application.WorkFlow;
using Learun.Util;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Linq;
using Learun.Util.Constant;

namespace Learun.Application.Web.Areas.LR_NewWorkFlow.Controllers
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创建人：研发部
    /// 日 期：2018.12.06
    /// 描 述：工作流模板(新)
    /// </summary>
    public class NWFSchemeController : MvcControllerBase
    {
        private NWFSchemeIBLL nWFSchemeIBLL = new NWFSchemeBLL();
        private AnnexesFileIBLL annexesFileIBLL = new AnnexesFileBLL();

        #region 视图功能
        /// <summary>
        /// 主页面（协同设计平台）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 主页面（系统管理）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CommonIndex()
        {
            return View();
        }
        /// <summary>
        /// 表单页面（协同设计平台）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Form()
        {
            return View();
        }
        /// <summary>
        /// 表单页面（系统管理）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CommonForm()
        {
            return View();
        }

        /// <summary>
        /// 复制流程页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CopyForm()
        {
            return View();
        }

        /// <summary>
        /// 表单页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ReIndex()
        {
            return View();
        }

        /// <summary>
        /// 流程模板分类页面（单位）
        /// </summary>
        /// <returns></returns>
        public ActionResult CategoryIndex()
        {
            return View();
        }

        /// <summary>
        /// 流程模板分类表单（单位）
        /// </summary>
        /// <returns></returns>
        public ActionResult CategoryForm()
        {
            return View();
        }
        /// <summary>
        /// 流程模板分类页面(项目级)
        /// </summary>
        /// <returns></returns>
        public ActionResult ReCategoryIndex()
        {
            return View();
        }

        /// <summary>
        /// 流程模板分类表单(项目级)
        /// </summary>
        /// <returns></returns>
        public ActionResult ReCategoryForm()
        {
            return View();
        }

        /// <summary>
        /// 流程模板设计历史记录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult HistoryForm()
        {
            return View();
        }
        /// <summary>
        /// 预览流程模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult PreviewForm()
        {
            return View();
        }


        /// <summary>
        /// 节点信息设置
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult NodeForm()
        {
            return View();
        }
        #region 审核人员添加
        /// <summary>
        /// 添加岗位
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult PostForm()
        {
            return View();
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult RoleForm()
        {
            return View();
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult UserForm()
        {
            return View();
        }
        /// <summary>
        /// 添加上下级
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult LevelForm()
        {
            return View();
        }
        /// <summary>
        /// 添加某节点执行人
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AuditorNodeForm()
        {
            return View();
        }
        /// <summary>
        /// 添加表单字段
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AuditorFieldForm()
        {
            return View();
        }
        #endregion

        #region 表单添加
        /// <summary>
        /// 表单添加
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult WorkformForm()
        {
            return View();
        }
        #endregion

        #region 条件字段
        /// <summary>
        /// 条件字段添加
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ConditionFieldForm()
        {
            return View();
        }
        #endregion

        #region 按钮设置
        /// <summary>
        /// 表单添加
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ButtonForm()
        {
            return View();
        }
        #endregion


        /// <summary>
        /// 线段信息设置
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult LineForm()
        {
            return View();
        }


        /// <summary>
        /// 导入页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ImportForm()
        {
            return View();
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="queryJson">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetInfoPageList(string pagination, string queryJson)
        {
            try
            {
                Pagination paginationobj = pagination.ToObject<Pagination>();
                var data = nWFSchemeIBLL.GetInfoPageList(paginationobj, queryJson);
                var jsonData = new
                {
                    rows = data,
                    total = paginationobj.total,
                    page = paginationobj.page,
                    records = paginationobj.records,
                };
                return Success(jsonData);
            }
            catch (Exception ex)
            {

                return Fail(ex.Message);
            }

        }

        /// <summary>
        ///  获取流程分类树形数据
        /// </summary>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetCategoryTree(string ProjectId, string Type)
        {
            string PlantType = string.Empty;
            if (Type == "create")
            {
                if (!ProjectId.IsEmpty())
                {
                    PlantType = Util.Constant.ConstantBiz.PLANTTYPE_PROJECT;
                }
                else
                {
                    PlantType = Util.Constant.ConstantBiz.PLANTTYPE_UNIT;
                }
            }
            if (Request["plantType"] == Util.Constant.ConstantBiz.PLANTTYPE_UNIT)
            {
                PlantType = Util.Constant.ConstantBiz.PLANTTYPE_UNIT;
            }
            else if (Request["plantType"] == Util.Constant.ConstantBiz.PLANTTYPE_PROJECT)
            {
                PlantType = Util.Constant.ConstantBiz.PLANTTYPE_PROJECT;
            }
            var data = nWFSchemeIBLL.GetCategoryTree(ProjectId, PlantType);
            return Success(data);
        }

        /// <summary>
        /// 获取流程分类数据
        /// </summary>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetCategoryList(string queryJson)
        {
            var data = nWFSchemeIBLL.GetCategoryList(queryJson);
            return Success(data);
        }

        /// <summary>
        /// 获取流程分类实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetCategoryForm(string keyValue)
        {
            var data = nWFSchemeIBLL.GetCategoryForm(keyValue);
            var jsonData = new
            {
                flow_category = data,
            };
            return Success(jsonData);
        }

        /// <summary>
        /// 获取自定义流程列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetMyInfoList(string ProjectId, string keyword)
        {
            UserInfo userInfo = LoginUserInfo.Get();
            var data = (List<NWFSchemeInfoEntity>)nWFSchemeIBLL.GetInfoList(userInfo, ProjectId);
            if (!string.IsNullOrEmpty(keyword))
            {
                data = data.FindAll(t => t.F_Name.Contains(keyword));
            }
            return Success(data);
        }
        /// <summary>
        /// 获取流程模板数据
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetFormData(string keyValue)
        {
            NWFSchemeInfoEntity schemeInfoEntity = nWFSchemeIBLL.GetInfoEntity(keyValue);
            if (schemeInfoEntity == null)
            {
                return Success(new { });
            }

            NWFSchemeEntity schemeEntity = nWFSchemeIBLL.GetSchemeEntity(schemeInfoEntity.F_SchemeId);
            var nWFSchemeAuthList = nWFSchemeIBLL.GetAuthList(schemeInfoEntity.F_Id);
            var jsonData = new
            {
                info = schemeInfoEntity,
                scheme = schemeEntity,
                authList = nWFSchemeAuthList
            };
            return Success(jsonData);
        }

        /// <summary>
        /// 获取模板分页数据
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="schemeInfoId"></param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetSchemePageList(string pagination, string schemeInfoId)
        {
            Pagination paginationobj = pagination.ToObject<Pagination>();
            var data = nWFSchemeIBLL.GetSchemePageList(paginationobj, schemeInfoId);
            var jsonData = new
            {
                rows = data,
                total = paginationobj.total,
                page = paginationobj.page,
                records = paginationobj.records,
            };
            return Success(jsonData);
        }
        /// <summary>
        /// 获取流程模板数据
        /// </summary>
        /// <param name="schemeId">模板主键</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetScheme(string schemeId)
        {
            var data = nWFSchemeIBLL.GetSchemeEntity(schemeId);
            return Success(data);
        }

        /// <summary>
        /// 获取流程模板数据
        /// </summary>
        /// <param name="code">流程编码</param>
        /// <returns></returns>
        [HttpPost, ValidateInput(false)]
        public void ExportScheme(string code)
        {
            NWFSchemeInfoEntity schemeInfoEntity = nWFSchemeIBLL.GetInfoEntityByCode(code);
            if (schemeInfoEntity != null)
            {
                NWFSchemeEntity schemeEntity = nWFSchemeIBLL.GetSchemeEntity(schemeInfoEntity.F_SchemeId);
                var nWFSchemeAuthList = nWFSchemeIBLL.GetAuthList(schemeInfoEntity.F_Id);
                var jsonData = new
                {
                    info = schemeInfoEntity,
                    scheme = schemeEntity,
                    authList = nWFSchemeAuthList
                };

                string data = jsonData.ToJson();

                FileDownHelper.DownLoadString(data, schemeInfoEntity.F_Name + ".lrscheme");
            }
        }


        /// <summary>
        /// excel文件导入（通用模板）
        /// </summary>
        /// <param name="templateId">模板Id</param>
        /// <param name="fileId">文件主键</param>
        /// <param name="chunks">分片数</param>
        /// <param name="ext">文件扩展名</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ExecuteImportScheme(string templateId, string fileId, int chunks, string ext)
        {
            UserInfo userInfo = LoginUserInfo.Get();
            string path = annexesFileIBLL.SaveAnnexes(fileId, fileId + "." + ext, chunks, userInfo);
            if (!string.IsNullOrEmpty(path))
            {
                // 读取导入文件
                string data = DirFileHelper.ReadText(path);
                // 删除临时文件
                DirFileHelper.DeleteFile2(path);
                string commonKeyValue = "";
                if (!string.IsNullOrEmpty(data))
                {
                    NWFSchemeModel nWFSchemeModel = data.ToObject<NWFSchemeModel>();
                    // 验证流程编码是否重复
                    var schemeInfoEntityTmpList = (List<NWFSchemeInfoEntity>)nWFSchemeIBLL.GetInfoList();
                    if (schemeInfoEntityTmpList.Count > 0)
                    {
                        NWFSchemeInfoEntity schemeInfoEntityTmp = schemeInfoEntityTmpList.Find(s => s.F_Code == Str.ConvertPinYin(nWFSchemeModel.info.F_Name).ToUpper() && s.ProjectId == null);
                        if (schemeInfoEntityTmp != null)
                        {
                            commonKeyValue = schemeInfoEntityTmp.F_Id;
                        }
                    }
                    nWFSchemeModel.info.ProjectId = null;
                    nWFSchemeIBLL.SaveEntity(commonKeyValue, nWFSchemeModel.info, nWFSchemeModel.scheme, nWFSchemeModel.authList); 
                }
                return Success("导入成功");
            }
            else
            {
                return Fail("导入模板失败!");
            }
        }

        /// <summary>
        /// excel文件导入（项目平台）
        /// </summary>
        /// <param name="templateId">模板Id</param>
        /// <param name="fileId">文件主键</param>
        /// <param name="chunks">分片数</param>
        /// <param name="ext">文件扩展名</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ImportScheme(string templateId, string fileId, int chunks, string ext, string ProjectId)
        {
            UserInfo userInfo = LoginUserInfo.Get();
            string path = annexesFileIBLL.SaveAnnexes(fileId, fileId + "." + ext, chunks, userInfo);
            if (!string.IsNullOrEmpty(path))
            {
                // 读取导入文件
                string data = DirFileHelper.ReadText(path);
                // 删除临时文件
                DirFileHelper.DeleteFile2(path);
                string keyValue = "";
                if (!string.IsNullOrEmpty(data))
                {
                    NWFSchemeModel nWFSchemeModel = data.ToObject<NWFSchemeModel>();
                    // 验证流程编码是否重复
                    var schemeInfoEntityTmpList = (List<NWFSchemeInfoEntity>)nWFSchemeIBLL.GetInfoList();
                    if (schemeInfoEntityTmpList.Count > 0)
                    {
                        NWFSchemeInfoEntity schemeInfoEntityTmp = schemeInfoEntityTmpList.Find(s => s.F_Code == Str.ConvertPinYin(nWFSchemeModel.info.F_Name).ToUpper() && s.ProjectId == ProjectId);
                        if (schemeInfoEntityTmp != null)
                        {
                            keyValue = schemeInfoEntityTmp.F_Id;
                        }
                    }
                    nWFSchemeModel.info.ProjectId = ProjectId;
                    nWFSchemeIBLL.SaveEntity(keyValue, nWFSchemeModel.info, nWFSchemeModel.scheme, nWFSchemeModel.authList);
                }
                return Success("导入成功");
            }
            else
            {
                return Fail("导入模板失败!");
            }
        }
        /// <summary>
        /// 获取流程模板列表
        /// </summary>
        /// <param name="category">流程分类</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetNWFSchemeInfoList(string category)
        {
            var schemeInfoLsit = (List<NWFSchemeInfoEntity>)nWFSchemeIBLL.GetInfoList();
            var data = schemeInfoLsit.FindAll(s => s.F_Category == category && string.IsNullOrEmpty(s.ProjectId));
            return Success(data);
        }


        #endregion

        #region 提交数据

        /// <summary>
        /// 保存流程模板 通用
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="schemeInfo">表单设计模板信息</param>
        /// <param name="shcemeAuth">模板权限信息</param>
        /// <param name="scheme">模板内容</param>
        /// <param name="type">类型1.正式2.草稿</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult CommonSaveForm(string keyValue, string schemeInfo, string shcemeAuth, string scheme, int type)
        {

            NWFSchemeInfoEntity schemeInfoEntity = schemeInfo.ToObject<NWFSchemeInfoEntity>();
            List<NWFSchemeAuthEntity> nWFSchemeAuthList = shcemeAuth.ToObject<List<NWFSchemeAuthEntity>>();
            NWFSchemeEntity schemeEntity = new NWFSchemeEntity();
            schemeEntity.F_Content = scheme;
            schemeEntity.F_Type = type;
            schemeInfoEntity.F_Code = Guid.NewGuid().ToString();
            // 验证流程编码是否重复

            var schemeInfoEntityTmpList = (List<NWFSchemeInfoEntity>)nWFSchemeIBLL.GetInfoList();
            if (schemeInfoEntityTmpList.Count > 0 && string.IsNullOrEmpty(keyValue))
            {
                NWFSchemeInfoEntity schemeInfoEntityTmp = schemeInfoEntityTmpList.Find(s => s.F_Code == Str.ConvertPinYin(schemeInfoEntity.F_Name).ToUpper() && s.ProjectId == null);
                if (schemeInfoEntityTmp != null)
                {
                    return Fail("流程名称重复");
                }
            }
            nWFSchemeIBLL.SaveEntity(keyValue, schemeInfoEntity, schemeEntity, nWFSchemeAuthList);
            return Success("保存成功！");
        }



        /// <summary>
        /// 保存流程模板
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="schemeInfo">表单设计模板信息</param>
        /// <param name="shcemeAuth">模板权限信息</param>
        /// <param name="scheme">模板内容</param>
        /// <param name="type">类型1.正式2.草稿</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string keyValue, string schemeInfo, string shcemeAuth, string scheme, int type)
        {

            NWFSchemeInfoEntity schemeInfoEntity = schemeInfo.ToObject<NWFSchemeInfoEntity>();
            List<NWFSchemeAuthEntity> nWFSchemeAuthList = shcemeAuth.ToObject<List<NWFSchemeAuthEntity>>();
            NWFSchemeEntity schemeEntity = new NWFSchemeEntity();
            schemeEntity.F_Content = scheme;
            schemeEntity.F_Type = type;
            if (schemeInfoEntity.ProjectId == null)
            {
                return Fail("获取项目ID失败!");
            }
            if (!string.IsNullOrEmpty(keyValue))
            {
                schemeInfoEntity.ProjectId = null;
            }
            nWFSchemeIBLL.SaveEntity(keyValue, schemeInfoEntity, schemeEntity, nWFSchemeAuthList);
            return Success("保存成功！");
        }


        /// <summary>
        /// 保存流程分类
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="entity">流程分类实体</param>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult CategorySaveEntity(string keyValue, string strEntity)
        {

            try
            {
                NWFSchemeCategoryEntity entity = strEntity.ToObject<NWFSchemeCategoryEntity>();
                if (string.IsNullOrEmpty(keyValue))
                {
                    if (entity.ProjectId == null)
                    {
                        return Fail("获取项目ID失败!");
                    }
                    UserInfo us = LoginUserInfo.Get();
                    if (us == null)
                    {
                        return Fail("读取用户信息异常");
                    }
                    entity.CreateUserID = us.userId;
                    entity.CreateTime = Time.MySqlTime;

                }
                else
                {
                    entity.ProjectId = null;
                }
                nWFSchemeIBLL.CategorySaveEntity(keyValue, entity);
                return Success("保存成功！");
            }
            catch (Exception ex)
            {

                return Fail(ex.Message);
            }

        }

        /// <summary>
        /// 删除流程分类
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="entity">流程分类实体</param>
        [HttpPost]
        [AjaxOnly]
        public ActionResult CategoryDeleteEntity(string keyValue)
        {
            nWFSchemeIBLL.CategoryDeleteEntity(keyValue);
            return Success("删除成功！");
        }

        /// <summary>
        /// 更新模板数据
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult UpdateForm(string keyValue)
        {
            var schemeInfoEntityTmpList = (List<NWFSchemeInfoEntity>)nWFSchemeIBLL.GetInfoList();
            // 当前模板数据
            var currentSchemeInfo = schemeInfoEntityTmpList.Find(s => s.F_Id == keyValue);
            // 通用模板数据
            var commonSchemeInfo = schemeInfoEntityTmpList.Find(s => s.F_Code == currentSchemeInfo.F_Code && string.IsNullOrEmpty(s.ProjectId) == true);
            if (commonSchemeInfo != null)
            {
                if (currentSchemeInfo != null)
                {
                    var commonSchemeList = (List<NWFSchemeEntity>)nWFSchemeIBLL.GetNewSchemeEntityBySchemeInfoId(commonSchemeInfo.F_Id);
                    if (commonSchemeList != null && commonSchemeList.Count > 0)
                    {
                        NWFSchemeEntity newCommonSchemeInfo = commonSchemeList.OrderByDescending(o => o.F_CreateDate).FirstOrDefault();
                        nWFSchemeIBLL.SaveEntity(currentSchemeInfo, newCommonSchemeInfo);
                    }
                    else
                    {
                        return Fail("更新失败，未找到通用模板！");
                    }
                }
                return Success("更新成功！");
            }
            else
            {
                return Fail("更新失败，未找到通用模板！");

            }
        }


        /// <summary>
        /// 删除模板数据
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteForm(string keyValue)
        {
            nWFSchemeIBLL.DeleteEntity(keyValue);
            return Success("删除成功！");
        }

        /// <summary>
        /// 启用/停用表单
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="state">状态1启用0禁用</param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult UpDateSate(string keyValue, int state)
        {
            nWFSchemeIBLL.UpdateState(keyValue, state);
            return Success((state == 1 ? "启用" : "禁用") + "成功！");
        }
        /// <summary>
        /// 更新表单模板版本
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="state">状态1启用0禁用</param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult UpdateScheme(string schemeInfoId, string schemeId)
        {
            nWFSchemeIBLL.UpdateScheme(schemeInfoId, schemeId);
            return Success("更新成功！");
        }


        [HttpPost]
        [AjaxOnly]
        public ActionResult CopyScheme(string ProjectId)
        {
            if (!string.IsNullOrEmpty(ProjectId))
            {
                //复制流程
                nWFSchemeIBLL.CopyScheme(ProjectId);
            }
            return Success("保存成功！");
        }
        #endregion
    }
}