using Learun.Application.Base.AuthorizeModule;
using Learun.Application.Organization;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.Operat;
using Learun.Util.SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Web.Http.Results;
using System.Web.Mvc;
using ec_projectEntity = Learun.Application.TwoDevelopment.ZZDT_EC.ec_projectEntity;

namespace Learun.Application.Web.Areas.ZZDT_EC.Controllers
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2020-12-04 15:20
    /// 描 述：项目管理
    /// </summary>
    public class ec_projectController : MvcControllerBase
    {
        private ec_projectIBLL ec_projectIBLL = new ec_projectBLL();

        #region 视图功能

        /// <summary>
        /// 主页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 项目切换页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ProjectListIndex()
        {
            return View();
        }

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

        /// <summary>
        /// 项目选择界面
        /// </summary>
        /// <returns></returns>
        public ActionResult SelectProjectForm()
        {
            return View();
        }

        #endregion

        #region 获取数据

        /// <summary>
        /// 显示项目列表数据（网页端）
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPageList(string pagination, string queryJson)
        {
            Pagination paginationobj = pagination.ToObject<Pagination>();
            var data = ec_projectIBLL.GetList(queryJson, paginationobj);
            var jsonData = new
            {
                rows = data,
                total = paginationobj.total,
                page = paginationobj.page,
                records = paginationobj.records
            };
            return Success(jsonData);
        }

        /// <summary>
        /// 获取项目选择页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetProjectSelectPageList(string pagination, string queryJson)
        {
            Pagination paginationobj = pagination.ToObject<Pagination>();
            var data = ec_projectIBLL.GetListUnderUser(paginationobj, queryJson);
            var jsonData = new
            {
                rows = data,
                total = paginationobj.total,
                page = paginationobj.page,
                records = paginationobj.records
            };
            return Success(jsonData);
        }

        /// <summary>
        /// 获取项目下拉框
        /// </summary>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        public ActionResult GetProjectSelectList(string queryJson)
        {
            Pagination paginationobj = new Pagination();
            paginationobj.page = 1;
            paginationobj.rows = 10000;
            paginationobj.sidx = "CreateTime";
            paginationobj.sord = "DESC";
            var data = ec_projectIBLL.GetList("{}", null);
            return Success(data);
        }

        /// <summary>
        /// 根据id获取项目数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetProjectById(string ProjectId)
        {
            var ec_projectData = ec_projectIBLL.GetEntity(ProjectId);
            var jsonData = new
            {
                ec_project = ec_projectData,
            };
            return Success(jsonData);
        }

        /// <summary>
        /// 获取表单数据。（网页端编辑项目）
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetFormData(string keyValue)
        {
            var ec_projectData = ec_projectIBLL.GetEntity(keyValue);
            var jsonData = new
            {
                ec_project = ec_projectData,
            };
            return Success(jsonData);
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteForm(string keyValue, string projectIndex)
        {
            ec_projectIBLL.DeleteEntity(keyValue, Convert.ToInt32(projectIndex));
            return Success("删除成功！", "项目列表", OperationType.Delete, null, null);
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string keyValue, string sourceProjId, string strEntity)
        {
            ec_projectEntity entity = strEntity.ToObject<ec_projectEntity>();
            //新建、编辑项目时，项目名称、项目编号不允许重复。
            var data = ec_projectIBLL.GetList("{}").ToList();

            data = data.FindAll(x => x.ProjectName == entity.ProjectName || x.ProjectCode == entity.ProjectCode);
            if (data != null && data.Count > 0)
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    data = data.FindAll(x => x.ProjectId != keyValue);
                    if (data != null && data.Count > 0)
                    {
                        return Fail("项目名称或项目编号重复！");
                    }
                }
                else
                {
                    return Fail("项目名称或项目编号重复！");
                }
            }
            ec_projectIBLL.SaveEntity(keyValue, entity);
            if (string.IsNullOrEmpty(keyValue))
            {
                entity = ec_projectIBLL.GetEntity(entity.ProjectId);
                //复制角色
                CopyRole(entity.ProjectId);

                var sourceProj = ec_projectIBLL.GetEntity(sourceProjId);
                //从业务表中获取数据，复制表结构
                var listBusinessTable = new ec_business_tableBLL().GetList("{}").ToList();
                List<string> TableCodes = listBusinessTable.Select(x => x.BusinessTableCode).Distinct().ToList();

                if (sourceProj == null)
                {

                    if (listBusinessTable != null && listBusinessTable.Count > 0)
                    {
                        //新建项目时需要复制“是否复制数据”为1的表数据（指的是从公司级 -> 项目级）
                        List<string> CopyTableData = listBusinessTable.FindAll(x => x.IsCopyData == 1).Select(x => x.BusinessTableCode).Distinct().ToList();
                        ec_projectIBLL.SynDataToProject(TableCodes, Convert.ToInt16(entity.ProjectIndex), CopyTableData);
                        #region 牵涉到文件的，要把annexe也复制一份，同时folderID也要换 

                        ec_projectIBLL.SaveDataAndAnnexes(entity.ProjectId);//创建项目

                        #endregion
                    }
                }
                else
                {
                    //基于一个现有项目
                    if (listBusinessTable != null && listBusinessTable.Count > 0)
                    {
                        ec_projectIBLL.SynDataSynDataToProjectToProject(TableCodes, sourceProj.ProjectIndex, entity.ProjectIndex);
                    }

                    #region 牵涉到文件的，要把annexe也复制一份，同时folderID也要换 
                    ec_projectIBLL.SaveDataAndAnnexes(entity.ProjectId);//创建项目，从某个现有项目

                    #endregion

                    #region 再处理一些状态相关的
                    //比如图纸都重置为第一个阶段，检入的状态
                    var dwgTbName = ProjectSugar.TableName<ec_drawing_fileEntity>(entity.ProjectId); 

                    var dataItemTb = ProjectSugar.TableName<ec_dataitemEntity>(entity.ProjectId);
                    var dataItemDetailTb = ProjectSugar.TableName<ec_dataitemdetailEntity>(entity.ProjectId);
                    var stage = SqlSugarHelper.Db.Queryable<ec_dataitemEntity>().AS(dataItemTb).First(x => x.DataItemCode == GlobalObject.enumlist_DrawingStage);
                    if (stage != null)
                    {
                        var dwgStages = SqlSugarHelper.Db.Queryable<ec_dataitemdetailEntity>().AS(dataItemDetailTb).Where(x => x.DataItemID == stage.DataItemID).OrderBy(X => X.OrderID).ToList();
                        var res2 = SqlSugarHelper.Db.Updateable<ec_drawing_fileEntity>().AS(dwgTbName).SetColumns(X => X.DrawingStage == dwgStages.FirstOrDefault().DataItemDetailID).Where(x=>x.IsEngineDWG ==1 ).
                        ExecuteCommand();
                    }

                    var res = SqlSugarHelper.Db.Updateable<ec_drawing_fileEntity>().AS(dwgTbName).SetColumns(X => X.IsCheckOut == 0).
                        Where(X => X.IsCheckOut != 0).ExecuteCommand();

                    //比如信号状态都设置为“新建”
                    #endregion
                }
            }
            return Success("保存成功！", "项目列表", string.IsNullOrEmpty(keyValue) ? OperationType.Create : OperationType.Update, null, null);
        }

        /// <summary>
        /// 同步数据，从单位平台同步对数据到项目表中。仅限选中的表
        /// <param name="projectCode">项目编号</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult SynData(string ProjectIndex, string strData, string ProjectId)
        {
            //判断是否有工程数据
            var TB = ProjectSugar.TableName<ec_enginedataEntity>(ProjectIndex);
            int countenginedata = SqlSugarHelper.Db.Queryable<ec_enginedataEntity>().AS(TB).Count();
            if (countenginedata > 0)
            {
                return Fail("该项目已经存在设计工程数据和位号，不允许同步数据！");
            }
            //页面上勾选的需要同步的表编号
            List<string> listTableCode = strData.ToList<string>();
            //同步关联表数据
            var synrelTable = new ec_synrel_tableBLL().GetList("{}").ToList();
            //需要同步表编号
            List<string> synTableCodes = new List<string>();
            foreach (var item in listTableCode)
            {
                var allDataByCode = synrelTable.FindAll(x => x.MainBusinessTableCode == item).Select(x => x.RelBusinessTableCode);
                synTableCodes.AddRange(allDataByCode);//关联表 
            }
            //最后需要同步数据的表编号集合
            var copyTables = listTableCode.Union(synTableCodes).Distinct().ToList(); //2个集合 取 并集
            ec_projectIBLL.SynDataToProject(copyTables, Convert.ToInt32(ProjectIndex), copyTables);

            ec_projectIBLL.SaveDataAndAnnexes(ProjectId);//手动同步数据

            return Success("同步成功！");
        }

        #endregion

        /// <summary>
        /// 复制角色
        /// </summary>
        /// <param name="ProjectId">项目ID</param>
        private void CopyRole(string ProjectId)
        {
            RoleBLL roleBLL = new RoleBLL();
            UserRelationIBLL userRelationIBLL = new UserRelationBLL();

            List<RoleEntity> projRoleList = roleBLL.GetList(ProjectId);
            if (projRoleList == null || projRoleList.Count == 0)
            {
                UserInfo userInfo = LoginUserInfo.Get();
                List<RoleEntity> commonRoleList = roleBLL.GetList("00000000-0000-0000-0000-000000000001");//单位通用的项目角色
                foreach (RoleEntity roleEntity in commonRoleList)
                {
                    IEnumerable<UserRelationEntity> commonUserRelationEntity = userRelationIBLL.GetUserIdList(roleEntity.F_RoleId, "00000000-0000-0000-0000-000000000001");
                    //拷贝授权
                    var auths = SqlSugarHelper.Db.Queryable<AuthorizeEntity>().Where(x => x.F_ObjectId == roleEntity.F_RoleId).ToList();

                    RoleEntity newRoleEntity = roleEntity;
                    newRoleEntity.ProjectId = ProjectId;
                    roleBLL.SaveEntity("", ref newRoleEntity);

                    foreach (UserRelationEntity userRelationEntity in commonUserRelationEntity)
                    {
                        UserRelationEntity newUserRelationEntity = userRelationEntity;
                        newUserRelationEntity.F_ObjectId = newRoleEntity.F_RoleId;
                        newUserRelationEntity.ProjectId = ProjectId;
                        userRelationIBLL.SaveEntity("", newUserRelationEntity);
                    }

                    auths.ForEach(x =>
                    {
                        x.Create();
                        x.F_ObjectId = newRoleEntity.F_RoleId;
                    });
                    SqlSugarHelper.Db.Insertable(auths).ExecuteCommand();
                }
            }
        }


    }
}
