using DocumentFormat.OpenXml.EMMA;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.SqlSugar;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web.Mvc;

namespace Learun.Application.Web.Areas.ZZDT_EC.Controllers
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-01-30 15:57
    /// 描 述：图纸文件
    /// </summary>
    public class ec_drawing_fileController : MvcControllerBase
    {
        private ec_drawing_fileBLL ec_drawing_fileIBLL = new ec_drawing_fileBLL();

        #region 视图功能

        /// <summary>
        /// 主页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 表单页
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Form()
        {
            return View();
        }
        /// <summary>
        /// 选择页
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult SelectIndex()
        {
            return View();
        }
        /// <summary>
        /// 回收站
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult RecycleBin()
        {
            return View();
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 导出图纸的一些检查内容
        /// </summary>
        /// <returns></returns>
        public void ReportToExcel(string ProjectId, string dwgId)
        {
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("未在布置图上出现的位号");

            //创建第一行  并赋值
            IRow row = sheet.CreateRow(0);
            row.CreateCell(0).SetCellValue("对象类型");
            row.CreateCell(1).SetCellValue("位号");
            int rowIndex = 2;

            #region 项目的基本信息
            //项目的基本信息
            var projectEntity = new ec_projectBLL().GetList("{ProjectId:\"" + ProjectId + "\"}").FirstOrDefault();
            var dwgTbName = ProjectSugar.TableName<ec_drawing_fileEntity>(ProjectId);
            var pixelTbName = ProjectSugar.TableName<ec_enginedata_pixelEntity>(ProjectId);
            var listTbName = ProjectSugar.TableName<ec_dataitemEntity>(ProjectId);
            var detailTbName = ProjectSugar.TableName<ec_dataitemdetailEntity>(ProjectId);
            var tagTbName = ProjectSugar.TableName<ec_enginedataEntity>(ProjectId);

            var dwgType = SqlSugarHelper.Db.Queryable<ec_dataitemEntity>().AS(listTbName).First(x => x.DataItemCode == GlobalObject.enumlist_DrawingType);
            var dwgTypes = SqlSugarHelper.Db.Queryable<ec_dataitemdetailEntity>().AS(detailTbName).
                Where(x => x.DataItemID == dwgType.DataItemID).ToList();

            var layoutDetail = dwgTypes.FirstOrDefault(x => x.DataItemName == GlobalObject.drawingType_Layout);

            var allDwgs = SqlSugarHelper.Db.Queryable<ec_drawing_fileEntity>().AS(dwgTbName).ToList();
            var allLayoutDwgs = allDwgs.Where(x => x.DrawingType == layoutDetail.DataItemDetailID).Select(x => x.DrawingFileID).
                Distinct().ToList();
            var allPixels = SqlSugarHelper.Db.Queryable<ec_enginedata_pixelEntity>().AS(pixelTbName).ToList();
            var pixelsOnDwg = allPixels.Where(x => x.DrawingFileID == dwgId).ToList();

            var TagIds = pixelsOnDwg.Select(x => x.EngineDataID).Distinct().ToList();

            //这些id是否再另外的图纸上
            var PixelOnOtherDwg = allPixels.Where(x => TagIds.Contains(x.EngineDataID)
            && x.DrawingFileID != dwgId
            && allLayoutDwgs.Contains(x.DrawingFileID)
            && x.DeleteFlg != 1).ToList();


            var tagIdsOccurOnLayout = PixelOnOtherDwg.Select(x => x.EngineDataID).Distinct().ToList();

            var allTag = SqlSugarHelper.Db.Queryable<ec_enginedataEntity>().AS(tagTbName).ToList();
            var ERROR_Tag = TagIds.Where(x => !tagIdsOccurOnLayout.Contains(x)).ToList();

            int rowIdx = 1;
            foreach (var tagId in ERROR_Tag)
            {
                var tag = allTag.FirstOrDefault(x => x.EngineDataID == tagId);
                row = sheet.CreateRow(rowIdx);
                row.CreateCell(0).SetCellValue(tag.ObjectTypeID);
                row.CreateCell(1).SetCellValue(tag.TagNumber);
                rowIdx++;
            }
            #endregion



            string filename = "系统图图纸检查_" + DateTime.Now.ToString("yyMMddHHmmss");
            ExcelHelper.DownloadIWorkbook(workbook, filename);
        }
        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetList(string queryJson)
        {
            var data = ec_drawing_fileIBLL.GetList(queryJson);
            return Success(data);
        }
        /// <summary>
        /// 获取列表分页数据
        /// <param name="pagination">分页参数</param>
        /// <param name="engineDataID">工程数据ID</param>
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPageList(string pagination, string queryJson, string engineDataID = "")
        {
            Pagination paginationobj = pagination.ToObject<Pagination>();
            var data = ec_drawing_fileIBLL.GetList(queryJson, engineDataID, paginationobj);
            var jsonData = new
            {
                rows = data,
                total = paginationobj.total,
                page = paginationobj.page,
                records = paginationobj.records
            };
            return Success(jsonData);
        }
        /// <summary>
        /// 获取表单数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetFormData(string keyValue, string ProjectId)
        {
            var data = ec_drawing_fileIBLL.GetEntity(keyValue, ProjectId);
            var jsonData = new
            {
                ec_drawing_file = data
            };
            return Success(jsonData);
        }
        /// <summary>
        /// 获取图纸目录文件树形数据。
        /// 场合：比如电缆清册、设备清册输出时的选择。
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetTreeData(string ProjectId, bool isShowCheck)
        {


            var tableName = ProjectSugar.TableName<ec_drawing_fileEntity>(ProjectId);
            var catalogueTableName = ProjectSugar.TableName<ec_drawing_catalogueEntity>(ProjectId);
            var pixelTableName = ProjectSugar.TableName<ec_enginedata_pixelEntity>(ProjectId);
            var list = SqlSugarHelper.Db.Queryable<ec_drawing_catalogueEntity>().AS(catalogueTableName).Where(x => x.DrawingCatalogueName != "材料表").ToList();

            var DrawingCatalogueIDs = list.Select(x => x.DrawingCatalogueID).ToList();
            var files = SqlSugarHelper.Db.Queryable<ec_drawing_fileEntity>().AS(tableName)
                .Where(x => DrawingCatalogueIDs.Contains(x.DrawingCatalogueID)).ToList();
            files = files.Where(x => x.IsDelete != 1).ToList();//排除删掉的
            files = files.Where(x => x.IsEngineDWG != null).Where(X => X.IsEngineDWG == 1).ToList();//排除非工程图纸
            //要适当过滤出一些无效图纸 25 04 09
            //比如图上没句柄的
            var DWGPixels = SqlSugarHelper.Db.Queryable<ec_enginedata_pixelEntity>().AS(pixelTableName).
                InnerJoin<ec_enginedataEntity>((x, y) => x.EngineDataID == y.EngineDataID).AS<ec_enginedataEntity>(ProjectSugar.TableName<ec_enginedataEntity>(ProjectId)).
                InnerJoin<ec_objecttypeEntity>((x, y, z) => y.ObjectTypeID == z.ObjectTypeID).AS<ec_objecttypeEntity>(ProjectSugar.TableName<ec_objecttypeEntity>(ProjectId)).
                Where((x, y, z) => x.DeleteFlg != 1 &&
                    files.Select(yy => yy.DrawingFileID).Contains(x.DrawingFileID) &&
                    !z.FullPathCN.EndsWith("电缆") &&
                    !z.FullPathCN.EndsWith("图框") &&
                    !z.FullPathCN.EndsWith("基点")).
                Select((x, y, z) => new { x.DrawingFileID, x.PixelCode, y.EngineDataID, z.FullPathCN }).ToList();
            //排除掉图框 基点一类的无效句柄
            var dwghavingPixels = DWGPixels.Select(x => x.DrawingFileID).Distinct().ToList();
            var invalidDwgs = files.Where(x => !dwghavingPixels.Contains(x.DrawingFileID)).ToList();

            //比如没有
            List<TreeModel> treeList = new List<TreeModel>();


            foreach (var item in list)
            {
                TreeModel node = new TreeModel();
                node.id = item.DrawingCatalogueID;
                node.text = item.DrawingCatalogueName;
                node.value = item.DrawingCatalogueID;
                node.showcheck = isShowCheck;
                node.checkstate = 0;
                node.isexpand = false;
                node.parentId = item.UpDrawingCatalogueID;
                node.NodeExtData = item;
                treeList.Add(node);
            }

            treeList.Add(new TreeModel
            {
                id = "☆图面暂无内容☆",
                text = "☆图面暂无内容☆",
                value = "☆图面暂无内容☆",
                showcheck = isShowCheck,
                checkstate = 0,
                isexpand = false,
                parentId = ""
            });
            foreach (var item in files)
            {
                if (invalidDwgs.Any(x => x.DrawingFileID == item.DrawingFileID))
                {
                    item.DrawingFileName = "【☆图面暂无内容☆】" + item.DrawingFileName;
                    item.DrawingCatalogueID = "☆图面暂无内容☆";
                }
                TreeModel node = new TreeModel();
                node.id = item.DrawingFileID;
                node.text = item.DrawingFileName;
                node.value = item.DrawingFileID;
                node.showcheck = isShowCheck;
                node.checkstate = 0;
                node.isexpand = false;
                node.parentId = item.DrawingCatalogueID;
                node.NodeExtData = item;
                treeList.Add(node);
            }
            return Success(treeList.ToTree());
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 彻底删除图纸
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteForm(string keyValue, string ProjectId, bool deleteTags)
        {
            ec_drawing_fileIBLL.DeleteEntity(keyValue, ProjectId);
            return Success("删除成功！");
        }
        /// <summary>
        /// 逻辑删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult LogicDelete(string keyValue, string ProjectId)
        {
            ec_drawing_fileIBLL.LogicDelete(keyValue, ProjectId);
            return Success("删除成功！");
        }

        /// <summary>
        /// 还原逻辑删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult RepeatLogicDelete(string keyValue, string ProjectId)
        {
            ec_drawing_fileIBLL.RepeatLogicDelete(keyValue, ProjectId);
            return Success("还原成功！");
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string keyValue, string strEntity, string ProjectId)
        {
            ec_drawing_fileEntity entity = strEntity.ToObject<ec_drawing_fileEntity>();
            //同一目录下不允许有名称相同的图纸文件
            var data = ec_drawing_fileIBLL.GetList("{DrawingCatalogueID:\"" + entity.DrawingCatalogueID + "\",ProjectId:\"" + ProjectId + "\",DrawingFileNameFull:\"" + entity.DrawingFileName + "\"}").ToList();
            if (data != null && data.Count > 0)
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    if (data.Find(x => x.DrawingFileID != keyValue) != null)
                    {
                        return Fail("同一目录下不允许有名称相同的图纸文件！");
                    }
                }
                else
                {
                    return Fail("同一目录下不允许有名称相同的图纸文件！");
                }
            }
            ec_drawing_fileEntity entityOld = new ec_drawing_fileEntity();
            if (!string.IsNullOrEmpty(keyValue))
            {
                entityOld = ec_drawing_fileIBLL.GetEntity(keyValue, ProjectId);
                //entity.IsPublish = entityOld.IsPublish;
                //entity.IsCheckOut = entityOld.IsCheckOut;
                //entity.CheckOutUserID = entityOld.CheckOutUserID;
                //entity.CheckOutTime = entityOld.CheckOutTime;
                //entity.CreateTime= entityOld.CreateTime;
                //entity.CreateUserID= entityOld.CreateUserID;
                //entity.DrawingFileID = entityOld.DrawingFileID;



                entityOld.DrawingFileName = entity.DrawingFileName;
                entityOld.DrawingType = entity.DrawingType;
                //entityOld.DrawingStage = entity.DrawingStage; 版次关系不能直接改
                entityOld.DrawingSystem = entity.DrawingSystem;
                entityOld.MaterialCensus = entity.MaterialCensus;
                entityOld.MaterialRange = entity.MaterialRange;
                entityOld.FileVersion = entity.FileVersion;
                entityOld.OrderID = entity.OrderID;
                entityOld.IsEngineDWG = entity.IsEngineDWG;
                //entityOld.FileMD5 = entity.FileMD5;
                entityOld.Describe1 = entity.Describe1;
                entityOld.Describe2 = entity.Describe2;
                entityOld.Describe3 = entity.Describe3;
            }
            ec_drawing_fileIBLL.SaveEntity(keyValue, entityOld, ProjectId);
            return Success("保存成功！");
        }

        /// <summary>
        /// 释放图纸文件
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult FreeDrawingFile(string keyValue, string ProjectId)
        {
            ec_drawing_fileIBLL.FreeDrawingFile(keyValue, ProjectId);
            return Success("释放成功！");
        }

        /// <summary>
        /// 图纸导入  类似于复制的功能
        /// <param name="DrawingCatalogueID">当前项目里的图纸目录ID，用于保存导入后的图纸</param>
        /// <param name="strEntity">包含DrawingFileID和ProjectId（source Project）</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult ImportDrawing(string drawingCatalogueID, string ProjectId, string strEntity)
        {
            string msg = ec_drawing_fileIBLL.ImportDrawing(drawingCatalogueID, ProjectId, strEntity);
            if (string.IsNullOrEmpty(msg))
            {
                return Success("导入成功！");
            }
            else
            {
                return Fail(msg);
            }
        }

        #endregion

    }
}
