using Learun.Application.Base.SystemModule;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.SqlSugar;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Pipelines.Sockets.Unofficial.Arenas;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;

namespace Learun.Application.Web.Areas.ZZDT_EC.Controllers
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-02-23 11:30
    /// 描 述：属性表
    /// </summary>
    public class ec_Wire_GroupController : MvcControllerBase
    {
        private ec_Wire_GroupIBLL ec_Wire_GroupIBLL = new ec_Wire_GroupBLL();
        private ec_Wire_Group_TemplateIBLL ec_Wire_Group_TemplateIBLL = new ec_Wire_Group_TemplateBLL();

        #region 视图功能

        /// <summary>
        /// 主页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 主页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ProjectIndex()
        {
            return View();
        }
        /// <summary>
        /// 表单页
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Form()
        {
            return View();
        }
        /// <summary>
        /// 选择模板
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult SelectTemplate()
        {
            return View();
        }
        /// <summary>
        /// 成品导出
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ExportTemplate()
        {
            return View();
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取左侧树形数据
        /// <summary>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetTree(string ProjectId)
        {
            var data = ec_Wire_GroupIBLL.GetTree(ProjectId);
            return Success(data);
        }
        /// <summary>
        /// 信号列表
        /// </summary> 
        /// <param name="projectId">项目编号</param>
        /// <param name="templateId">模板编号</param>
        /// <param name="wireGroupId">信号编号</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetList(string pagination, string queryJson)
        {
            try
            {
                Pagination paginationobj = pagination.ToObject<Pagination>();
                paginationobj.sidx = "OrderID ";
                paginationobj.sord = "ASC";
                var data = ec_Wire_GroupIBLL.GetList(queryJson, Assigned: false, pagination: paginationobj);
                var jsonData = new
                {
                    rows = data,
                    total = paginationobj.total,
                    page = paginationobj.page,
                    records = paginationobj.records
                };
                return Success(jsonData);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        /// <summary>
        /// 获取页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <param name="engineDataID">工程数据ID</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPageList(string queryJson)
        {
            try
            {
                var res = ec_Wire_GroupIBLL.GetList(queryJson);
                return Success(res);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
            ;
        }
        /// <summary>
        /// 获取页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <param name="engineDataID">工程数据ID</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPageList(string pagination, string queryJson)
        {
            Pagination paginationobj = pagination.ToObject<Pagination>();
            var data = ec_Wire_GroupIBLL.GetList(queryJson, pagination: 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_Wire_GroupIBLL.GetEntity(keyValue, ProjectId);
            var jsonData = new
            {
                ec_Wire_Group = data
            };
            return Success(jsonData);
        }
        /// <summary>
        /// 获取对象类型目录树形数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetTreeData(string ProjectId, bool isShowCheck, string WireGroupTemplateID, string CurWireGroupID)
        {
            string queryJson = "{\"ProjectId\":\"" + ProjectId + "\",\"WireGroupTemplateID\":\"" + WireGroupTemplateID + "\",\"CurWireGroupID\":\"" + CurWireGroupID + "\"}";
            var list = ec_Wire_GroupIBLL.GetList(queryJson);

            List<TreeModel> treeList = new List<TreeModel>();
            foreach (var item in list)
            {
                TreeModel node = new TreeModel();
                node.id = item.Wire_Group_ID;
                node.text = item.Group_Name;
                node.value = item.Wire_Group_ID;
                node.showcheck = isShowCheck;
                node.checkstate = 0;
                node.isexpand = false;
                node.parentId = item.LinkedID;
                node.NodeExtData = item;
                treeList.Add(node);
            }
            var res = treeList.ToTree();
            return Success(res);
        }
        #endregion
        #region 提交数据
        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteForm(string keyValue, string ProjectId)
        {
            var res = ec_Wire_GroupIBLL.DeleteEntity(ProjectId, keyValue, false);
            if (string.IsNullOrEmpty(res))
            {
                return Success("删除成功！");
            }
            else
            {
                return Fail(res);
            }
        }
        /// <summary>
        /// 导入数据（网页）
        /// </summary>
        /// <param name="fileId">文件主键（导入之前会上传文件，在lr base annexesfile表中，创建一行记录。那里会得到Id）</param>
        /// <param name="ProjectId"></param>
        /// <param name="WireGroupTemplateID"></param>
        /// <param name="mode">1时为（只新增），2时为（新增和更新）,3时为（完全）</param>
        /// <param name="version">1,1462;2,8600</param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult ExcelImport(string fileId, string ProjectId, string WireGroupTemplateID, ImportMode mode, int version, string singleColIndex = "")
        {
            try
            {
                var bll = new ec_Wire_GroupBLL(ProjectId);
                string res = "";
                switch (mode)
                {
                    case ImportMode.Create:
                    case ImportMode.CreateUpdate:
                        res = bll.ImportSignals(ProjectId, WireGroupTemplateID, fileId, mode, version);
                        break;
                    case ImportMode.SingleColumn:
                        res = bll.ImportSignals(ProjectId, WireGroupTemplateID, fileId, mode, version, singleColIndex);
                        break;
                    case ImportMode.Full:
                        //24 6 5新增
                        res = bll.ImportSignalsFullMode(ProjectId, WireGroupTemplateID, fileId, mode, version);
                        break;
                    default:
                        break;
                }

                if (!string.IsNullOrEmpty(res))
                {
                    return Fail(res);
                }
                return Success("导入完成");
            }
            catch (Exception e)
            {
                return Fail(e.Message);
            }
        }
        /// <summary>
        /// 导入结果
        /// </summary>
        /// <param name="fileId"></param>
        public void ImportResult(string fileId)
        {
            var file = new AnnexesFileBLL().GetByfolderIdEntity(fileId);
            if (string.IsNullOrWhiteSpace(file?.F_FilePath))
            {
                return;
            }
            FileDownHelper.DownLoad("", file.F_FilePath, $"导入结果{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");
        }
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="DeleteFlg"></param>
        /// <param name="folderId"></param>
        /// <param name="reportFileName"></param>

        public void ExportToExcel(string ProjectId, bool DeleteFlg, string folderId, string reportFileName, string DateFrom, string DateTo)
        {
            //如果网页ui上选择的是 3.3 ~ 3.7
            if (DateFrom.ToLower() == "undefined")//2025-03-03 00:00:00
            {
                DateFrom = "";
            }
            if (DateTo.ToLower() == "undefined")//2025-03-07 23:59:59
            {
                DateTo = "";
            }
            int version = 0;
            byte[] bytes = null;
            switch (reportFileName)
            {
                case "信号清册（1642版）":
                    version = 1;
                    break;
                case "信号清册（8600版）":
                    version = 2;
                    break;
                case "信号修改清单":
                    version = 4;
                    break;
                default:
                    bytes = System.Text.Encoding.UTF8.GetBytes("确保选择的报表名字为：信号清册（1642版）   或     信号清册（8600版）");
                    goto res1;
            }
            var BLL = new ec_Wire_GroupBLL();
            bytes = BLL.ExportSignals(ProjectId, DeleteFlg, version, folderId, DateFrom, DateTo);//web export
        res1:
            var stream = new MemoryStream(bytes);
            FileDownHelper.DownLoad(stream, $"成品导出{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");//网页上导出excel
        }

        /// <summary>
        /// 24 06 27,监测系统生成Excel
        /// 如果网页端下载。可以用这样一套逻辑在html里实现：
        ///var iframeUrl = top.$.rootUrl + '/ZZDT_EC/ec_report_file/ExportToExcel?ProjectId=' + ProjectId + "&folderId=" + folderId + "&reportFileName=" + reportFileName + "&objectTypeIDs=" + objectTypeIDs + "&propertyIDs=" + propertyIDs + "&relTypeIDs=" + relTypeIDs;
        ///learun.loading(true, "生成报表中...");
        ///var body = document.getElementsByTagName("body")[0];
        ///var downloadIframe = document.createElement("iframe");
        ///downloadIframe.setAttribute("src", iframeUrl);
        ///downloadIframe.setAttribute("style", "display:none;")
        ///body.appendChild(downloadIframe);
        ///learun.loading(false);
        ///learun.loading(false);
        ///
        /// 并且接口本身不需要任何post get的定义
        /// </summary>
        /// <param name="ProjId"></param>
        public void IOModuleExportExcel(string ProjId)
        {
            var res = new ec_PanelChannelBLL().IOModuleExportExcel(ProjId);
            var stream = new MemoryStream(res);
            FileDownHelper.DownLoad(stream, $"监测系统分配表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");//网页上导出excel
        }
        /// <summary>
        /// 导入 监控系统表 （不支持panel strip的修改），只支持已有模块下的 signal和cable的关联
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="ProjId"></param>
        /// <returns></returns>
        public ActionResult IOModuleImportExcel(string keyValue, string ProjId)
        {
            //MVC
            //查询文件的真实路径
            var file = new AnnexesFileBLL().GetByfolderIdEntity(keyValue);
            if (string.IsNullOrWhiteSpace(file?.F_FilePath))
            {
                return Fail("找不到文件" + file?.F_FilePath);
            }
            string strFilePath = file?.F_FilePath;//"C:/Users/xingheng/Downloads/数据字典_甲板号_250627210628.xlsx"
            var insertCount = 0;
            var deleteCount = 0;
            #region 读取excel
            var res = new ec_PanelChannelBLL().IOModuleImportExcel(ProjId,strFilePath);
            #endregion


            return Success($"导入成功！合计新建【{insertCount}】个，删除【{deleteCount}】个");
        }


        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string keyValue, string strEntity, string ProjectId)
        {
            ec_Wire_GroupEntity entity = strEntity.ToObject<ec_Wire_GroupEntity>();
            ec_Wire_GroupIBLL.SaveEntity(ProjectId, ref keyValue, entity);
            return Success("保存成功！");
        }
        /// <summary>
        /// 改变实体状态
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult SaveStatus(string ProjectId, string keyValue, WireGroupStatusEnum status)
        {
            var tableName = ProjectSugar.TableName<ec_Wire_GroupEntity>(ProjectId);
            var entity = SqlSugarHelper.Db.Queryable<ec_Wire_GroupEntity>().AS(tableName).First(x => x.Wire_Group_ID == keyValue);
            if (entity == null)
            {
                return Fail("信号不存在！！！");
            }
            entity.Status = status;
            var BLL = new ec_Wire_GroupBLL(ProjectId);
            string result = BLL.SaveEntity(ProjectId, ref keyValue, entity, "0");
            if (string.IsNullOrEmpty(result))
            {
                return Success("修改成功！");
            }
            else
            {
                return Fail(result);
            }
        }
        #endregion
    }
}
