using DocumentFormat.OpenXml.ExtendedProperties;
using DocumentFormat.OpenXml.Spreadsheet;
using Learun.Application.Base.SystemModule;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.SqlSugar;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Windows.Interop;

namespace Learun.Application.Web.Areas.ZZDT_EC.Controllers
{

    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-02-24 11:10
    /// 描 述：对象类型
    /// </summary>
    public class ec_objecttypeController : MvcControllerBase
    {
        const string sheetName4enum = "隐藏的下拉菜单";
        private ec_objecttypeIBLL ec_objecttypeIBLL = new ec_objecttypeBLL();

        #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 BatchSelctIndex()
        {
            return View();
        }
        #endregion

        #region 获取数据

        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetList(string queryJson)
        {
            var data = ec_objecttypeIBLL.GetList(queryJson, null, true);
            return Success(data);
        }
        /// <summary>
        /// 获取列表分页数据
        /// <param name="pagination">分页参数</param>
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPageList(string pagination, string queryJson)
        {
            Pagination paginationobj = pagination.ToObject<Pagination>();
            var data = ec_objecttypeIBLL.GetList(queryJson, paginationobj);
            var jsonData = new
            {
                rows = data,
                total = paginationobj.total,
                page = paginationobj.page,
                records = paginationobj.records
            };
            return Success(jsonData);
        }
        /// <summary>
        /// 获取表单数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetFormData(string keyValue, string ProjectId)
        {
            var data = ec_objecttypeIBLL.GetEntity(keyValue, ProjectId);
            var jsonData = new
            {
                ec_objecttype = data
            };
            return Success(jsonData);
        }



        /// <summary>
        /// 获取对象类型目录树形数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetTreeData(string ProjectId, bool isShowCheck, string ObjectTypeID)
        {
            string queryJson = "{\"ProjectId\":\"" + ProjectId + "\",\"CurObjectTypeID\":\"" + ObjectTypeID + "\"}";
            var list = ec_objecttypeIBLL.GetList(queryJson);

            List<TreeModel> treeList = new List<TreeModel>();
            foreach (var item in list)
            {
                TreeModel node = new TreeModel();
                node.id = item.ObjectTypeID;
                node.text = item.ObjectTypeName;
                node.value = item.ObjectTypeID;
                node.showcheck = isShowCheck;
                node.checkstate = 0;
                node.isexpand = false;
                node.parentId = item.UpObjectTypeID;
                node.NodeExtData = item;
                treeList.Add(node);
            }
            var res = treeList.ToTree();
            return Success(res);
        }
        /// <summary>
        /// 获取对象类型目录树形数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetTreeDataByFilter(string ProjectId, bool isShowCheck, string ObjectTypeName, string TagNumber)
        {
            string queryJson = "{\"ProjectId\":\"" + ProjectId + "\",\"ObjectTypeName\":\"" + ObjectTypeName + "\",\"TagNumber\":\"" + TagNumber + "\"}";
            var list = ec_objecttypeIBLL.GetTree(queryJson);

            List<TreeModel> treeList = new List<TreeModel>();
            foreach (var item in list)
            {
                TreeModel node = new TreeModel();
                node.id = item.ObjectTypeID;
                node.text = item.ObjectTypeName;
                node.value = item.ObjectTypeID;
                node.showcheck = isShowCheck;
                node.checkstate = 0;
                node.isexpand = false;
                node.parentId = item.UpObjectTypeID;
                node.NodeExtData = item;
                treeList.Add(node);
            }
            var res = treeList.ToTree();
            return Success(res);
        }
        /// <summary>
        /// 判断是否在工程数据表已存在数据 
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult IsHaveEngineData(string ProjectId, string objectTypeID)
        {
            bool IsHaveData = false;
            var data = new ec_enginedataBLL().GetList("{ProjectId:\"" + ProjectId + "\",FullPath:\"" + objectTypeID + "\"}").ToList();
            if (data != null && data.Count > 0)
            {
                IsHaveData = true;
            }
            return Success(IsHaveData);
        }
        #endregion

        #region 提交数据
        /// <summary>下
        /// 导出Excel
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="IsExportData">数据库中的数据是否导出</param>
        /// <param name="objectTypeIDs"></param>
        public void ExportPropsIfNeed(string ProjectId)
        {
             
            //创建工作表
            IWorkbook workbook = new XSSFWorkbook();
            //设置样式
            ICellStyle cellstyle = workbook.CreateCellStyle();
            cellstyle.VerticalAlignment = VerticalAlignment.Center;
            cellstyle.Alignment = HorizontalAlignment.Center; 
            //创建sheet页
            ISheet sheet_Preperties = workbook.CreateSheet("属性需求");
            IRow rowProperty = sheet_Preperties.CreateRow(0);
            rowProperty.CreateCell(0).SetCellValue("序号");
            rowProperty.CreateCell(1).SetCellValue("类型分类");
            rowProperty.CreateCell(2).SetCellValue("属性类型");
            rowProperty.CreateCell(3).SetCellValue("属性");
            rowProperty.CreateCell(4).SetCellValue("必填阶段");

            var propertyObjectTypePEntityTableName = ProjectSugar.TableName<ec_objecttypepEntity>(ProjectId);
            var propertyObjectTypeEntityTableName = ProjectSugar.TableName<ec_objecttypeEntity>(ProjectId);
            var propertyEntityTableName = ProjectSugar.TableName<ec_propertyEntity>(ProjectId);

            var queryObjTypeP = SqlSugarHelper.Db.Queryable<ec_objecttypepEntity>().AS(propertyObjectTypePEntityTableName)
                .LeftJoin< ec_objecttypeEntity >((eotep,eote)=>eotep.ObjectTypeID==eote.ObjectTypeID).AS< ec_objecttypeEntity >(propertyObjectTypeEntityTableName)
                .LeftJoin< ec_propertyEntity >((eotep,eote,epe)=>eotep.PropertyID==epe.PropertyID).AS< ec_propertyEntity >(propertyEntityTableName)
                .Where((eotep, eote, epe) => !string.IsNullOrEmpty(eote.FullPathCN))
                .OrderBy((eotep, eote, epe) => new { eote.FullPathCN, eote.ObjectTypeName } , OrderByType.Asc)
                .Select((eotep, eote, epe) => new { 
                    eote.FullPathCN,
                    eote.ObjectTypeName,
                    epe.PropertyName,
                    eotep.IsRequired
                })
                .ToList();

            int PropertyCurRow = 1;
            int PropSequenceNo = 1;
            foreach (var objp in queryObjTypeP)
            {
                try
                {
                    rowProperty = sheet_Preperties.CreateRow(PropertyCurRow++);
                    rowProperty.CreateCell(0).SetCellValue(PropSequenceNo++);
                    rowProperty.CreateCell(1).SetCellValue(objp.FullPathCN);
                    rowProperty.CreateCell(2).SetCellValue(objp.ObjectTypeName);
                    rowProperty.CreateCell(3).SetCellValue(objp.PropertyName);
                    rowProperty.CreateCell(4).SetCellValue(Convert.ToString(objp.IsRequired));
                }
                catch (Exception ex)
                {
                    log4net.LogManager.GetLogger("ERROR").Error("属性必填矩阵 - " + ex.Message + ex.StackTrace);
                    continue;
                }

            }

            string filename = "属性必填矩阵" + DateTime.Now.ToString("yyMMddHHmmss"); 
            ExcelHelper.DownloadIWorkbook(workbook, filename);
        }
        /// <summary>
        /// 批量导入数据
        /// <param name="fileId">文件主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult ImportPropsIfNeed(string fileId, string ProjectId)
        {
            //获取附件信息
            var file = new AnnexesFileBLL().GetByfolderIdEntity(fileId);
            if (string.IsNullOrWhiteSpace(file?.F_FilePath))
            {
                return Fail("服务器中找不到fileId为 " + fileId + " 的文件。");
            }
            var excelFile = new ClosedXML.Excel.XLWorkbook(file.F_FilePath);
            var sheet = excelFile.Worksheets.FirstOrDefault();
            if (sheet != null)
            {
                Console.WriteLine("ImportPropsIfNeed " + sheet.Name);
                var startRow = 6;
                var endRow = sheet.LastRowUsed().RowNumber();
                var startCol = 7;
                var endCol = sheet.LastColumnUsed().ColumnNumber();
                var tbType = ProjectSugar.TableName<ec_objecttypeEntity>(ProjectId);
                var tbProp = ProjectSugar.TableName<ec_propertyEntity>(ProjectId);
                var tbTypeP = ProjectSugar.TableName<ec_objecttypepEntity>(ProjectId);
                var allType = SqlSugarHelper.Db.Queryable<ec_objecttypeEntity>().AS(tbType).ToList();
                var allProp = SqlSugarHelper.Db.Queryable<ec_propertyEntity>().AS(tbProp).ToList();
                var allTypeProp = SqlSugarHelper.Db.Queryable<ec_objecttypepEntity>().AS(tbTypeP).ToList();

                List<ec_objecttypepEntity> needAdd = new List<ec_objecttypepEntity>();
                List<ec_objecttypepEntity> needModify = new List<ec_objecttypepEntity>();
                for (int row = startRow; row < endRow; row++)
                {
                    // 读取 A 列的值，如果为空则获取合并区域第一个单元格的值
                    var cellA = sheet.Cell(row, 1);
                    var dataA = cellA.IsEmpty() ? cellA.MergedRange()?.FirstCell().GetString() : cellA.GetString();

                    // 读取 B 列的值，如果为空则获取合并区域第一个单元格的值
                    var cellB = sheet.Cell(row, 2);
                    var dataB = cellB.IsEmpty() ? cellB.MergedRange()?.FirstCell().GetString() : cellB.GetString();

                    // 读取 C 列的值，如果为空则获取合并区域第一个单元格的值
                    var cellC = sheet.Cell(row, 3);
                    var dataC = cellC.IsEmpty() ? cellC.MergedRange()?.FirstCell().GetString() : cellC.GetString();

                    var TypeFullPath = string.Join("/", new[] { dataA, dataB, dataC });
                    if (TypeFullPath.EndsWith("/"))
                    {
                        TypeFullPath = TypeFullPath.TrimEnd('/');
                    }
                    var matchType = allType.FirstOrDefault(x => x.FullPathCN == TypeFullPath);
                    if (matchType != null)
                    {
                        Console.WriteLine("");
                        //找到匹配的类型后，去匹配属性
                        for (int col = startCol; col < endCol; col++)
                        {
                            var matchProp = allProp.FirstOrDefault(x => x.PropertyName == sheet.Cell(3, col)?.GetString());
                            if (matchProp != null)
                            {
                                var cellValue = sheet.Cell(row, col)?.GetString();
                                //需要设置为必填 
                                var matchLink = allTypeProp.FirstOrDefault(x => x.ObjectTypeID == matchType.ObjectTypeID && x.PropertyID == matchProp.PropertyID);

                                switch (cellValue)
                                {
                                    case "":
                                        if (matchLink != null)
                                        {
                                            matchLink.IsRequired = 0;
                                            needModify.Add(matchLink);
                                        }
                                        break;
                                    case "1":
                                        if (matchLink != null)
                                        {
                                            matchLink.IsRequired = 1;
                                            needModify.Add(matchLink);
                                        }
                                        else
                                        {
                                            var newObj = new ec_objecttypepEntity();
                                            newObj.Create();
                                            newObj.ObjectTypeID = matchType.ObjectTypeID;
                                            newObj.PropertyID = matchProp.PropertyID;
                                            newObj.IsRequired = 1;
                                            needAdd.Add(newObj);
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }


                        SqlSugarHelper.Db.Insertable<ec_objecttypepEntity>(needAdd).AS(tbTypeP).ExecuteCommand();
                        SqlSugarHelper.Db.Updateable<ec_objecttypepEntity>(needModify).AS(tbTypeP).ExecuteCommand();
                    }
                }


            }
            else
            {
                return Fail("上传的excel中没有sheet ");
            }
            return Success("批量导入数据成功！");
        }


        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteForm(string keyValue, string ProjectId)
        {
            ec_objecttypeIBLL.DeleteEntity(keyValue, ProjectId);
            return Success("删除成功！");
        }
        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string keyValue, string strEntity, string ProjectId)
        {
            ec_objecttypeEntity entity = strEntity.ToObject<ec_objecttypeEntity>();

            ec_objecttypeIBLL.SaveEntity(keyValue, entity, ProjectId);
            return Success("保存成功！");
        }
        #endregion

        #region  导入导出Excel
        public class codelists
        {
            public string EnumData { get; set; }
            public string EnumDataCode { get; set; }
        }
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="IsExportData">数据库中的数据是否导出</param>
        /// <param name="objectTypeIDs"></param>
        /// <param name="dwgIds">图纸范围,IsExportData为真时才有意义</param>
        public void ExportToExcel(string ProjectId, bool IsExportData, string objectTypeIDs, string TagNumber,string dwgIds)
        {
            //获取要导出的属性数据
            var exportPropData = new ec_objecttypepBLL().GetObjectTypePById(objectTypeIDs, ProjectId, true).ToList();
            var dt = ExcelHelper.ListToDataTable(exportPropData);
            //获取要导出的对象类型数据
            var exportObjData = ec_objecttypeIBLL.GetList("{ObjectTypeIDs:\"" + objectTypeIDs + "\",ProjectId:\"" + ProjectId + "\"}");
            //获取所有的计量单位数据
            var measuringUnitData = new ec_measuring_unitBLL().GetList("{ ProjectId:\"" + ProjectId + "\"}").ToList();
            //用来获取要合并的列
            string propertyGroupName = "";
            int stratindex = 1;
            int endindex = 0;
            int propindex = 1;
            //创建工作表
            IWorkbook workbook = new XSSFWorkbook();
            //设置样式
            ICellStyle cellstyle = workbook.CreateCellStyle();
            cellstyle.VerticalAlignment = VerticalAlignment.Center;
            cellstyle.Alignment = HorizontalAlignment.Center;
            #region 处理隐藏sheet，专门用于提供下拉
            //创建sheet页
            ISheet sheet_codelist = workbook.CreateSheet(sheetName4enum) as ISheet;
            //隐藏sheet
            workbook.SetSheetHidden(workbook.GetSheetIndex(sheet_codelist), SheetState.Hidden);
            int row_idx = 0;//当前这个枚举在哪列
            Dictionary<string, string> rangeNames4Enum = new Dictionary<string, string>();
            foreach (var item in exportPropData.Where(x => x.PropertyType == "00003" && !string.IsNullOrEmpty(x.EnumDataCode)).Select(it => new { it.EnumData, it.EnumDataCode }).Distinct())
            {
                //枚举都丢到一个独立的表里
                IRow row_ListName = sheet_codelist.CreateRow(row_idx);

                row_ListName.CreateCell(0).SetCellValue(item.EnumData);//数据字典的名字（如 电缆规格）
                string[] enumDatas = item.EnumDataCode.Split(',');
                for (int i = 0; i < enumDatas.Length; i++)
                {
                    row_ListName.CreateCell(i + 1).SetCellValue(enumDatas[i]);
                }



                var rangeName = "Range" + 1 + row_idx;//定义一个名称，指向刚才创建的下拉项的区域：(不能用数据字典本身的名字，否则有/ %这些字符就不行)
                IName range = workbook.CreateName();
                range.RefersToFormula = sheet_codelist.SheetName + $"!$B${1 + row_idx}:${GetColumnChar(1 + enumDatas.Length)}${1 + row_idx}";
                range.NameName = rangeName;

                rangeNames4Enum.Add(item.EnumData, rangeName);
                row_idx++;
            }
            workbook.SetSheetHidden(workbook.GetSheetIndex(sheet_codelist), SheetState.Hidden);
            #endregion
            #region Task 6908
            var pixelTbName = ProjectSugar.TableName<ec_enginedata_pixelEntity>(ProjectId);
            var TagIdOnDwg = SqlSugarHelper.Db.Queryable<ec_enginedata_pixelEntity>().AS(pixelTbName).Where(x => dwgIds.Split(',').Contains(x.DrawingFileID)).Select(x => x.EngineDataID).Distinct().ToList();
            #endregion
            var engineDatas = new ec_enginedataBLL().GetList("{ProjectId:\"" + ProjectId + "\",ObjectTypeIDs:\"" + objectTypeIDs + "\",TagNumberFilter:\"" + TagNumber + "\"}").ToList();
            if (IsExportData)
            {
                engineDatas = engineDatas.Where(x => TagIdOnDwg.Contains(x.EngineDataID)).ToList();
            }
            var engineDataIDs = string.Join(",", engineDatas.Select(x => x.EngineDataID).Distinct());

            var engineDataPropAlls = new ec_enginedata_propertyBLL().GetEnginePropById(ProjectId, engineDataIDs).ToList();

            foreach (var item in exportObjData)
            {
                //创建sheet页
                ISheet sheet = workbook.CreateSheet(item.ObjectTypeName) as ISheet;
                //创建第一行  并赋值
                IRow row = sheet.CreateRow(0);
                row.CreateCell(0).SetCellValue("对象类型");
                row.CreateCell(1).SetCellValue(item.FullPathCN);
                //创建第2、3行  并赋值
                IRow row1 = sheet.CreateRow(1);
                IRow row2 = sheet.CreateRow(2);
                IRow row3 = sheet.CreateRow(3);
                row1.CreateCell(0).SetCellValue("位号");
                row2.CreateCell(0).SetCellValue("位号");
                //合并单元格
                sheet.AddMergedRegion(new CellRangeAddress(1, 3, 0, 0));
                //当前对象类型对应的属性数据
                var propDataById = exportPropData.FindAll(x => x.ObjectTypeID == item.ObjectTypeID);
                stratindex = 1;
                endindex = 0;
                propindex = 1;
                propertyGroupName = "";
                IDataValidationHelper helper = new XSSFDataValidationHelper((XSSFSheet)sheet);//获得一个数据验证Helper  
                if (propDataById != null && propDataById.Count > 0)
                {
                    //给第二三行的单元格赋值
                    for (var i = 0; i < propDataById.Count; i++)
                    {
                        if (propertyGroupName != propDataById[i].PropertyGroupName)
                        {
                            if (i != 0)
                            {
                                if (stratindex < endindex)
                                {
                                    sheet.AddMergedRegion(new CellRangeAddress(1, 1, stratindex, endindex));
                                }
                                stratindex = endindex + 1;
                            }
                            row1.CreateCell(stratindex).SetCellValue(propDataById[i].PropertyGroupName);
                            propertyGroupName = propDataById[i].PropertyGroupName;
                        }
                        endindex++;
                        if (!string.IsNullOrEmpty(propDataById[i].MeasuringUnitTypeID))
                        {
                            endindex++;
                        }
                        if (i == propDataById.Count - 1)
                        {
                            if (stratindex < endindex)
                            {
                                sheet.AddMergedRegion(new CellRangeAddress(1, 1, stratindex, endindex));
                            }
                        }

                        row2.CreateCell(propindex).SetCellValue(propDataById[i].PropertyName);
                        row3.CreateCell(propindex).SetCellValue("属性值");
                        #region 设置Excel单元格格式
                        CellRangeAddressList regions = new CellRangeAddressList(4, 65535, propindex, propindex);//约束范围：c2到c65535  
                        if (propDataById[i].PropertyType == "00002")
                        {
                            //数字类型
                            string charCol = GetColumnChar(propindex);
                            string listFormula = $"TRUNC({charCol}5,{propDataById[i].DecimalPoint})={charCol}5";
                            var customConstraint = helper.CreateCustomConstraint(listFormula);
                            IDataValidation customValidation = helper.CreateValidation(customConstraint, regions);
                            customValidation.CreateErrorBox("错误", $"只能输入小数点为:{propDataById[i].DecimalPoint}的数字！");
                            customValidation.ShowErrorBox = true;
                            sheet.AddValidationData(customValidation);
                        }
                        //else if (propDataById[i].PropertyType == "00005")
                        //{
                        //    //数字类型
                        //    var numberConstraint = helper.CreateNumericConstraint(ValidationType.DECIMAL, OperatorType.BETWEEN,0.ToString(),100000000000.ToString());
                        //    IDataValidation numberValidation = helper.CreateValidation(numberConstraint, regions);
                        //    numberValidation.CreateErrorBox("错误", $"只能输入数字");
                        //    numberValidation.ShowErrorBox = true;
                        //    sheet.AddValidationData(numberValidation);

                        //}
                        else if (propDataById[i].PropertyType == "00003" && !string.IsNullOrEmpty(propDataById[i].EnumDataCode))
                        {
                            ////枚举类型                                
                            //string[] enumData = propDataById[i].EnumDataCode.Split(',');
                            //IDataValidation validation = helper.CreateValidation(helper.CreateExplicitListConstraint(enumData), regions);//创建约束
                            //validation.CreateErrorBox("错误", "请按右侧下拉箭头选择!");//不符合约束时的提示  
                            //validation.ShowErrorBox = true;//显示上面提示 = True  
                            //sheet.AddValidationData(validation);//添加进去 

                            //枚举类型（超过255，用一个sheet单独存放）   
                            var constraint = helper.CreateFormulaListConstraint(rangeNames4Enum[propDataById[i].EnumData]);
                            // 关联上面的Name的名称
                            var validation = helper.CreateValidation(constraint, regions);
                            validation.CreateErrorBox("错误", "请按右侧下拉箭头选择!");//不符合约束时的提示  
                            validation.ShowErrorBox = true;//显示上面提示 = True 
                            sheet.AddValidationData(validation);//添加进去 
                        }
                        if (!string.IsNullOrEmpty(propDataById[i].MeasuringUnitTypeID))
                        {
                            CellRangeAddressList regions1 = new CellRangeAddressList(4, 65535, propindex + 1, propindex + 1);//约束范围：c2到c65535 
                            string[] unitNameData = measuringUnitData.FindAll(m => m.MeasuringUnitTypeID == propDataById[i].MeasuringUnitTypeID).Select(n => n.MeasuringUnitName).ToArray();
                            IDataValidation validation = helper.CreateValidation(helper.CreateExplicitListConstraint(unitNameData), regions1);//创建约束
                            validation.CreateErrorBox("错误", "请按右侧下拉箭头选择!");//不符合约束时的提示  
                            validation.ShowErrorBox = true;//显示上面提示 = True  
                            sheet.AddValidationData(validation);//添加进去 
                        }
                        #endregion
                        if (!string.IsNullOrEmpty(propDataById[i].MeasuringUnitTypeID))
                        {
                            propindex++;
                            row3.CreateCell(propindex).SetCellValue("属性单位");
                            sheet.AddMergedRegion(new CellRangeAddress(2, 2, propindex - 1, propindex));
                        }
                        propindex++;
                    }
                    if (endindex > 1)
                    {
                        sheet.AddMergedRegion(new CellRangeAddress(0, 0, 1, endindex));
                    }
                }
                if (IsExportData)
                {
                    //获取当前项目的工程数据
                    //var engineData = new ec_enginedataBLL().GetList("{ProjectId:\"" + ProjectId + "\",ObjectTypeID:\"" + item.ObjectTypeID + "\",TagNumberFilter:\"" + TagNumber + "\"}").ToList();

                    //List<string> listEngineDataID = engineData.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();
                    var engineData = engineDatas.Where(x => x.ObjectTypeID == item.ObjectTypeID).ToList();
                    var IDs = engineData.Select(x => x.EngineDataID).Distinct();
                    var engineDataPropAll = engineDataPropAlls.Where(x => IDs.Contains(x.EngineDataID)).ToList();
                    //获取第三行的值
                    IRow rowValue = sheet.GetRow(2);
                    int rowIndex = 0;
                    var propName = "";
                    var tempEngineDataProp = new ec_enginedata_propertyEntity();


                    // 创建单元格样式
                    ICellStyle style = workbook.CreateCellStyle();



                    //当前对象类型对应的工程数据
                    foreach (var itemengineData in engineData)
                    {
                        //是否锁

                        //获取当前工程数据属性
                        var engineDataProp = engineDataPropAll.FindAll(m => m.EngineDataID == itemengineData.EngineDataID).ToList();
                        //创建行  并赋值
                        IRow rowByIndex = sheet.CreateRow(rowIndex + 4);
                        for (int k = 0; k < rowValue.LastCellNum; k++)
                        {
                            //获取每个单元格
                            if (k == 0)
                            {
                                rowByIndex.CreateCell(0).SetCellValue(itemengineData.TagNumber);
                                if (itemengineData.Locked == "1")
                                {
                                }
                            }
                            else
                            {
                                if (rowValue == null || rowValue.GetCell(k) == null || string.IsNullOrEmpty(rowValue.GetCell(k).ToString()))
                                {
                                    if (sheet.GetRow(3) == null || sheet.GetRow(3).GetCell(k) == null || string.IsNullOrEmpty(sheet.GetRow(3).GetCell(k).ToString()))
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        //判断属性是否设置了单位  设置了单位就赋值
                                        if (!string.IsNullOrEmpty(tempEngineDataProp?.MeasuringUnit))
                                        {
                                            rowByIndex.CreateCell(k).SetCellValue(tempEngineDataProp.MeasuringUnit);
                                        }
                                        else
                                        {
                                            var tempProp = propDataById.FirstOrDefault(x => x.PropertyName == propName);
                                            if (!string.IsNullOrEmpty(tempProp?.DefaultUnitName))
                                            {
                                                rowByIndex.CreateCell(k).SetCellValue(tempProp.DefaultUnitName);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    propName = rowValue.GetCell(k).ToString();
                                    tempEngineDataProp = engineDataProp.Find(x => x.PropertyName == propName);
                                    //给属性值的单元格赋值
                                    rowByIndex.CreateCell(k).SetCellValue(tempEngineDataProp?.PropertyValue);
                                }
                            }
                        }
                        rowIndex++;
                    }
                }

                ExcelHelper.SetColumnWidth(dt, sheet, cellstyle);
            }
            string filename = "工程数据模板导出" + DateTime.Now.ToString("yyMMddHHmmss");
            workbook.SetSheetHidden(workbook.GetSheetIndex(sheet_codelist), SheetState.Hidden);
            ExcelHelper.DownloadIWorkbook(workbook, filename);
        }

        #region 数字转为Excel列名
        /// <summary>
        /// 数字转为Excel列名
        /// </summary>
        /// <param name="col"></param>
        /// <returns></returns>
        private string GetColumnChar(int col)
        {
            int a = col / 26;
            int b = col % 26;

            if (a > 0)
            {
                return GetColumnChar(a - 1) + (char)(b + 65); //ASCII A->65
            }

            return ((char)(b + 65)).ToString();
        }
        #endregion

        /// <summary>
        /// 读取excel，然后批量导入工程位号数据
        /// </summary>
        /// <param name="fileId">文件主键</param>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult MuliteImport(string fileId, string ProjectId)
        {
            string msg = "";
            //获取附件信息
            var file = new AnnexesFileBLL().GetByfolderIdEntity(fileId);
            if (string.IsNullOrWhiteSpace(file?.F_FilePath))
            {
                return Fail(msg);
            }
            List<ec_enginedataEntity> listEngineData;
            //读取文件，并转换为流
            using (FileStream fs = new FileStream(file.F_FilePath, FileMode.Open, FileAccess.Read))
            {
                ExcelImport(fs, file.F_FileExtensions, out listEngineData);
                fs.Close();
            }
            if (listEngineData == null || listEngineData.Count == 0)
            {
                return Fail("请上传有位号数据的Excel！");
            }
            //获取当前项目的所有工程数据
            var allEngineData = new ec_enginedataBLL().GetList("{ProjectId:\"" + ProjectId + "\"}").ToList();
            //获取当前项目的所有属性数据
            var allPropData = new ec_objecttypepBLL().GetObjectTypePById("", ProjectId, true).ToList();
            //获取当前项目的所有对象类型数据
            var allObjectData = new ec_objecttypeBLL().GetList("{ProjectId:\"" + ProjectId + "\"}").ToList();
            //如果位号存在就只更新属性数据  不存在就新增工程数据和工程数据属性
            //如果属性不不存在，则返回提示信息(位号XXX，XXX、XXX、XXX属性没有配置)。
            foreach (var item in listEngineData)
            {
                var temEngineData = allEngineData.Find(x => x.TagNumber.ToUpper() == item.TagNumber.ToUpper());
                if (temEngineData != null)
                {
                    //用来区别是新增还是编辑

                    item.EngineDataID = temEngineData.EngineDataID;
                    item.CaseID = temEngineData.CaseID;
                    item.DataStatus = temEngineData.DataStatus;
                    item.CreateUserID = temEngineData.CreateUserID;
                    item.CreateTime = temEngineData.CreateTime;
                    item.SerialNumber = temEngineData.SerialNumber;
                    item.Locked = temEngineData.Locked;
                }
                var temObjectData = allObjectData.Find(x => x.FullPathCN == item.FullPathCN);
                item.ObjectTypeID = temObjectData?.ObjectTypeID;
                item.TagNumber = item.TagNumber?.ToUpper(); // task 6164
                //获取当前位号配置的属性
                var temProp = allPropData.FindAll(x => x.ObjectTypeID == item.ObjectTypeID);
                foreach (var it in item.EngineDataProperty)
                {
                    var temEngineProp = temProp.FindAll(x => x.PropertyName == it.PropertyName);
                    if (temEngineProp == null || temEngineProp.Count == 0)
                    {
                        msg = "位号" + item.TagNumber + "," + it.PropertyName + "属性没有配置";
                        return Fail(msg);
                    }
                }

                //用来判断是否需要记录流水号
                if (temObjectData?.IsSerialNumber == 1)
                {
                    //截取位号后面的数字作为流水号
                    if (!string.IsNullOrEmpty(temObjectData.ObjectTypeNameEN))
                    {
                        string strSerialNumber = item.TagNumber.Replace(temObjectData.ObjectTypeNameEN, "").Trim();
                        if (IsInteger(strSerialNumber))
                        {
                            item.SerialNumber = strSerialNumber.ToInt();
                        }
                        else
                        {
                            item.SerialNumber = 0;
                        }
                    }
                }

            }
            new ec_enginedataBLL().SaveImportData(listEngineData, ProjectId);
            if (string.IsNullOrEmpty(msg))
            {
                return Success("批量导入数据成功！");
            }
            else
            {
                return Fail(msg);
            }

        }


        /// <summary>
        /// 读取excel，然后批量更新CheckIsRequiredPropsByDrawing后的结果 
        /// </summary>
        /// <param name="fileId">文件主键</param>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult PropertyCheckResImport(string fileId, string ProjectId)
        {
            string msg = "";
            //获取附件信息
            var file = new AnnexesFileBLL().GetByfolderIdEntity(fileId);
            if (string.IsNullOrWhiteSpace(file?.F_FilePath))
            {
                return Fail(msg);
            }
            List<ec_enginedataEntity> listEngineData;
            //读取文件，并转换为流
            using (FileStream fs = new FileStream(file.F_FilePath, FileMode.Open, FileAccess.Read))
            {
                ExcelImport2(fs, file.F_FileExtensions, out listEngineData);
                fs.Close();
            }
            if (listEngineData == null || listEngineData.Count == 0)
            {
                return Fail("请上传有位号数据的Excel！");
            }
            //获取当前项目的所有工程数据
            var allEngineData = new ec_enginedataBLL().GetList("{ProjectId:\"" + ProjectId + "\"}").ToList();
            ////获取当前项目的所有属性数据
            //var allPropData = new ec_objecttypepBLL().GetObjectTypePById("", ProjectId, true).ToList();
            ////获取当前项目的所有对象类型数据
            //var allObjectData = new ec_objecttypeBLL().GetList("{ProjectId:\"" + ProjectId + "\"}").ToList();
            //如果位号存在就只更新属性数据  不存在就新增工程数据和工程数据属性
            //如果属性不不存在，则返回提示信息(位号XXX，XXX、XXX、XXX属性没有配置)。
            foreach (var item in listEngineData)
            {
                var temEngineData = allEngineData.Find(x => x.TagNumber.ToUpper() == item.TagNumber.ToUpper());
                if (temEngineData != null )
                {
                    //用来区别是新增还是编辑

                    item.EngineDataID = temEngineData.EngineDataID;
                    item.CaseID = temEngineData.CaseID;
                    item.DataStatus = temEngineData.DataStatus;
                    item.CreateUserID = temEngineData.CreateUserID;
                    item.CreateTime = temEngineData.CreateTime;
                    item.SerialNumber = temEngineData.SerialNumber;
                    item.Locked = temEngineData.Locked;
                }
                else
                {
                    continue; // insertion is not allowed
                }
                
                //var temObjectData = allObjectData.Find(x => x.FullPathCN == item.FullPathCN);
                item.ObjectTypeID = temEngineData?.ObjectTypeID;
                item.TagNumber = item.TagNumber?.ToUpper(); // task 6164
               
                 

            }
            new ec_enginedataBLL().SaveImportData(listEngineData, ProjectId);
            if (string.IsNullOrEmpty(msg))
            {
                return Success("批量导入数据成功！");
            }
            else
            {
                return Fail(msg);
            }

        }

        /// <summary>
        /// 验证字符串是否为整数
        /// </summary>
        /// <param name="value">要验证的字符串</param>    
        public static bool IsInteger(string value)
        {
            //如果为空，认为验证不合格
            if (string.IsNullOrEmpty(value))
            {
                return false;
            }
            return System.Text.RegularExpressions.Regex.IsMatch(value, @"^\d*$");
        }

        /// <summary>
        /// 读取excel里面的数据
        /// </summary>
        /// <param name="fileStream">文件数据流</param>
        /// <param name="flieType">文件后缀</param>
        /// <param name="listEngineData">工程数据</param>
        /// <returns></returns>
        public void ExcelImport(Stream fileStream, string flieType, out List<ec_enginedataEntity> listEngineData)
        {
            listEngineData = new List<ec_enginedataEntity>();
            ISheet sheet = null;
            IWorkbook workbook;
            if (flieType == ".xls")
            {
                workbook = new HSSFWorkbook(fileStream);
            }
            else
            {
                workbook = new XSSFWorkbook(fileStream);
            }
            for (int i = 0; i < workbook.NumberOfSheets; i++)
            {
                //获取每个Sheet表
                sheet = workbook.GetSheetAt(i);
                if (sheet.GetRow(0) == null || sheet.GetRow(0).GetCell(1) == null || string.IsNullOrEmpty(sheet.GetRow(0).GetCell(1).ToString()))
                {
                    continue;//需要确定每个sheet的objecttype
                }
                if (sheet.SheetName == sheetName4enum)
                {
                    continue;
                }
                var propName = "";
                for (int j = 4; j <= sheet.LastRowNum; j++)
                {
                    propName = "";
                    //获取每行
                    ec_enginedataEntity ec_Enginedata = new ec_enginedataEntity();
                    ec_Enginedata.EngineDataProperty = new List<ec_enginedata_propertyEntity>();
                    IRow row = sheet.GetRow(j);
                    //获取位号
                    if (row == null || row.GetCell(0) == null || string.IsNullOrEmpty(row.GetCell(0).ToString()))
                    {
                        continue;
                    }
                    else
                    {
                        ec_Enginedata.TagNumber = row.GetCell(0).ToString();
                        ec_Enginedata.FullPathCN = sheet.GetRow(0).GetCell(1).ToString();
                    }
                    //获取属性
                    for (int k = 1; k < row.LastCellNum; k++)
                    {
                        if (sheet.GetRow(2).GetCell(k) == null || string.IsNullOrEmpty(sheet.GetRow(2).GetCell(k).ToString()))
                        {
                            continue;
                        }
                        else
                        {
                            if (sheet.GetRow(2).GetCell(k).ToString() != propName)
                            {
                                propName = sheet.GetRow(2).GetCell(k).ToString();
                            }
                            else
                            {
                                continue;//相同属性（因为第三行一个属性占了2列，一列是属性，一列是uom）
                            }
                            if (row.GetCell(k) != null && !string.IsNullOrEmpty(row.GetCell(k).ToString()))
                            {
                                ec_enginedata_propertyEntity propertyEntity = new ec_enginedata_propertyEntity();
                                propertyEntity.PropertyName = propName;
                                propertyEntity.PropertyValue = row.GetCell(k).ToString();
                                if (sheet.GetRow(3).GetCell(k + 1) != null && !string.IsNullOrEmpty(sheet.GetRow(3).GetCell(k + 1).ToString()))
                                {
                                    if ((sheet.GetRow(3).GetCell(k + 1).ToString() == "属性单位"))
                                    {
                                        propertyEntity.MeasuringUnit = row.GetCell(k + 1).ToString();
                                    }
                                }
                                ec_Enginedata.EngineDataProperty.Add(propertyEntity);
                            }
                        }
                    }
                    listEngineData.Add(ec_Enginedata);
                }
            }
        }


        /// <summary>
        /// 读取excel里面的数据
        /// </summary>
        /// <param name="fileStream">文件数据流</param>
        /// <param name="flieType">文件后缀</param>
        /// <param name="listEngineData">工程数据</param>
        /// <returns></returns>
        void ExcelImport2(Stream fileStream, string flieType, out List<ec_enginedataEntity> listEngineData)
        {
            listEngineData = new List<ec_enginedataEntity>();
            ISheet sheet = null;
            IWorkbook workbook;
            if (flieType == ".xls")
            {
                workbook = new HSSFWorkbook(fileStream);
            }
            else
            {
                workbook = new XSSFWorkbook(fileStream);
            }
            for (int i = 0; i < workbook.NumberOfSheets; i++)
            {
                //获取每个Sheet表
                sheet = workbook.GetSheetAt(i);
                if (sheet.GetRow(0) == null || sheet.GetRow(0).GetCell(1) == null || string.IsNullOrEmpty(sheet.GetRow(0).GetCell(1).ToString()))
                {
                    continue;//需要确定每个sheet的objecttype
                }
                if (sheet.SheetName == "sheetName4enum")
                {
                    continue;
                }
                var patternSheetName = "^\\d+_[\\w\\u4e00-\\u9fa5]+$";
                if (!Regex.Match(sheet.SheetName, patternSheetName).Success) { 
                    continue; 
                }
                var objectTypeName =sheet.SheetName.Substring(sheet.SheetName.IndexOf('_')+1);
                
                var propName = "";
                for (int j = 1; j <= sheet.LastRowNum; j++)
                {
                    propName = "";
                    //获取每行
                    ec_enginedataEntity ec_Enginedata = new ec_enginedataEntity();
                    ec_Enginedata.EngineDataProperty = new List<ec_enginedata_propertyEntity>();
                    IRow row = sheet.GetRow(j);
                    //获取位号
                    if (row == null || row.GetCell(0) == null || string.IsNullOrEmpty(row.GetCell(0).ToString()))
                    {
                        continue;
                    }
                    else
                    {
                        ec_Enginedata.TagNumber = row.GetCell(0).ToString();
                       //ec_Enginedata.FullPathCN = sheet.GetRow(0).GetCell(1).ToString();
                    }
                    //获取属性
                    for (int k = 1; k < row.LastCellNum; k++)
                    {
                        if (row.GetCell(k) == null || string.IsNullOrEmpty(row.GetCell(k).ToString()))
                        {
                            continue;
                        }
                        else
                        {
                            if (sheet.GetRow(0).GetCell(k) == null || string.IsNullOrEmpty(sheet.GetRow(0).GetCell(k).ToString()))
                            {
                                continue;
                            }
                            else
                            { 
                                propName = sheet.GetRow(0).GetCell(k).ToString();
                            }
                          
                                ec_enginedata_propertyEntity propertyEntity = new ec_enginedata_propertyEntity();
                                propertyEntity.PropertyName = propName;
                                propertyEntity.PropertyValue = row.GetCell(k).ToString();
                                //if (sheet.GetRow(3).GetCell(k + 1) != null && !string.IsNullOrEmpty(sheet.GetRow(3).GetCell(k + 1).ToString()))
                                //{
                                //    if ((sheet.GetRow(3).GetCell(k + 1).ToString() == "属性单位"))
                                //    {
                                //        propertyEntity.MeasuringUnit = row.GetCell(k + 1).ToString();
                                //    }
                                //}
                                ec_Enginedata.EngineDataProperty.Add(propertyEntity);
                            
                        }
                    }
                    listEngineData.Add(ec_Enginedata);
                }
            }
        }

        #endregion

    }
}
