using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.ExtendedProperties;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using Learun.Application.Base.SystemModule;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.SqlSugar;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OfficeOpenXml;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Engineering;
using Pipelines.Sockets.Unofficial.Arenas;
using Quartz.Util;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Helpers;
using System.Web.Mvc;
using static Learun.Application.TwoDevelopment.ZZDT_EC.ec_enginedata_pixelService;
using SystemIO = System.IO;

namespace Learun.Application.Web.Areas.ZZDT_EC.Controllers
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-06-15 10:00
    /// 描 述：报表文件
    /// </summary>
    public class ec_report_fileController : MvcControllerBase
    {
        private ec_report_fileIBLL ec_report_fileIBLL = new ec_report_fileBLL();
        Repository<ec_drawing_synEntity> _drawingSynRepository => new Repository<ec_drawing_synEntity>();

        #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 ParamSelect()
        {
            return View();
        }
        /// <summary>
        /// 电缆清单 参数选择页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult SystemSelect()
        {
            return View();
        }
        /// <summary>
        /// 信号清单 参数选择页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult SignalParamSelect()
        {
            return View();
        }
        /// <summary>
        /// 云线备注清单 参数选择页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CloudListParamSelect()
        {
            return View();
        }


        /// <summary>
        /// 设备清册 图纸范围选择 页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult SelectDrawings()
        {
            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_report_fileIBLL.GetList(queryJson, paginationobj);
            var jsonData = new
            {
                rows = data,
                total = paginationobj.total,
                page = paginationobj.page,
                records = paginationobj.records
            };
            return Success(jsonData);
        }

        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetList(string queryJson)
        {
            var data = ec_report_fileIBLL.GetList(queryJson);
            return Success(data);
        }

        /// <summary>
        /// 获取表单数据
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetFormData(string ProjectId, string keyValue)
        {
            var ec_report_fileData = ec_report_fileIBLL.GetEntity(ProjectId, keyValue);
            var jsonData = new
            {
                ec_report_file = ec_report_fileData,
            };
            return Success(jsonData);
        }

        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteForm(string ProjectId, string keyValue)
        {
            ec_report_fileIBLL.DeleteEntity(ProjectId, keyValue);
            return Success("删除成功！");
        }
        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string ProjectId, string keyValue, string strEntity)
        {
            ec_report_fileEntity entity = strEntity.ToObject<ec_report_fileEntity>();
            //同一目录下不允许有名称相同的报表文件
            var data = ec_report_fileIBLL.GetList("{ReportCatalogueID:\"" + entity.ReportCatalogueID + "\",ProjectId:\"" + ProjectId + "\",ReportFileNameFull:\"" + entity.ReportFileName + "\"}").ToList();
            if (data != null && data.Count > 0)
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    if (data.Find(x => x.ReportFileID != keyValue) != null)
                    {
                        return Fail("同一目录下不允许有名称相同的报表文件！");
                    }
                }
                else
                {
                    return Fail("同一目录下不允许有名称相同的报表文件！");
                }
            }
            ec_report_fileIBLL.SaveEntity(ProjectId, keyValue, entity);
            return Success("保存成功！");
        }
        #endregion

        #region 生成报表
        enum CableTypeEnum
        {
            动力 = 0, 信号 = 1, CAT6 = 2
        }

        /// <summary>
        /// 生成报表
        /// </summary>
        /// <param name="ProjectId">项目ID</param>
        /// <param name="folderId">文件夹ID</param>
        /// <param name="reportFileName">报表文件名称</param>
        /// <param name="objectTypeIDs">对象类型ID集合</param>
        /// <param name="propertyIDs">属性ID集合</param>
        /// <param name="relTypeIDs">关联类型ID集合</param>
        public void ExportToExcel(string ProjectId, string folderId, string reportFileName, string objectTypeIDs, string propertyIDs, string relTypeIDs)
        {

            string filePath = "";
            var annexesFile = new AnnexesFileBLL().GetList(folderId).FirstOrDefault();
            filePath = annexesFile?.F_FilePath;
            if (!string.IsNullOrEmpty(filePath))
            {
                FileInfo fileinfo = new SystemIO.FileInfo(filePath);
                if (fileinfo.Exists)
                {
                    IWorkbook workbook;
                    using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        if (annexesFile.F_FileExtensions == ".xls")
                        {
                            workbook = new HSSFWorkbook(fileStream);
                        }
                        else
                        {
                            workbook = new XSSFWorkbook(fileStream);
                        }
                    }

                    #region common
                    ISheet sheet = workbook.CreateSheet("工程数据");

                    //创建第一行  并赋值
                    IRow row = sheet.CreateRow(0);
                    row.CreateCell(0).SetCellValue("对象类型");
                    row.CreateCell(1).SetCellValue("位号");
                    int rowIndex = 2;
                    //获取要导出的属性数据
                    var exportPropData = new ec_propertyBLL().GetList("{PropertyIDs:\"" + propertyIDs + "\",ProjectId:\"" + ProjectId + "\"}");
                    foreach (var prop in exportPropData)
                    {
                        row.CreateCell(rowIndex).SetCellValue(prop.PropertyName);
                        rowIndex++;
                    }
                    //获取要导出的对象类型数据
                    List<string> listObjectTypeID = objectTypeIDs.Split(',').ToList();
                    //获取当前对象类型对应的工程数据
                    var engineDataAll = new ec_enginedataBLL().GetList("{ProjectId:\"" + ProjectId + "\",ObjectTypeIDs:\"" + objectTypeIDs + "\"}").ToList();
                    //获取当前工程数据属性
                    List<string> listEngineDataID = engineDataAll.Select(x => x.EngineDataID).ToList();
                    string engineDataIDs = string.Join(",", (from tb in listEngineDataID select tb).ToList());
                    var engineDataPropAll = new ec_enginedata_propertyBLL().GetEnginePropById(ProjectId, engineDataIDs).ToList();
                    rowIndex = 1;
                    foreach (var item in listObjectTypeID)
                    {
                        //获取当前对象类型对应的工程数据
                        var engineData = engineDataAll.FindAll(x => x.ObjectTypeID == item).ToList();
                        foreach (var itemEngineData in engineData)
                        {
                            //获取当前工程数据属性
                            var engineDataProp = engineDataPropAll.FindAll(x => x.EngineDataID == itemEngineData.EngineDataID).ToList();
                            IRow rowdata = sheet.CreateRow(rowIndex);
                            for (int k = 0; k < row.LastCellNum; k++)
                            {
                                //获取每个单元格
                                if (k == 0)
                                {
                                    rowdata.CreateCell(0).SetCellValue(itemEngineData.FullPathCN);
                                }
                                else if (k == 1)
                                {
                                    rowdata.CreateCell(1).SetCellValue(itemEngineData.TagNumber);
                                }
                                else
                                {
                                    rowdata.CreateCell(k).SetCellValue(engineDataProp.Find(x => x.PropertyName == row.GetCell(k).ToString())?.PropertyValue);
                                }
                            }
                            rowIndex++;
                        }
                    }
                    ExcelHelper.AutoColumnWidth(sheet, row.LastCellNum.ToInt());
                    #region 项目的基本信息
                    //项目的基本信息
                    var projectEntity = new ec_projectBLL().GetList("{ProjectId:\"" + ProjectId + "\"}").FirstOrDefault();
                    ISheet sheet1 = workbook.CreateSheet("项目信息");
                    //创建第一行  并赋值
                    IRow row1 = sheet1.CreateRow(0);
                    row1.CreateCell(0).SetCellValue("项目名称");
                    row1.CreateCell(1).SetCellValue(projectEntity.ProjectName);
                    IRow row2 = sheet1.CreateRow(1);
                    row2.CreateCell(0).SetCellValue("项目代号");
                    row2.CreateCell(1).SetCellValue(projectEntity.ProjectCode);
                    IRow row3 = sheet1.CreateRow(2);
                    row3.CreateCell(0).SetCellValue("船名（中文）");
                    row3.CreateCell(1).SetCellValue(projectEntity.ShipNameCN);
                    IRow row4 = sheet1.CreateRow(3);
                    row4.CreateCell(0).SetCellValue("船名（英文）");
                    row4.CreateCell(1).SetCellValue(projectEntity.ShipNameEN);
                    IRow row5 = sheet1.CreateRow(4);
                    row5.CreateCell(0).SetCellValue("船型（中文）");
                    row5.CreateCell(1).SetCellValue(projectEntity.ShipTypeCNName);
                    IRow row6 = sheet1.CreateRow(5);
                    row6.CreateCell(0).SetCellValue("船型（英文）");
                    row6.CreateCell(1).SetCellValue(projectEntity.ShipTypeENName);
                    IRow row7 = sheet1.CreateRow(6);
                    row7.CreateCell(0).SetCellValue("船级社");
                    row7.CreateCell(1).SetCellValue(projectEntity.ShipSocietyName);
                    IRow row8 = sheet1.CreateRow(7);
                    row8.CreateCell(0).SetCellValue("船东");
                    row8.CreateCell(1).SetCellValue(projectEntity.ShipOwner);
                    IRow row9 = sheet1.CreateRow(8);
                    row9.CreateCell(0).SetCellValue("挂旗国（船籍国）");
                    row9.CreateCell(1).SetCellValue(projectEntity.FlagStateName);
                    IRow row10 = sheet1.CreateRow(9);
                    row10.CreateCell(0).SetCellValue("IMO编号");
                    row10.CreateCell(1).SetCellValue(projectEntity.IMONumber);
                    IRow row11 = sheet1.CreateRow(10);
                    row11.CreateCell(0).SetCellValue("项目更多描述一");
                    row11.CreateCell(1).SetCellValue(projectEntity.Describe1);
                    IRow row12 = sheet1.CreateRow(11);
                    row12.CreateCell(0).SetCellValue("项目更多描述二");
                    row12.CreateCell(1).SetCellValue(projectEntity.Describe2);
                    IRow row13 = sheet1.CreateRow(12);
                    row13.CreateCell(0).SetCellValue("项目更多描述三");
                    row13.CreateCell(1).SetCellValue(projectEntity.Describe3);
                    IRow row14 = sheet1.CreateRow(13);
                    row14.CreateCell(0).SetCellValue("创建人");
                    row14.CreateCell(1).SetCellValue(projectEntity.CreateUserName);
                    ExcelHelper.AutoColumnWidth(sheet1, row1.LastCellNum.ToInt());
                    IRow row15 = sheet1.CreateRow(14);
                    row15.CreateCell(0).SetCellValue("创建时间");
                    row15.CreateCell(1).SetCellValue(Convert.ToDateTime(projectEntity.CreateTime).ToString("yyyy-MM-dd HH:mm"));
                    ExcelHelper.AutoColumnWidth(sheet1, row1.LastCellNum.ToInt());
                    #endregion

                    #region 关联关系
                    //关联关系
                    ISheet sheet2 = workbook.CreateSheet("关联关系");
                    //创建第一行  并赋值
                    IRow row2_1 = sheet2.CreateRow(0);
                    row2_1.CreateCell(0).SetCellValue("位号");
                    row2_1.CreateCell(1).SetCellValue("关联数据类型");
                    row2_1.CreateCell(2).SetCellValue("关联工程数据");
                    rowIndex = 1;
                    if (!string.IsNullOrEmpty(relTypeIDs))
                    {
                        //获取工程数据关联数据
                        var engineDataRelAll = new ec_enginedata_relBLL().GetList("{ProjectId:\"" + ProjectId + "\",RelTypeIDs:\"" + relTypeIDs + "\"}").ToList();
                        if (engineDataRelAll != null && engineDataRelAll.Count > 0)
                        {
                            foreach (var item in engineDataAll)
                            {
                                var engineDataRel = engineDataRelAll.FindAll(x => x.RelEngineData1ID == item.EngineDataID || x.RelEngineData2ID == item.EngineDataID).ToList();
                                foreach (var reldata in engineDataRel)
                                {
                                    IRow row2_2 = sheet2.CreateRow(rowIndex);
                                    row2_2.CreateCell(0).SetCellValue(item.TagNumber);
                                    row2_2.CreateCell(1).SetCellValue(reldata.RelTypeName);
                                    if (reldata.RelEngineData1ID == item.EngineDataID)
                                    {
                                        row2_2.CreateCell(2).SetCellValue(reldata.TagNumber2);
                                    }
                                    else
                                    {
                                        row2_2.CreateCell(2).SetCellValue(reldata.TagNumber1);
                                    }
                                    rowIndex++;
                                }
                            }
                        }
                    }
                    ExcelHelper.AutoColumnWidth(sheet2, row2_1.LastCellNum.ToInt());
                    #endregion
                    if (workbook.NumberOfSheets > 2)
                    {//隐藏指定sheet页 如果不止一个sheet页的话
                        workbook.SetSheetHidden(workbook.GetSheetIndex("工程数据"), 1);
                        workbook.SetSheetHidden(workbook.GetSheetIndex("项目信息"), 1);
                        workbook.SetSheetHidden(workbook.GetSheetIndex("关联关系"), 1);
                    }

                    #endregion


                    string filename = reportFileName + DateTime.Now.ToString("yyMMddHHmmss");
                    ExcelHelper.DownloadIWorkbook(workbook, filename, annexesFile.F_FileExtensions);
                }
            }
        }

        /// <summary>
        /// 判断一个位号是否属于某一个范围（某个系统、某个图纸目录）
        /// </summary>
        /// <param name="validRange">系统的dataitemdetailid 或者 图纸的dwgfileid</param>
        /// <param name="model">0所有，1按系统，2按目录</param>
        /// <returns></returns>
        bool TagInRange(int model, string PropValue, ec_enginedataEntity cable, List<string> validRange,
            ref List<ec_enginedata_pixelEntity> pixels, ref List<ec_drawing_fileEntity> allDwgs, ref List<ec_dataitemdetailEntity> allSystems)
        {
            var dwgIds = pixels.Where(x => x.EngineDataID == cable.EngineDataID).
                            Select(x => x.DrawingFileID).Distinct().ToList();//位号句柄所在的图纸id
            switch (model)
            {
                case 1:
                    if (string.IsNullOrEmpty(PropValue))
                    {
                        #region 如果是空，则用其图纸的名字或系统来协助判断                                   

                        //if (dwgIds.Count() == 1)
                        //{
                        //    //相当于一个系统内部的东西，不会跨系统
                        //    var dwg = allDwgs.FirstOrDefault(x => x.DrawingFileID == dwgIds.First());
                        //    if (dwg != null)
                        //    {
                        //        var dwgName = dwg.DrawingFileName.Replace(".dwg", "");
                        //        #region 通过图纸的名字、系统 去判断是否有这样的一个系统
                        //        var system_dwg = allSystems.FirstOrDefault(x => x.DataItemName == dwgName || x.DataItemNameEN == dwgName || x.DataItemCode == dwgName);
                        //        if (system_dwg == null)
                        //        {
                        //            //如果图纸的名字不能判断，再用图纸自己的系统判断
                        //            system_dwg = allSystems.FirstOrDefault(x => x.DataItemDetailID == dwg.DrawingSystem);
                        //            if (system_dwg == null)
                        //            {
                        //                //无法判断
                        //                return false;
                        //            }

                        //        }
                        //        #endregion
                        //        #region 是否在范围内
                        //        if (validRange.Any(x => x == system_dwg.DataItemDetailID))
                        //        {
                        //            return true;
                        //        }
                        //        else
                        //        {
                        //            //不在范围内
                        //            return false;
                        //        }
                        //        #endregion
                        //    }
                        //    else
                        //    {
                        //        //无法判断
                        //        return false;
                        //    }
                        //}
                        if (dwgIds.Count() > 0)
                        {
                            //相当于跨系统的东西
                            var dwgs = allDwgs.Where(x => dwgIds.Contains(x.DrawingFileID)).ToList();
                            if (dwgs.Count() != 0)
                            {
                                List<string> anyDwgMatch = new List<string>();
                                //通过图纸的名字去判断是否有这样的一个系统
                                foreach (var dwg in dwgs)
                                {
                                    var dwgName = dwg.DrawingFileName.Replace(".dwg", "");
                                    #region 通过图纸的名字、系统 去判断是否有这样的一个系统
                                    var system_dwg = allSystems.FirstOrDefault(x => x.DataItemName == dwgName || x.DataItemNameEN == dwgName || x.DataItemCode == dwgName);
                                    if (system_dwg == null)
                                    {
                                        //如果图纸的名字不能判断，再用图纸自己的系统判断
                                        system_dwg = allSystems.FirstOrDefault(x => x.DataItemDetailID == dwg.DrawingSystem);
                                        if (system_dwg == null)
                                        {
                                            //无法判断 
                                        }
                                        else
                                        {
                                            anyDwgMatch.Add(system_dwg.DataItemDetailID);
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        anyDwgMatch.Add(system_dwg.DataItemDetailID);
                                        break;
                                    }
                                    #endregion

                                }
                                if (anyDwgMatch.Count > 0)
                                {
                                    #region 是否在范围内
                                    if (validRange.Any(x => anyDwgMatch.Contains(x)))
                                    {
                                        Console.WriteLine("");
                                    }
                                    else
                                    {
                                        //不在范围内
                                        return false;
                                    }
                                    #endregion
                                }
                                else
                                {
                                    //无法判断
                                    return false;
                                }
                            }
                            else
                            {
                                //无法判断
                                return false;
                            }

                        }
                        else
                        {
                            //无法判断
                            return false;
                        }
                        #endregion
                    }
                    else
                    {
                        #region 不为空，检查自己
                        //通过名字去判断是否有这样的一个系统
                        var system_dwg = allSystems.FirstOrDefault(x => x.DataItemName == PropValue || x.DataItemNameEN == PropValue || x.DataItemCode == PropValue);
                        if (system_dwg == null)
                        {
                            //无法判断
                            return false;
                        }
                        if (validRange.Any(x => x == system_dwg.DataItemDetailID))
                        {
                            return true;
                        }
                        else
                        {
                            //不在范围内
                            return false;
                        }
                        #endregion
                    }
                    break;
                case 2:
                    //该位号的pixel是否在这个图纸范围上
                    if (dwgIds.Count() > 0)
                    {
                        #region 是否在范围内
                        if (validRange.Any(x => dwgIds.Contains(x)))
                        {
                            Console.WriteLine("");
                        }
                        else
                        {
                            //不在范围内
                            return false;
                        }
                        #endregion
                    }
                    else
                    {
                        //无法判断
                        return false;
                    }
                    break;
                case 0:
                    //所有
                    return true;
                default:
                    return true;
            }

            return true;
        }
        /// <summary>
        /// 生成特定的报表
        /// </summary>
        /// <param name="ProjectId">项目ID</param>
        /// <param name="folderId">文件夹ID</param>
        /// <param name="reportFileName">报表文件名称</param>

        public void ReportToExcel(string ProjectId, string folderId, string reportFileName, string param)
        {
            try
            {
                var paramObj = param.ToJObject();
                

                string filePath = "";
                var annexesFile = new AnnexesFileBLL().GetList(folderId).FirstOrDefault();
                filePath = annexesFile?.F_FilePath;
                if (!string.IsNullOrEmpty(filePath))//文件背后实际的file
                {
                    FileInfo fileinfo = new SystemIO.FileInfo(filePath);
                    if (fileinfo.Exists)
                    {
                        try
                        {
                            IWorkbook workbook;
                            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            {
                                if (annexesFile.F_FileExtensions == ".xls")
                                {
                                    workbook = new HSSFWorkbook(fileStream);
                                }
                                else
                                {
                                    workbook = new XSSFWorkbook(fileStream);
                                }
                            }
                            int ReportMark = 0;
                            
                            switch (reportFileName)
                            {
                                case "电缆清册":
                                    #region 电缆表
                                    string dataItemDetailIDOrDwgCategoryID; int model;
                                    dataItemDetailIDOrDwgCategoryID = paramObj.Value<string>("dataItemDetailIDOrDrawingCategoryID");// paramObj["dataItemDetailIDOrDwgCategoryID"].ToString();
                                    model = paramObj.Value<int>("model");


                                    ISheet sheetCable = workbook.CreateSheet("电缆清册");
                                    ISheet sheetCable2 = workbook.CreateSheet("电缆清册(双星)");
                                    #region 表头部分
                                    IRow rowCable = sheetCable.CreateRow(0);
                                    rowCable.CreateCell(0).SetCellValue("所属系统");
                                    rowCable.CreateCell(1).SetCellValue("电缆编号");
                                    rowCable.CreateCell(2).SetCellValue("电缆类型");
                                    rowCable.CreateCell(3).SetCellValue("电缆规格");
                                    rowCable.CreateCell(4).SetCellValue("电缆型号");
                                    rowCable.CreateCell(5).SetCellValue("起始设备代码");
                                    rowCable.CreateCell(6).SetCellValue("起始" + "\n" + "FrDeck");
                                    rowCable.CreateCell(7).SetCellValue("设备位置" + "\n" + "FrRoom");
                                    rowCable.CreateCell(8).SetCellValue("设备名称" + "\n" + "FrEquip");
                                    rowCable.CreateCell(9).SetCellValue("终止设备代码");
                                    rowCable.CreateCell(10).SetCellValue("终止" + "\n" + "ToDeck");
                                    rowCable.CreateCell(11).SetCellValue("设备位置" + "\n" + "ToRoom");
                                    rowCable.CreateCell(12).SetCellValue("设备名称" + "\n" + "ToEquip");
                                    rowCable.CreateCell(13).SetCellValue("是否变频");
                                    rowCable.CreateCell(14).SetCellValue("是否本安");
                                    rowCable.CreateCell(15).SetCellValue("是否独立屏蔽");
                                    rowCable.CreateCell(16).SetCellValue("是否防火");
                                    rowCable.CreateCell(17).SetCellValue("是否铠装");

                                    IRow rowCable2 = sheetCable2.CreateRow(0);
                                    rowCable2.CreateCell(0).SetCellValue("所属系统");
                                    rowCable2.CreateCell(1).SetCellValue("电缆编号");
                                    rowCable2.CreateCell(2).SetCellValue("电缆类型");
                                    rowCable2.CreateCell(3).SetCellValue("电缆规格");
                                    rowCable2.CreateCell(4).SetCellValue("电缆型号");
                                    rowCable2.CreateCell(5).SetCellValue("起始设备代码");
                                    rowCable2.CreateCell(6).SetCellValue("起始" + "\n" + "FrDeck");
                                    rowCable2.CreateCell(7).SetCellValue("设备位置" + "\n" + "FrRoom");
                                    rowCable2.CreateCell(8).SetCellValue("设备名称" + "\n" + "FrEquip");
                                    rowCable2.CreateCell(9).SetCellValue("终止设备代码");
                                    rowCable2.CreateCell(10).SetCellValue("终止" + "\n" + "ToDeck");
                                    rowCable2.CreateCell(11).SetCellValue("设备位置" + "\n" + "ToRoom");
                                    rowCable2.CreateCell(12).SetCellValue("设备名称" + "\n" + "ToEquip");
                                    rowCable2.CreateCell(13).SetCellValue("是否变频");
                                    rowCable2.CreateCell(14).SetCellValue("是否本安");
                                    rowCable2.CreateCell(15).SetCellValue("是否独立屏蔽");
                                    rowCable2.CreateCell(16).SetCellValue("是否防火");
                                    rowCable2.CreateCell(17).SetCellValue("是否铠装");
                                    #endregion
                                    #region 表名区
                                    var enginedataTableName = ProjectSugar.TableName<ec_enginedataEntity>(ProjectId);
                                    var objectTypeTableName = ProjectSugar.TableName<ec_objecttypeEntity>(ProjectId);
                                    var relTypeTableName = ProjectSugar.TableName<ec_reltypeEntity>(ProjectId);
                                    var PropertyTableName = ProjectSugar.TableName<ec_propertyEntity>(ProjectId);
                                    var DataItemTableName = ProjectSugar.TableName<ec_dataitemEntity>(ProjectId);
                                    var DataItemDetailTableName = ProjectSugar.TableName<ec_dataitemdetailEntity>(ProjectId);
                                    var relTableName = ProjectSugar.TableName<ec_enginedata_relEntity>(ProjectId);
                                    var propertyTableName = ProjectSugar.TableName<ec_enginedata_propertyEntity>(ProjectId);
                                    var pixelTableName = ProjectSugar.TableName<ec_enginedata_pixelEntity>(ProjectId);
                                    var dwgTableName = ProjectSugar.TableName<ec_drawing_fileEntity>(ProjectId);
                                    var dwgCategoryTableName = ProjectSugar.TableName<ec_drawing_catalogueEntity>(ProjectId);
                                    #endregion
                                    #region 数据查询区，避免循环里查询
                                    var pixels = SqlSugarHelper.Db.Queryable<ec_enginedata_pixelEntity>().AS(pixelTableName).Distinct().ToList();
                                    pixels = pixels.Where(x => x.DeleteFlg != 1).ToList();
                                    var dwgCategory = SqlSugarHelper.Db.Queryable<ec_drawing_catalogueEntity>().AS(dwgCategoryTableName).Distinct().ToList();

                                    var allDwgs = SqlSugarHelper.Db.Queryable<ec_drawing_fileEntity>().AS(dwgTableName).ToList();
                                    //var allProps = SqlSugarHelper.Db.Queryable<ec_enginedata_propertyEntity>().AS(propertyTableName).ToList();
                                    var DeckProp = SqlSugarHelper.Db.Queryable<ec_propertyEntity>().AS(PropertyTableName).First(x => x.PropertyName == "甲板号");
                                    List<ec_dataitemdetailEntity> allDecks = new List<ec_dataitemdetailEntity>();
                                    List<ec_dataitemdetailEntity> allSystems = new List<ec_dataitemdetailEntity>();
                                    List<string> validSystemIds = new List<string>(); // dataItemDetailID 以及 其下面所有的
                                    if (DeckProp != null)
                                    {
                                        var DeckEnumList = SqlSugarHelper.Db.Queryable<ec_dataitemEntity>().AS(DataItemTableName).First(x => x.DataItemName == DeckProp.EnumData);
                                        if (DeckEnumList != null)
                                        {
                                            allDecks = SqlSugarHelper.Db.Queryable<ec_dataitemdetailEntity>().AS(DataItemDetailTableName).Where(x => x.DataItemID == DeckEnumList.DataItemID).ToList();
                                        }
                                    }
                                    var SystemEnumList = SqlSugarHelper.Db.Queryable<ec_dataitemEntity>().AS(DataItemTableName).First(x => x.DataItemCode == GlobalObject.enumlist_System);
                                    if (SystemEnumList != null)
                                    {
                                        allSystems = SqlSugarHelper.Db.Queryable<ec_dataitemdetailEntity>().AS(DataItemDetailTableName).Where(x => x.DataItemID == SystemEnumList.DataItemID).ToList();


                                    }
                                    var needPropsName = new List<string>() {
                                        GlobalObject.propName_System, GlobalObject.propName_CableSpec,
                                    "变频电缆","本安电缆","是否独立屏蔽","是否防火","是否铠装","电缆供货类型","平行电缆",
"甲板号","房间号","中文名称",GlobalObject.propName_Frame};
                                    var allprops = SqlSugarHelper.Db.Queryable<ec_enginedata_propertyEntity>().AS(propertyTableName).
                                        Where(x => needPropsName.Contains(x.PropertyName)).
                                        ToList();

                                    switch (model)
                                    {
                                        case 0:
                                            break;
                                        case 1://按系统
                                            validSystemIds = new ec_dataitemBLL().GetChildNodes(ProjectId, dataItemDetailIDOrDwgCategoryID); break;
                                        case 2://按图纸（可能选的是目录，也可能选的是图纸）
                                            var folder = dwgCategory.FirstOrDefault(x => x.DrawingCatalogueID == dataItemDetailIDOrDwgCategoryID);
                                            if (folder != null)
                                            {
                                                //选的是目录
                                                validSystemIds = new ec_drawing_catalogueBLL().GetChildNodes(ProjectId, dataItemDetailIDOrDwgCategoryID); break;
                                            }
                                            else
                                            {
                                                var dwg = allDwgs.FirstOrDefault(x => x.DrawingFileID == dataItemDetailIDOrDwgCategoryID);
                                                if (dwg != null)
                                                {
                                                    //选的是文件
                                                    validSystemIds.Add(dwg.DrawingFileID);
                                                }
                                                else
                                                {
                                                    //ID 有些问题
                                                }
                                            }
                                            break;
                                        default:
                                            break;
                                    }

                                    var cableFromToRel = SqlSugarHelper.Db.Queryable<ec_reltypeEntity>().AS(relTypeTableName).ToList().FirstOrDefault(x => x.RelType == ((int)enum_RelType.设备_电缆).ToString());
                                    if (cableFromToRel == null)
                                    {
                                        throw new Exception($"查不到【{enum_RelType.设备_电缆.ToString()}】这个关联类型。");
                                    }
                                    var relDatas = SqlSugarHelper.Db.Queryable<ec_enginedata_relEntity>().AS(relTableName)
                                        .LeftJoin<ec_enginedataEntity>((eere,eede1)=>eere.RelEngineData1ID==eede1.EngineDataID).AS<ec_enginedataEntity>(enginedataTableName)
                                        .LeftJoin<ec_objecttypeEntity>((eere,eede1,eote1)=>eede1.ObjectTypeID==eote1.ObjectTypeID).AS<ec_objecttypeEntity>(objectTypeTableName)
                                        .LeftJoin<ec_enginedataEntity2>((eere, eede1, eote1,eede2)=> eere.RelEngineData2ID == eede2.EngineDataID).AS<ec_enginedataEntity2>(enginedataTableName)
                                        .LeftJoin<ec_objecttypeEntity2>((eere, eede1, eote1, eede2,eote2)=> eede2.ObjectTypeID == eote2.ObjectTypeID).AS<ec_objecttypeEntity2>(objectTypeTableName)
                                        .Where((eere, eede1, eote1, eede2, eote2) => eere.RelTypeID == cableFromToRel.RelTypeID)
                                        .Select((eere, eede1, eote1, eede2, eote2)=> new {
                                            eere.EngineDataRelID,
                                            eere.RelTypeID,
                                            eere.RelEngineData1ID,
                                            RelEngDataObjType1= eote1.ObjectTypeName,
                                            eere.RelEngineData2ID,
                                            RelEngDataObjType2 = eote2.ObjectTypeName,
                                            eere.OPCPixel
                                        })
                                        .ToList();
                                    var cables = SqlSugarHelper.Db.Queryable<ec_enginedataEntity>().AS(enginedataTableName)
                                                         .InnerJoin<ec_objecttypeEntity>((a, b) => a.ObjectTypeID == b.ObjectTypeID).AS<ec_objecttypeEntity>(objectTypeTableName)
                                                         .InnerJoin<ec_enginedata_pixelEntity>((a, b, c) => a.EngineDataID == c.EngineDataID).AS<ec_enginedata_pixelEntity>(pixelTableName)
                                                         .Where((a, b, c) =>
                                                            b.ObjectTypeName.EndsWith("电缆") &&
                                                            !string.IsNullOrEmpty(a.TagNumber) &&
                                                            c.DeleteFlg != 1)
                                                         .OrderBy((a, b) => a.TagNumber)
                                                         .Distinct().ToList();
                                    //24 4 2，过滤掉图面上不存在的

                                    var Equips = SqlSugarHelper.Db.Queryable<ec_enginedataEntity>().AS(enginedataTableName)
                                                         .InnerJoin<ec_objecttypeEntity>((a, b) => a.ObjectTypeID == b.ObjectTypeID).AS<ec_objecttypeEntity>(objectTypeTableName)
                                                         .Where((a, b) => !b.ObjectTypeName.EndsWith("电缆"))
                                                         .OrderBy((a, b) => a.TagNumber)
                                                         .ToList();
                                    #endregion
                                    int curRow = 1;
                                    //对电缆编号排序
                                    cables.Sort((x, y) => CommonHelper.Compare(x.TagNumber, y.TagNumber));

                                    foreach (var cable in cables) //Where(x => x.TagNumber == "TEST-CABLE-001" || x.TagNumber == "1L11-7")
                                    {
                                        try
                                        {

                                            bool RoutingType = false;//true时，代表**，会出现在第二个sheet里
                                            rowCable = sheetCable.CreateRow(curRow++);
                                            rowCable.CreateCell(0).SetCellValue("");
                                            rowCable.CreateCell(1).SetCellValue("");
                                            rowCable.CreateCell(2).SetCellValue("");
                                            rowCable.CreateCell(3).SetCellValue("");
                                            rowCable.CreateCell(4).SetCellValue("");
                                            rowCable.CreateCell(5).SetCellValue("");
                                            rowCable.CreateCell(6).SetCellValue("");
                                            rowCable.CreateCell(7).SetCellValue("");
                                            rowCable.CreateCell(8).SetCellValue("");
                                            rowCable.CreateCell(9).SetCellValue("");
                                            rowCable.CreateCell(10).SetCellValue("");
                                            rowCable.CreateCell(11).SetCellValue("");
                                            rowCable.CreateCell(12).SetCellValue("");
                                            rowCable.CreateCell(13).SetCellValue("");
                                            rowCable.CreateCell(14).SetCellValue("");
                                            rowCable.CreateCell(15).SetCellValue("");
                                            rowCable.CreateCell(16).SetCellValue("");
                                            rowCable.CreateCell(17).SetCellValue("");

                                            //25 02 28，优化速速，估注释，搬到循环外
                                            var TagProps = allprops.Where(x => x.EngineDataID == cable.EngineDataID)//&& (x.CaseID == "0" || string.IsNullOrEmpty(x.CaseID))
                                                .ToList();//位号的所有属性
                                            var PropValue = "";




                                            #region 所属系统
                                            var TagProp = TagProps.Where(x => x.PropertyName == GlobalObject.propName_System && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                            PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;

                                            if (!TagInRange(model, PropValue, cable, validSystemIds, ref pixels, ref allDwgs, ref allSystems))
                                            {
                                                curRow--;
                                                continue;
                                            } //判断是否在范围内

                                            if (!string.IsNullOrEmpty(PropValue) && Regex.IsMatch(PropValue, "^[A-Za-z0-9]*$") && allSystems.Any(x => x.DataItemName == PropValue))
                                            {
                                                //换成枚举的描述
                                                PropValue = allSystems.FirstOrDefault(x => x.DataItemName == PropValue).DataItemCode;
                                            }
                                            rowCable.Cells[0].SetCellValue(PropValue);//感觉这里保持默认好点
                                            #endregion
                                            #region 位号
                                            rowCable.Cells[1].SetCellValue(cable.TagNumber);
                                            if (cable.TagNumber.Contains("**"))
                                            {
                                                RoutingType = true;
                                            }
                                            #endregion
                                            rowCable.Cells[2].SetCellValue("");//电缆类型，信号、电力、本安、动力、随机
                                            #region 电缆规格
                                            TagProp = TagProps.Where(x => x.PropertyName == GlobalObject.propName_CableSpec && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                            PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                            //动力：一个* | 一个*一个+
                                            //对绞：两个*
                                            CableTypeEnum CableType;
                                            rowCable.Cells[3].SetCellValue(PropValue);


                                            if (Regex.IsMatch(PropValue, "[^*]*\\*[^*]*\\*[^*]*"))
                                            {
                                                //如2*2*1.5
                                                CableType = CableTypeEnum.信号;
                                            }
                                            else if (Regex.IsMatch(PropValue, "[^*]*\\*[^*]*"))
                                            {
                                                //如2*1.5
                                                CableType = CableTypeEnum.动力;

                                            }
                                            else if (PropValue.ToUpper().Contains("CAT"))
                                            {
                                                //如cat6
                                                CableType = CableTypeEnum.CAT6;
                                            }
                                            else
                                            {
                                                goto xxx;
                                            }
                                            #endregion
                                            #region 电缆型号（CJ86）
                                            TagProp = TagProps.Where(x => x.PropertyName == "变频电缆" && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                            PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                            rowCable.Cells[13].SetCellValue(PropValue);
                                            switch (PropValue.ToLower())
                                            {
                                                case "yes":
                                                case "true":
                                                case "是":
                                                    //变频
                                                    rowCable.Cells[2].SetCellValue("VFD");//电缆类型，信号、电力、本安、动力、随机
                                                    rowCable.Cells[4].SetCellValue("CJPF86/SC-VFD");
                                                    goto xxx;
                                                default:
                                                    break;
                                            }
                                            bool flg_IS = false;
                                            bool flg_PairShield = false;
                                            bool flg_fire = false;
                                            bool flg_arm = false;

                                            TagProp = TagProps.Where(x => x.PropertyName == "本安电缆" && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                            PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                            rowCable.Cells[14].SetCellValue(PropValue);
                                            switch (PropValue.ToLower().Replace("）", ")").Replace("（", "("))
                                            {
                                                case "yes":
                                                case "true":
                                                case "是":
                                                case "i.s":
                                                case "i.s.":
                                                case "(i.s)":
                                                case "(i.s.)":
                                                case "i.e":
                                                case "i.e.":
                                                case "(i.e)":
                                                case "(i.e.)":
                                                    //本安
                                                    flg_IS = true;
                                                    rowCable.Cells[2].SetCellValue("IS");//电缆类型，信号、电力、本安、动力、随机
                                                    break;
                                                default:
                                                    //非本安
                                                    switch (CableType)
                                                    {
                                                        case CableTypeEnum.动力:
                                                            rowCable.Cells[2].SetCellValue("L");//电缆类型，信号、电力、本安、动力、随机
                                                            break;
                                                        case CableTypeEnum.信号:
                                                            rowCable.Cells[2].SetCellValue("I");//电缆类型，信号、电力、本安、动力、随机
                                                            break;
                                                        case CableTypeEnum.CAT6:
                                                            rowCable.Cells[2].SetCellValue("T");//电缆类型，信号、电力、本安、动力、随机
                                                            break;
                                                        default:
                                                            break;
                                                    }

                                                    break;
                                            }
                                            TagProp = TagProps.Where(x => x.PropertyName == "是否独立屏蔽" && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                            PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                            rowCable.Cells[15].SetCellValue(PropValue);
                                            switch (PropValue.ToLower())
                                            {
                                                case "yes":
                                                case "true":
                                                case "是":
                                                    //独立屏蔽
                                                    flg_PairShield = true;
                                                    break;
                                                default:
                                                    break;
                                            }
                                            TagProp = TagProps.Where(x => x.PropertyName == "是否防火" && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                            PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                            rowCable.Cells[16].SetCellValue(PropValue);
                                            switch (PropValue.ToLower())
                                            {
                                                case "yes":
                                                case "true":
                                                case "是":
                                                case "(f)":
                                                case "（f）":
                                                    //防火
                                                    flg_fire = true;
                                                    break;
                                                default:
                                                    break;
                                            }
                                            TagProp = TagProps.Where(x => x.PropertyName == "是否铠装" && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                            PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                            rowCable.Cells[17].SetCellValue(PropValue);
                                            switch (PropValue.ToLower())
                                            {
                                                case "yes":
                                                case "true":
                                                case "是":
                                                    //铠装
                                                    flg_arm = true;
                                                    break;
                                                default:
                                                    break;
                                            }

                                            if (CableType == CableTypeEnum.动力)
                                            {
                                                if (flg_arm == false)
                                                {
                                                    rowCable.Cells[4].SetCellValue("CJPF/SC");
                                                }
                                                else if (flg_fire == true)
                                                {
                                                    rowCable.Cells[4].SetCellValue("CJ86/NSC");
                                                }
                                                else if (flg_IS == true)
                                                {
                                                    rowCable.Cells[4].SetCellValue("CJ86/SC.IS");
                                                }
                                                else
                                                {
                                                    rowCable.Cells[4].SetCellValue("CJ86/SC");
                                                }
                                            }
                                            else
                                            {
                                                if (flg_arm == false)
                                                {
                                                    rowCable.Cells[4].SetCellValue("CHJPF/SC");//?????
                                                }
                                                else if (flg_fire == true)
                                                {
                                                    rowCable.Cells[4].SetCellValue("CHJ86/NSC");//
                                                }
                                                else if (flg_IS == true)
                                                {
                                                    rowCable.Cells[4].SetCellValue("CHJ86/SC.IS");//
                                                }
                                                else if (flg_PairShield == true)//也只有信号电缆2*2*1.5这种才有
                                                {
                                                    rowCable.Cells[4].SetCellValue("CHJP86/SC");//
                                                }
                                                else
                                                {
                                                    rowCable.Cells[4].SetCellValue("CHJ86/SC");
                                                }
                                            }
                                        #endregion
                                        xxx:
                                            #region 供货范围
                                            TagProp = TagProps.Where(x => x.PropertyName == "电缆供货类型" && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                            PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                            if (PropValue.Contains("**"))
                                            {
                                                RoutingType = true;
                                            }
                                            else if (PropValue.Contains("*"))
                                            {
                                                rowCable.Cells[2].SetCellValue("A");//电缆类型，信号、电力、本安、动力、随机
                                            }
                                            else
                                            {
                                                //根据前面的 CableTypeEnum 来
                                            }
                                            #endregion
                                            //电缆的from to是根据甲板号的order顺序来的，高优先级的就属于from
                                            int? FromOrder = -1; int? ToOrder = -1;
                                            #region From
                                            var cableFromId = relDatas.FirstOrDefault(x => x.RelEngineData2ID == cable.EngineDataID && !x.RelEngDataObjType1.Contains("OPC"))?.RelEngineData1ID;
                                            if (!string.IsNullOrEmpty(cableFromId))
                                            {
                                                var cableFromObj = Equips.FirstOrDefault(x => x.EngineDataID == cableFromId);
                                                if (cableFromObj != null)
                                                {
                                                    var EquipFromProps = allprops.Where(x => x.EngineDataID == cableFromObj.EngineDataID)
                                                        .ToList();
                                                    rowCable.Cells[5].SetCellValue(cableFromObj?.TagNumber);

                                                    TagProp = EquipFromProps.Where(x => x.PropertyName == "甲板号" && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                                    PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                                    //转换
                                                    if (!string.IsNullOrEmpty(PropValue))
                                                    {
                                                        var frDeck = allDecks.FirstOrDefault(x => x.DataItemName == ec_dataitemService.GetNameBeforeDoublePipe(PropValue));
                                                        if (frDeck != null)
                                                        {
                                                            //找到匹配的enum，但是如果code为空，依旧使用自己原本的
                                                            PropValue = string.IsNullOrEmpty(frDeck.DataItemCode) ? PropValue : frDeck.DataItemCode;
                                                            FromOrder = frDeck.OrderID;
                                                        }

                                                    }

                                                    rowCable.Cells[6].SetCellValue(PropValue);//没找到依旧用自己原本的

                                                    TagProp = EquipFromProps.Where(x => x.PropertyName == "房间号" && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                                    PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                                    if (string.IsNullOrEmpty(PropValue))
                                                    {
                                                        //没房间号，取肋位号
                                                        TagProp = EquipFromProps.Where(x => x.PropertyName == GlobalObject.propName_Frame && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                                        PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                                    }
                                                    else
                                                    {
                                                        //有房间号，取房间号
                                                    }
                                                    rowCable.Cells[7].SetCellValue(PropValue);


                                                    TagProp = EquipFromProps.Where(x => x.PropertyName == "中文名称" && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                                    PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                                    rowCable.Cells[8].SetCellValue(PropValue);

                                                }

                                            }
                                            #endregion
                                            #region To
                                            var cableEndId = relDatas.FirstOrDefault(x => x.RelEngineData1ID == cable.EngineDataID && !x.RelEngDataObjType2.Contains("OPC"))?.RelEngineData2ID;
                                            if (!string.IsNullOrEmpty(cableEndId))
                                            {
                                                var cableEndObj = Equips.FirstOrDefault(x => x.EngineDataID == cableEndId);
                                                if (cableEndObj != null)
                                                {
                                                    var EquipToProps = allprops.Where(x => x.EngineDataID == cableEndObj.EngineDataID)
                                                        .ToList();
                                                    rowCable.Cells[9].SetCellValue(cableEndObj?.TagNumber);


                                                    TagProp = EquipToProps.Where(x => x.PropertyName == "甲板号" && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                                    PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                                    //转换
                                                    if (!string.IsNullOrEmpty(PropValue))
                                                    {
                                                        //目前属性寸的是name + || + nameEN，因为cad需要这样显示
                                                        //但是电缆表需要的是Code 
                                                        var ToDeck = allDecks.FirstOrDefault(x => x.DataItemName ==ec_dataitemService.GetNameBeforeDoublePipe(PropValue));
                                                        if (ToDeck != null)
                                                        {
                                                            //找到匹配的enum，但是如果code为空，依旧使用自己原本的
                                                            PropValue = string.IsNullOrEmpty(ToDeck.DataItemCode) ? PropValue : ToDeck.DataItemCode;
                                                            ToOrder = ToDeck.OrderID;
                                                        }
                                                    }

                                                    rowCable.Cells[10].SetCellValue(PropValue);

                                                    TagProp = EquipToProps.Where(x => x.PropertyName == "房间号" && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                                    PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                                    if (string.IsNullOrEmpty(PropValue))
                                                    {
                                                        //没房间号，取肋位号
                                                        TagProp = EquipToProps.Where(x => x.PropertyName == GlobalObject.propName_Frame && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                                        PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                                    }
                                                    else
                                                    {
                                                        //有房间号，取房间号
                                                    }
                                                    rowCable.Cells[11].SetCellValue(PropValue);


                                                    TagProp = EquipToProps.Where(x => x.PropertyName == "中文名称" && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                                    PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                                    rowCable.Cells[12].SetCellValue(PropValue);
                                                }

                                            }
                                            #endregion
                                            if (FromOrder != -1 && ToOrder != -1)
                                            {
                                                if (FromOrder > ToOrder)
                                                {
                                                    //5678    9 10 11 12
                                                    var tempTag = rowCable.Cells[5].StringCellValue;
                                                    var tempDeck = rowCable.Cells[6].StringCellValue;
                                                    var tempRoom = rowCable.Cells[7].StringCellValue;
                                                    var tempName = rowCable.Cells[8].StringCellValue;

                                                    rowCable.Cells[5].SetCellValue(rowCable.Cells[9].StringCellValue);

                                                    rowCable.Cells[6].SetCellValue(rowCable.Cells[10].StringCellValue);

                                                    rowCable.Cells[7].SetCellValue(rowCable.Cells[11].StringCellValue);

                                                    rowCable.Cells[8].SetCellValue(rowCable.Cells[12].StringCellValue);

                                                    rowCable.Cells[9].SetCellValue(tempTag);
                                                    rowCable.Cells[10].SetCellValue(tempDeck);
                                                    rowCable.Cells[11].SetCellValue(tempRoom);
                                                    rowCable.Cells[12].SetCellValue(tempName);
                                                }
                                            }
                                            #region 第二个sheet和平行电缆
                                            if (RoutingType)
                                            {
                                                // 在目标工作表中创建新行
                                                IRow newRow = sheetCable2.CreateRow(sheetCable2.LastRowNum + 1); // 将新行添加到目标工作表的末尾

                                                // 复制源行的单元格数据到新行
                                                for (int i = 0; i < rowCable.LastCellNum; i++)
                                                {
                                                    ICell sourceCell = rowCable.GetCell(i);
                                                    ICell newCell = newRow.CreateCell(i);

                                                    if (sourceCell != null)
                                                    {
                                                        newCell.SetCellValue(sourceCell.StringCellValue); // 这里假设你的单元格都包含文本数据
                                                    }
                                                }
                                                for (int i = 0; i < rowCable.LastCellNum; i++)
                                                {
                                                    rowCable.CreateCell(i).SetCellValue("");
                                                }
                                                curRow--;
                                            }
                                            else
                                            {
                                                TagProp = TagProps.Where(x => x.PropertyName == "平行电缆" && !string.IsNullOrEmpty(x.PropertyValue)).ToList();
                                                PropValue = TagProp.Count() == 0 ? "" : TagProp.Last()?.PropertyValue;
                                                if (!string.IsNullOrEmpty(PropValue))
                                                {
                                                    foreach (var pCable in PropValue.Split(','))
                                                    {
                                                        // 创建新行
                                                        IRow newRow = sheetCable.CreateRow(curRow++); // 将新行添加到目标工作表的末尾

                                                        // 复制源行的单元格数据到新行
                                                        for (int i = 0; i < rowCable.LastCellNum; i++)
                                                        {
                                                            ICell sourceCell = rowCable.GetCell(i);
                                                            ICell newCell = newRow.CreateCell(i);

                                                            if (sourceCell != null)
                                                            {
                                                                newCell.SetCellValue(sourceCell.StringCellValue); // 这里假设你的单元格都包含文本数据
                                                            }
                                                        }
                                                        newRow.CreateCell(1).SetCellValue(pCable);
                                                    }
                                                    Console.Write(PropValue);
                                                }
                                            }
                                            #endregion
                                        }
                                        catch (Exception ex)
                                        {
                                            log4net.LogManager.GetLogger("ERROR").Error("导出电缆清册 - " + ex.Message + ex.StackTrace);
                                            continue;
                                        }

                                    }
                                    #endregion
                                    break;
                                case "云线备注清单":
                                    #region 云线备注清单 
                                    int SelectModel;

                                    SelectModel = paramObj.Value<int>("model");
                                    // <param name="SelectModel">0全部，1未抽取过，2抽取过</param>


                                    ISheet sheetMark = workbook.GetSheetAt(0);
                                    if (sheetMark == null) sheetMark = workbook.CreateSheet("云线备注清单");
                                    workbook.SetSheetName(0, "云线备注清单");
                                    ICellStyle cellStyle = workbook.CreateCellStyle();
                                    IDataFormat format = workbook.CreateDataFormat();
                                    string pattern = "yyyy-MM-dd HH:mm:ss";
                                    short formatIndex = format.GetFormat(pattern);
                                    cellStyle.DataFormat = formatIndex;
                                    #region 表头部分
                                    IRow rowMark = sheetMark.CreateRow(0);
                                    rowMark.CreateCell(0).SetCellValue("序号");
                                    rowMark.CreateCell(1).SetCellValue("图号");
                                    rowMark.CreateCell(2).SetCellValue("图名");
                                    rowMark.CreateCell(3).SetCellValue("页码");
                                    rowMark.CreateCell(4).SetCellValue("电缆号");
                                    rowMark.CreateCell(5).SetCellValue("注意改图是否影响填料函（注意重新退审）");
                                    rowMark.CreateCell(6).SetCellValue("修改内容");
                                    rowMark.CreateCell(7).SetCellValue("修改属性" + "\n" + "（新增/删除/修改）");
                                    rowMark.CreateCell(8).SetCellValue("修改原因");
                                    rowMark.CreateCell(9).SetCellValue("CAD履历OK？");
                                    rowMark.CreateCell(10).SetCellValue("日期");
                                    rowMark.CreateCell(11).SetCellValue("系统修改人");
                                    rowMark.CreateCell(12).SetCellValue("是否涉及生产设计");
                                    rowMark.CreateCell(13).SetCellValue("是否涉及其他系统图" + "\n" + "（如有需告知相关人员）");
                                    rowMark.CreateCell(14).SetCellValue("涉及其他图纸");
                                    rowMark.CreateCell(15).SetCellValue("OA通知对方否");
                                    rowMark.CreateCell(16).SetCellValue("生产涉及主管确认");
                                    rowMark.CreateCell(17).SetCellValue("切割册单号");
                                    rowMark.CreateCell(18).SetCellValue("抽取日期");

                                    #endregion
                                    #region 表名区
                                    var drawingsynEntityTableName = ProjectSugar.TableName<ec_drawing_synEntity>(ProjectId);
                                    var drawingfileEntityTableName = ProjectSugar.TableName<ec_drawing_fileEntity>(ProjectId);
                                    var drawingfileEntityTableName2 = ProjectSugar.TableName<ec_drawing_fileEntity>(ProjectId);
                                    var drawingcatalogueEntityTableName = ProjectSugar.TableName<ec_drawing_catalogueEntity>(ProjectId);
                                    #endregion
                                    #region 数据查询区，避免循环里查询

                                    string strExtractDate = string.Empty;

                                    switch (SelectModel)
                                    {
                                        case 0:
                                            strExtractDate = "";
                                            break;
                                        case 1:
                                            strExtractDate = "Exist";
                                            break;
                                        default:
                                            break;
                                    }
                                    var marks = SqlSugarHelper.Db.Queryable<ec_drawing_synEntity>().AS(drawingsynEntityTableName)
                                                         .LeftJoin<ec_drawing_fileEntity>((eds, edf) => eds.DrawingFileID == edf.DrawingFileID).AS<ec_drawing_fileEntity>(drawingfileEntityTableName)
                                                         .LeftJoin<ec_drawing_catalogueEntity>((eds, edf, edc) => edf.DrawingCatalogueID == edc.DrawingCatalogueID).AS<ec_drawing_catalogueEntity>(drawingcatalogueEntityTableName)
                                                         .WhereIF(strExtractDate == "", (eds, edf, edc) => eds.cloud != string.Empty && eds.cloud != null && eds.ExtractDate == null)
                                                         .WhereIF(strExtractDate == "Exist", (eds, edf, edc) => eds.cloud != string.Empty && eds.cloud != null && eds.ExtractDate != null)
                                                         .Select((eds, edf, edc) => new MarkInfo
                                                         {
                                                             DrawingNo = eds.DrawingNo,
                                                             DrawingFileName = edf.DrawingFileName,
                                                             PageNo = eds.PageNos,
                                                             CableNo = eds.Cables,
                                                             IsMaterial = eds.IsMaterial,
                                                             Remark = eds.Remark,
                                                             Type = eds.Type,
                                                             CreateTime = eds.CreateTime,
                                                             CreateUserId = eds.CreateUserID,
                                                             IsProcess = eds.IsProcess,
                                                             RelDrawingFileID = eds.otherDwgIds,
                                                             ExtractDate = eds.ExtractDate
                                                         })
                                                         .ToList();
                                    #endregion
                                    int MarkCurRow = 1;
                                    int sequenceNo = 1;
                                    foreach (var mark in marks)
                                    {
                                        try
                                        {
                                            rowMark = sheetMark.CreateRow(MarkCurRow++);
                                            rowMark.CreateCell(0).SetCellValue(sequenceNo++);
                                            rowMark.CreateCell(1).SetCellValue(mark.DrawingNo);
                                            rowMark.CreateCell(2).SetCellValue(mark.DrawingFileName);
                                            rowMark.CreateCell(3).SetCellValue(mark.PageNo);
                                            rowMark.CreateCell(4).SetCellValue(mark.CableNo);
                                            if (mark.IsMaterial.Equals(1))
                                            {
                                                rowMark.CreateCell(5).SetCellValue("是");
                                            }
                                            else
                                            {
                                                rowMark.CreateCell(5).SetCellValue("否");
                                            }
                                            rowMark.CreateCell(6).SetCellValue(mark.Remark);
                                            rowMark.CreateCell(7).SetCellValue(mark.Type);
                                            rowMark.CreateCell(8).SetCellValue(string.Empty);
                                            rowMark.CreateCell(9).SetCellValue(string.Empty);
                                            rowMark.CreateCell(10).SetCellValue((DateTime)mark.CreateTime);
                                            rowMark.Cells[10].CellStyle = cellStyle;
                                            rowMark.CreateCell(11).SetCellValue(mark.CreateUserId);
                                            if (mark.IsProcess.Equals(1))
                                            {
                                                rowMark.CreateCell(12).SetCellValue("是");
                                            }
                                            else
                                            {
                                                rowMark.CreateCell(12).SetCellValue("否");
                                            }
                                            if (mark.RelDrawingFileID.IsEmpty())
                                            {
                                                rowMark.CreateCell(13).SetCellValue("否");
                                                rowMark.CreateCell(14).SetCellValue(mark.RelDrawingFileID);
                                            }
                                            else
                                            {
                                                rowMark.CreateCell(13).SetCellValue("是");
                                                string[] partMarks = mark.RelDrawingFileID.Split('|');
                                                string strDwgFileName = string.Empty;
                                                foreach (string partMark in partMarks)
                                                {
                                                    strDwgFileName = "," + GetDrawingFileName(partMark, drawingfileEntityTableName);
                                                }
                                                strDwgFileName = strDwgFileName.Remove(0, 1);
                                                rowMark.CreateCell(14).SetCellValue(strDwgFileName);
                                            }

                                            rowMark.CreateCell(15).SetCellValue(string.Empty);
                                            rowMark.CreateCell(16).SetCellValue(string.Empty);
                                            rowMark.CreateCell(17).SetCellValue(string.Empty);
                                            if (mark.ExtractDate.IsEmpty())
                                            {
                                                rowMark.CreateCell(18).SetCellValue(Time.MySqlTime);
                                            }
                                            else
                                            {
                                                rowMark.CreateCell(18).SetCellValue((DateTime)mark.ExtractDate);
                                            }
                                            rowMark.Cells[18].CellStyle = cellStyle;
                                        }
                                        catch (Exception ex)
                                        {
                                            log4net.LogManager.GetLogger("ERROR").Error("导出云线备注清册 - " + ex.Message + ex.StackTrace);
                                            continue;
                                        }

                                    }
                                    if (strExtractDate == "")
                                    {
                                        updateExtractDate(ProjectId);
                                    }
                                    #endregion
                                    break;
                                case "设备清册":
                                    #region 设备清单 
                                    var type = paramObj.Value<string>("range");
                                    int selectModel = 0;
                                    var dwgIds = string.Empty;
                                    List<string> dwgIdCos = new List<string>();
                                    if (type == "0")
                                    {
                                        selectModel = 1;
                                        //为了过滤无效图纸，其实还是要处理dwgIdCos
                                        var tableName = ProjectSugar.TableName<ec_drawing_fileEntity>(ProjectId);
                                        var pixelTableName2 = ProjectSugar.TableName<ec_enginedata_pixelEntity>(ProjectId);
                                        var files = SqlSugarHelper.Db.Queryable<ec_drawing_fileEntity>().AS(tableName).ToList();
                                        files = files.Where(x => x.IsDelete != 1).Where(x => x.IsEngineDWG != null).Where(X => X.IsEngineDWG == 1).ToList();
                                        dwgIdCos = SqlSugarHelper.Db.Queryable<ec_enginedata_pixelEntity>().AS(pixelTableName2).
    Where(x => x.DeleteFlg != 1 && files.Select(y => y.DrawingFileID).ToList().Contains(x.DrawingFileID)).
    Select(x => x.DrawingFileID).Distinct().ToList();
                                    }
                                    else
                                    {
                                        dwgIds = paramObj.Value<string>("dwgIds");
                                        dwgIdCos = dwgIds.Split(',').ToList();
                                        selectModel = 1;
                                    }

                                    ISheet sheetEquipments = workbook.GetSheetAt(0);
                                    if (sheetEquipments == null) sheetMark = workbook.CreateSheet("设备清册");
                                    workbook.SetSheetName(0, "设备清册");
                                    #region 表头部分
                                    IRow rowEquipment = sheetEquipments.CreateRow(0);
                                    rowEquipment.CreateCell(0).SetCellValue("序号");
                                    rowEquipment.CreateCell(1).SetCellValue("系统图号");
                                    rowEquipment.CreateCell(2).SetCellValue("系统图名");
                                    rowEquipment.CreateCell(3).SetCellValue("系统页码");
                                    rowEquipment.CreateCell(4).SetCellValue("数据输入时间");
                                    rowEquipment.CreateCell(5).SetCellValue("电缆编号");
                                    rowEquipment.CreateCell(6).SetCellValue("设备代码");
                                    rowEquipment.CreateCell(7).SetCellValue("设备中文名称");
                                    rowEquipment.CreateCell(8).SetCellValue("设备英文名称");
                                    rowEquipment.CreateCell(9).SetCellValue("设备单元");
                                    rowEquipment.CreateCell(10).SetCellValue("甲板号");
                                    rowEquipment.CreateCell(11).SetCellValue("甲板代码");
                                    rowEquipment.CreateCell(12).SetCellValue("房间号");
                                    rowEquipment.CreateCell(13).SetCellValue("肋位号");

                                    #endregion
                                    #region 表名区
                                    var eqiEnginedataPixelEntityTableName = ProjectSugar.TableName<ec_enginedata_pixelEntity>(ProjectId);
                                    var eqiEnginedataEntityTableName = ProjectSugar.TableName<ec_enginedataEntity>(ProjectId);
                                    var eqiObjectTypeEntityTableName = ProjectSugar.TableName<ec_objecttypeEntity>(ProjectId);
                                    var eqidrawingfileEntityTableName = ProjectSugar.TableName<ec_drawing_fileEntity>(ProjectId);
                                    var eqidrawingcatalogueEntityTableName = ProjectSugar.TableName<ec_drawing_catalogueEntity>(ProjectId);
                                    var eqiEnginePropertyEntityTableName = ProjectSugar.TableName<ec_enginedata_propertyEntity>(ProjectId);
                                    var eqiPropertyTableName = ProjectSugar.TableName<ec_propertyEntity>(ProjectId);
                                    var eqiDataItemTable = ProjectSugar.TableName<ec_dataitemEntity>(ProjectId);
                                    var eqiDataItemDetailTable = ProjectSugar.TableName<ec_dataitemdetailEntity>(ProjectId);
                                    #endregion
                                    #region 数据查询区，避免循环里查询
                                    // 子查询先筛选 dtaitemname != "" 且 DataItemCode是甲板号的数据，以免leftjoin到空或者其他ITEM项下面的数据
                                    var subQuery = SqlSugarHelper.Db.Queryable<ec_dataitemdetailEntity>().AS(eqiDataItemDetailTable)
                                        .LeftJoin<ec_dataitemEntity>((did,die)=>did.DataItemID==die.DataItemID).AS<ec_dataitemEntity>(eqiDataItemTable)
                                        .Where((did, die) => did.DataItemName != "" && die.DataItemCode == "甲板号")
                                        .Select((did, die) => new { did.DataItemName, did.DataItemCode });

                                    var Equipments = SqlSugarHelper.Db.Queryable(
                                        SqlSugarHelper.Db.Queryable<ec_enginedata_pixelEntity>().AS(eqiEnginedataPixelEntityTableName)
                                                    .LeftJoin<ec_enginedataEntity>((eep, ee) => eep.EngineDataID == ee.EngineDataID).AS<ec_enginedataEntity>(eqiEnginedataEntityTableName)
                                                    .LeftJoin<ec_objecttypeEntity>((eep, ee, eo) => ee.ObjectTypeID == eo.ObjectTypeID).AS<ec_objecttypeEntity>(eqiObjectTypeEntityTableName)
                                                    .LeftJoin<ec_drawing_fileEntity>((eep, ee, eo, edf) => eep.DrawingFileID == edf.DrawingFileID).AS<ec_drawing_fileEntity>(eqidrawingfileEntityTableName)
                                                    .LeftJoin<ec_drawing_catalogueEntity>((eep, ee, eo, edf, edc) => edf.DrawingCatalogueID == edc.DrawingCatalogueID).AS<ec_drawing_catalogueEntity>(eqidrawingcatalogueEntityTableName)
                                                    .LeftJoin(SqlSugarHelper.Db.Queryable<ec_enginedata_propertyEntity>().AS(eqiEnginePropertyEntityTableName)
                                                        .Select(eep => new
                                                        {
                                                            eep.EngineDataID,
                                                            中文名称 = SqlFunc.IIF(eep.PropertyName == "中文名称", eep.PropertyValue, string.Empty),
                                                            英文名称 = SqlFunc.IIF(eep.PropertyName == "英文名称", eep.PropertyValue, string.Empty),
                                                            设备单元 = SqlFunc.IIF(eep.PropertyName =="设备单元",eep.PropertyValue, string.Empty),
                                                            甲板号 = SqlFunc.IIF(eep.PropertyName == "甲板号", SqlFunc.IIF(
                                                                                                                SqlFunc.Contains(eep.PropertyValue, "||"),
                                                                                                                SqlFunc.Trim(SqlFunc.Substring(eep.PropertyValue, 0, SqlFunc.CharIndexNew(eep.PropertyValue, "||") - 1)),
                                                                                                                eep.PropertyValue), string.Empty),
                                                            房间号 = SqlFunc.IIF(eep.PropertyName == "房间号", eep.PropertyValue, string.Empty),
                                                            肋位号 = SqlFunc.IIF(eep.PropertyName == "肋位号", eep.PropertyValue, string.Empty)
                                                        })
                                                        .MergeTable()
                                                        .GroupBy(e => e.EngineDataID)
                                                        .Select(e => new
                                                        {
                                                            e.EngineDataID,
                                                            中文名称 = SqlFunc.AggregateMax(e.中文名称),
                                                            英文名称 = SqlFunc.AggregateMax(e.英文名称),
                                                            设备单元=SqlFunc.AggregateMax(e.设备单元),
                                                            甲板号 = SqlFunc.AggregateMax(e.甲板号),
                                                            房间号 = SqlFunc.AggregateMax(e.房间号),
                                                            肋位号= SqlFunc.AggregateMax(e.肋位号)
                                                        }),
                                                        (eep, ee, eo, edf, edc, edp) => eep.EngineDataID == edp.EngineDataID
                                                    )
                                                    .LeftJoin(subQuery, (eep, ee, eo, edf, edc, edp,dde)=> edp.甲板号 == dde.DataItemName)
                                                    .WhereIF(selectModel == 0, (eep, ee, eo, edf, edc, edp, dde) => !eo.FullPathCN.EndsWith("电缆") && !eo.FullPathCN.EndsWith("图框") && !eo.FullPathCN.EndsWith("基点") && !eo.FullPathCN.EndsWith("OPC") && eep.DeleteFlg == 0)
                                                    .WhereIF(selectModel == 1, (eep, ee, eo, edf, edc, edp, dde) => !eo.FullPathCN.EndsWith("电缆") && !eo.FullPathCN.EndsWith("图框") && !eo.FullPathCN.EndsWith("基点") && !eo.FullPathCN.EndsWith("OPC") && dwgIdCos.Contains(eep.DrawingFileID) && eep.DeleteFlg == 0)
                                                    .GroupBy((eep, ee, eo, edf, edc, edp, dde) => new
                                                    {
                                                        edc.DrawingCatalogueNO,
                                                        edf.DrawingFileName,
                                                        ee.TagNumber,
                                                        edp.中文名称,
                                                        edp.英文名称,
                                                        edp.设备单元,
                                                        edp.甲板号,
                                                        dde.DataItemCode,
                                                        edp.房间号,
                                                        edp.肋位号,
                                                        eo.ObjectTypeName
                                                    })
                                                    .Select((eep, ee, eo, edf, edc, edp, dde) => new
                                                    {
                                                        edc.DrawingCatalogueNO,
                                                        edf.DrawingFileName,
                                                        ee.TagNumber,
                                                        edp.中文名称,
                                                        edp.英文名称,
                                                        edp.设备单元,
                                                        edp.甲板号,
                                                        dde.DataItemCode,
                                                        edp.房间号,
                                                        edp.肋位号,
                                                        eo.ObjectTypeName
                                                    }))
                                        .GroupBy(e => new
                                        {
                                            e.TagNumber,
                                            e.中文名称,
                                            e.英文名称,
                                            e.设备单元,
                                            e.甲板号,
                                            e.DataItemCode,
                                            e.房间号,
                                            e.肋位号,
                                            e.ObjectTypeName
                                        }
                                        )
                                        .Select(e => new {
                                            图号 = SqlFunc.MappingColumn<string>("GROUP_CONCAT(DrawingCatalogueNO separator ',')"),
                                            图名 = SqlFunc.MappingColumn<string>("GROUP_CONCAT(DrawingFileName separator ',')"),
                                            e.TagNumber,
                                            e.中文名称,
                                            e.英文名称,
                                            e.设备单元,
                                            e.甲板号,
                                            e.DataItemCode,
                                            e.房间号,
                                            e.肋位号,
                                            e.ObjectTypeName
                                        })
                                        .ToList();
                                    
                                    //照明综合图纸里面的电力分电箱特殊处理
                                    var equipmentFiliter = Equipments
                                        .GroupBy(x => new
                                            { 
                                                x.图号,
                                                x.图名,
                                                newtag= (x.图名.Equals("照明综合图纸.dwg")&&x.ObjectTypeName.Equals("电力分电箱"))?
                                                Regex.Match(x.TagNumber, @"(\d+)(L|EL)").Value:x.TagNumber,
                                                x.中文名称,
                                                x.英文名称,
                                                x.设备单元,
                                                x.甲板号,
                                                x.DataItemCode,
                                                x.房间号,
                                                x.肋位号,
                                                x.ObjectTypeName
                                            })
                                         .Select(group => new
                                         {
                                             group.Key.图号,
                                             group.Key.图名,
                                             group.Key.newtag,
                                             group.Key.中文名称,
                                             group.Key.英文名称,
                                             group.Key.设备单元,
                                             group.Key.甲板号,
                                             group.Key.DataItemCode,
                                             group.Key.房间号,
                                             group.Key.肋位号
                                         })
                                        .ToList();

                                    #endregion
                                    int EquipCurRow = 1;
                                    int EquiSequenceNo = 1;
                                    foreach (var Equipment in equipmentFiliter)
                                    {
                                        try
                                        {
                                            rowEquipment = sheetEquipments.CreateRow(EquipCurRow++);
                                            rowEquipment.CreateCell(0).SetCellValue(EquiSequenceNo++);
                                            rowEquipment.CreateCell(1).SetCellValue(Equipment.图号);
                                            rowEquipment.CreateCell(2).SetCellValue(Equipment.图名);
                                            rowEquipment.CreateCell(3).SetCellValue(string.Empty);
                                            rowEquipment.CreateCell(4).SetCellValue(string.Empty);
                                            rowEquipment.CreateCell(5).SetCellValue(string.Empty);
                                            rowEquipment.CreateCell(6).SetCellValue(Equipment.newtag);
                                            rowEquipment.CreateCell(7).SetCellValue(Equipment.中文名称);
                                            rowEquipment.CreateCell(8).SetCellValue(Equipment.英文名称);
                                            rowEquipment.CreateCell(9).SetCellValue(Equipment.设备单元);
                                            rowEquipment.CreateCell(10).SetCellValue(Equipment.甲板号);
                                            rowEquipment.CreateCell(11).SetCellValue(Equipment.DataItemCode);
                                            rowEquipment.CreateCell(12).SetCellValue(Equipment.房间号);
                                            rowEquipment.CreateCell(13).SetCellValue(Equipment.肋位号);
                                        }
                                        catch (Exception ex)
                                        {
                                            log4net.LogManager.GetLogger("ERROR").Error("导出设备清册 - " + ex.Message + ex.StackTrace);
                                            continue;
                                        }

                                    }
                                    #endregion
                                    break;
                                default:
                                    break;
                            }
                            string filename = reportFileName + DateTime.Now.ToString("yyMMddHHmmss");
                            ExcelHelper.DownloadIWorkbook(workbook, filename, annexesFile.F_FileExtensions);

                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message + ex.StackTrace);
                            throw;
                        }
                    }
                    else
                    {
                        throw new Exception($"服务器中找不到文件{filePath}");
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
  
        public class MarkInfo
        {
            public string DrawingNo { get; set; }
            public string DrawingFileName { get; set; }
            public string PageNo { get; set; }
            public string CableNo { get; set; }
            public int IsMaterial { get; set; }
            public string Remark { get; set; }
            public string Type { get; set; }
            public DateTime? CreateTime { get; set; }
            public string CreateUserId { get; set; }
            public int IsProcess { get; set; }
            public string RelDrawingFileID { get; set; }
            public DateTime? ExtractDate { get; set; }
        }

        public class ec_enginedataEntity2
        {
            #region 实体成员
            /// <summary>
            /// 工程数据ID
            /// </summary>
            [SugarColumn(IsPrimaryKey = true)]
            public string EngineDataID { get; set; }
            /// <summary>
            /// 位号
            /// </summary>
            public string TagNumber { get; set; } = "";
            /// <summary>
            /// 对象类型ID。<see cref="ec_objecttypeEntity.ObjectTypeID"/>"/>
            /// </summary>
            public string ObjectTypeID { get; set; } = "";

            /// <summary>
            /// 查询时，为该位号当前激活的case。
            /// 更新提交时，为该位号需要修改的case。<see cref="ec_CaseEntity.CaseID"/>
            /// </summary>
            public string CaseID { get; set; } = "0";
            /// <summary>
            /// 数据状态
            /// </summary>
            public string DataStatus { get; set; } = "";
            /// <summary>
            /// 流水号
            /// </summary>
            /// <returns></returns>
            public int? SerialNumber { get; set; }
            /// <summary>
            /// 创建人
            /// </summary>
            public string CreateUserID { get; set; }
            /// <summary>
            /// 创建时间
            /// </summary>
            public DateTime? CreateTime { get; set; }
            /// <summary>
            /// 更新人
            /// </summary>
            public string UpdateUserID { get; set; }
            /// <summary>
            /// 更新时间
            /// </summary>
            public DateTime? UpdateTime { get; set; }

            /// <summary>
            /// 是否被锁
            /// 0 AND 1
            /// </summary>
            public string Locked { get; set; } = "0";
            #endregion
        }
        public class ec_objecttypeEntity2
        {
            #region 实体成员
            /// <summary>
            /// 对象类型ID
            /// </summary>
            /// <returns></returns>
            [SugarColumn(IsPrimaryKey = true)]
            public string ObjectTypeID { get; set; }
            /// <summary>
            /// 上级对象类型ID。<see cref="ObjectTypeID"/>"/>
            /// </summary>
            /// <returns></returns>
            public string UpObjectTypeID { get; set; } = "";
            /// <summary>
            /// 默认的布置图的图例
            /// </summary>
            /// <returns></returns>
            public string DefaultLayoutLibFileID { get; set; } = "";

            /// <summary> 
            /// 特殊类型
            /// </summary> 
            /// <returns></returns>  
            public specialType specialType { get; set; }
            /// <summary>
            /// 对象类型名称
            /// </summary>
            /// <returns></returns>
            public string ObjectTypeName { get; set; } = "";
            /// <summary>
            /// 对象类型名称(英文)
            /// </summary>
            /// <returns></returns>
            public string ObjectTypeNameEN { get; set; } = "";
            /// <summary>
            /// 是否生成流水号
            /// </summary>
            /// <returns></returns>
            public int? IsSerialNumber { get; set; }

            /// <summary>
            /// 是否是系统内置的关键类型（如基点、OPC、内部开关、图框等）。
            /// 1为是。其他为否。
            /// </summary>
            /// <returns></returns>
            public int? IsOOTB { get; set; }



            /// <summary>
            /// 排序
            /// </summary>
            /// <returns></returns>
            public int? OrderID { get; set; }
            /// <summary>
            /// 完整路径
            /// </summary>
            /// <returns></returns>
            public string FullPath { get; set; } = "";
            /// <summary>
            /// 完整路径(中文)
            /// </summary>
            /// <returns></returns>
            public string FullPathCN { get; set; } = "";
            /// <summary>
            /// 创建人
            /// </summary>
            /// <returns></returns>
            public string CreateUserID { get; set; }
            /// <summary>
            /// 创建时间
            /// </summary>
            /// <returns></returns>
            public DateTime? CreateTime { get; set; }
            /// <summary>
            /// 更新人
            /// </summary>
            /// <returns></returns>
            public string UpdateUserID { get; set; }
            /// <summary>
            /// 更新时间
            /// </summary>
            /// <returns></returns>
            public DateTime? UpdateTime { get; set; }
            #endregion
        }
        /// <summary>
        /// 根据图纸ID抽取图纸名称
        /// </summary>
        /// <param name="strDwgFileID">图纸ID</param>
        /// <param name="drawingfileEntityTableName">有项目号的表</param>
        /// <returns>图纸名称</returns>
        public string GetDrawingFileName(string strDwgFileID, string drawingfileEntityTableName)
        {
            try
            {
                if (strDwgFileID.IsEmpty())
                {
                    return string.Empty;
                }
                string strDwgFileName = SqlSugarHelper.Db.Queryable<ec_drawing_fileEntity>().AS(drawingfileEntityTableName)
                    .Where(x => x.DrawingFileID.Equals(strDwgFileID))
                    .Select(x => x.DrawingFileName)
                    .First();
                return strDwgFileName;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                throw;
            }
        }

        public void updateExtractDate(string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                var ProjectEntity = new ec_projectBLL().GetEntity(ProjectId);
                if (string.IsNullOrWhiteSpace(ProjectId))
                {

                }
                else
                {
                    _drawingSynRepository.AsUpdateable()
                        .SetColumns(x => new ec_drawing_synEntity { ExtractDate = Time.MySqlTime })
                        .Where(b => b.cloud != string.Empty && b.cloud != null && b.ExtractDate == null)
                        .AS($"ec_drawing_syn_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                Console.WriteLine(ex.Message + ex.StackTrace);
                throw;
            }
        }

        #endregion
    }
}
