using Learun.Application.Base.SystemModule;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.SqlSugar;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
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-06-01 15:08
    /// 描 述：数据字典
    /// </summary>
    public class ec_dataitemController : MvcControllerBase
    {
        private ec_dataitemIBLL ec_dataitemIBLL = new ec_dataitemBLL();

        #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 ClassifyIndex()
        {
            return View();
        }
        /// <summary>
        /// 字典分类管理表单页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ClassifyForm()
        {
            return View();
        }

        #endregion

        #region 获取数据

        /// <summary>
        /// 导出 单个 数据字典
        /// </summary>
        /// <returns></returns>
        public void exportSingle(string ProjectId, string dataItemID)
        {
            IWorkbook workbook = new XSSFWorkbook();
            var tbName = ProjectSugar.TableName<ec_dataitemEntity>(ProjectId);
            var detailName = ProjectSugar.TableName<ec_dataitemdetailEntity>(ProjectId);

            var codelist = SqlSugarHelper.Db.Queryable<ec_dataitemEntity>().AS(tbName).First(x => x.DataItemID == dataItemID);
            if (codelist == null)
            {
                throw new System.Exception("无效的dataItemID");
            }
            var enums = SqlSugarHelper.Db.Queryable<ec_dataitemdetailEntity>().AS(detailName).Where(x => x.DataItemID == dataItemID).ToList();
            ISheet sheet = null;
            try
            {
                sheet = workbook.CreateSheet(codelist.DataItemName);
            }
            catch (System.Exception)
            {
                //万一名字奇奇怪怪的
                sheet = workbook.CreateSheet("数据字典");
            }


            //创建第一行  并赋值
            IRow row = sheet.CreateRow(0);
            row.CreateCell(0).SetCellValue("数据字典内部ID（勿改）");
            row.CreateCell(1).SetCellValue(dataItemID);

            row = sheet.CreateRow(2);
            row.CreateCell(0).SetCellValue("中文名称（不能重复）");
            row.CreateCell(1).SetCellValue("英文名称");
            row.CreateCell(2).SetCellValue("编号（不能重复）");
            row.CreateCell(3).SetCellValue("是否有效(0无效，1有效）");
            row.CreateCell(4).SetCellValue("备注");
            row.CreateCell(5).SetCellValue("ID（勿改，新增的行留空即可）");
            int rowIndex = 3;
            foreach (var ENUM in enums)
            {
                row = sheet.CreateRow(rowIndex);
                row.CreateCell(0).SetCellValue(ENUM.DataItemName);
                row.CreateCell(1).SetCellValue(ENUM.DataItemNameEN);
                row.CreateCell(2).SetCellValue(ENUM.DataItemCode);
                row.CreateCell(3).SetCellValue(ENUM.IsEnabled.ToString());
                row.CreateCell(4).SetCellValue(ENUM.Remark);
                row.CreateCell(5).SetCellValue(ENUM.DataItemDetailID);
                rowIndex++;
            }


            string filename = $"数据字典_{codelist.DataItemName}_" + DateTime.Now.ToString("yyMMddHHmmss");
            ExcelHelper.DownloadIWorkbook(workbook, filename);
        }
        /// <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_dataitemIBLL.GetList(queryJson, pagination: paginationobj);
            var jsonData = new
            {
                rows = data,
                total = paginationobj.total,
                page = paginationobj.page,
                records = paginationobj.records
            };
            return Success(jsonData);
        }

        /// <summary>
        /// 获取页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetList(string queryJson)
        {
            var data = ec_dataitemIBLL.GetList(queryJson, false);
            return Success(data);
        }

        /// <summary>
        /// 获取表单数据
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetFormData(string keyValue, string ProjectId)
        {
            var ec_dataitemData = ec_dataitemIBLL.GetEntity(keyValue, ProjectId);
            var ec_dataitemdetailData = ec_dataitemIBLL.GetEntity(ec_dataitemData.DataItemID, ProjectId);
            var jsonData = new
            {
                ec_dataitem = ec_dataitemData,
                ec_dataitemdetail = ec_dataitemdetailData,
            };
            return Success(jsonData);
        }
        /// <summary>
        /// 获取字典分类列表(树结构)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetClassifyTree(string ProjectId)
        {
            var data = ec_dataitemIBLL.GetClassifyTree(ProjectId);
            return this.Success(data);
        }

        /// <summary>
        /// 分类编号不能重复
        /// </summary>
        /// <param name="DataItemCode">编码</param>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult ExistItemCode(string keyValue, string DataItemCode, string ProjectId)
        {
            bool res = ec_dataitemIBLL.ExistItemCode(keyValue, DataItemCode, ProjectId);
            return Success(res);
        }
        /// <summary>
        /// 分类名称不能重复
        /// </summary>
        /// <param name="DataItemName">名称</param>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult ExistItemName(string keyValue, string DataItemName, string ProjectId)
        {
            bool res = ec_dataitemIBLL.ExistItemName(keyValue, DataItemName, ProjectId);
            return Success(res);
        }

        #endregion

        #region 提交数据
        /// <summary>
        /// 用于数据字典的导入。 
        /// </summary>
        /// <param name="keyValue">事先上传到服务器的文件的id</param>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult ExcelImport(string keyValue, string ProjectId)
        {
            //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
            using (FileStream fs = new FileStream(strFilePath, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook = new XSSFWorkbook(fs); // .xlsx 用 XSSFWorkbook

                ISheet sheet = workbook.GetSheetAt(0);
                Console.WriteLine($"📄 Sheet: {sheet.SheetName}");
                var tbName = ProjectSugar.TableName<ec_dataitemEntity>(ProjectId);
                var detailName = ProjectSugar.TableName<ec_dataitemdetailEntity>(ProjectId);

                var id = sheet.GetRow(0).GetCell(1).ToString();

                var codelist = SqlSugarHelper.Db.Queryable<ec_dataitemEntity>().AS(tbName).First(x => x.DataItemID == id);
                var ENUMS = SqlSugarHelper.Db.Queryable<ec_dataitemdetailEntity>().AS(detailName).Where(X => X.DataItemID == id).ToList();
                var existIds = ENUMS.Select(x => x.DataItemDetailID).ToList();
                if (codelist == null)
                {
                    //无效
                    return Fail("单元格（0，1）为无效的id");
                }
                
                for (int row = 3; row <= sheet.LastRowNum; row++)
                { 
                    IRow currentRow = sheet.GetRow(row);
                    if (currentRow == null) continue;

                    var name = ExcelHelper.GetCellStringValue(currentRow.GetCell(0));
                    var nameEN = ExcelHelper.GetCellStringValue(currentRow.GetCell(1));
                    var code = ExcelHelper.GetCellStringValue(currentRow.GetCell(2));
                    var isEnable = ExcelHelper.GetCellStringValue(currentRow.GetCell(3));
                    var remark = ExcelHelper.GetCellStringValue(currentRow.GetCell(4));
                    var detailId = ExcelHelper.GetCellStringValue(currentRow.GetCell(5));
                    if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(code))
                    {
                        continue;
                    }

                    var exist = ENUMS.FirstOrDefault(x => x.DataItemDetailID == detailId);
                    if (exist != null)
                    {
                        #region m

                        exist.DataItemName = name;
                        exist.DataItemNameEN = nameEN;
                        exist.DataItemCode = code;
                        if (isEnable == "1")
                        {
                            exist.IsEnabled = 1;
                        }
                        else
                        {
                            exist.IsEnabled = 0;
                        }
                        exist.Remark = remark;
                        exist.OrderID = row - 2;
                        SqlSugarHelper.Db.Updateable(exist).AS(detailName).ExecuteCommand();
                        #endregion
                    }
                    else
                    {
                        #region a  
                        var existOther = ENUMS.Any(X => X.DataItemName == name);
                        if (existOther)
                        {
                            //已有同名的
                            continue;
                        }
                        exist = new ec_dataitemdetailEntity();
                        exist.Create();
                        exist.DataItemName = name;
                        exist.DataItemNameEN = nameEN;
                        exist.DataItemCode = code;
                        if (isEnable == "1")
                        {
                            exist.IsEnabled = 1;
                        }
                        else
                        {
                            exist.IsEnabled = 0;
                        }
                        exist.Remark = remark;
                        exist.DataItemID = id;
                        exist.OrderID = row - 2;
                        insertCount++;
                        SqlSugarHelper.Db.Insertable(exist).AS(detailName).ExecuteCommand();
                        #endregion
                    }

                    #region d
                    existIds.Remove(detailId);
                    #endregion

                }

                //剩下的就是需要删的
                foreach (var item in existIds)
                {
                    var nouse = ENUMS.FirstOrDefault(x => x.DataItemDetailID == item);
                    nouse.IsEnabled = 0;
                    nouse.UpdateTime = System.DateTime.Now;
                    nouse.UpdateUserID = LoginUserInfo.Get().userId; 
                    SqlSugarHelper.Db.Updateable(nouse).AS(detailName).ExecuteCommand();
                }
                deleteCount = existIds.Count;

            }
            #endregion


            return Success($"导入成功！合计新建【{insertCount}】个，删除【{deleteCount}】个");
        }
        /// <summary>
        /// 单纯smart 3d的数据导入，用于二三维校验用的part Name
        /// </summary>
        /// <param name="keyValue">事先上传到服务器的文件的id</param>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult ExcelImport3D(string keyValue, string ProjectId)
        {
            //MVC
            //查询文件的真实路径
            var file = new AnnexesFileBLL().GetByfolderIdEntity(keyValue);
            if (string.IsNullOrWhiteSpace(file?.F_FilePath))
            {
                return Fail("找不到文件" + file?.F_FilePath);
            }
            string strFilePath = file?.F_FilePath;
            var DataItemPartNumber = ec_dataitemIBLL.GetEntity("Part Number", ProjectId);
            if (DataItemPartNumber.IsEmpty())
            {
                return Fail("请先在分类树中建立一个节点为Part Number的节点");
            }
            string strPartNumberUID = DataItemPartNumber.DataItemID;
            ec_dataitemIBLL.PartNumberDetailImport(strPartNumberUID, strFilePath, ProjectId);
            return Success("导入成功！");
        }
        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteForm(string keyValue, string ProjectId)
        {
            ec_dataitemIBLL.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_dataitemEntity entity = strEntity.ToObject<ec_dataitemEntity>();
            ec_dataitemIBLL.SaveEntity(keyValue, entity, ProjectId);
            return Success("保存成功！");
        }
        #endregion

        #region 字典明细
        /// <summary>
        /// 获取数据字典明显根据分类编号
        /// </summary>
        /// <param name="dataItemCode">分类编号</param>
        /// <param name="keyword">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetDetailList(string dataItemCode, string keyword, string ProjectId)
        {
            var data = ec_dataitemIBLL.GetDetailList(dataItemCode, keyword, ProjectId);
            return Success(data);
        }

        /// <summary>
        /// 获取数据字典明显树形数据
        /// </summary>
        /// <param name="itemCode">分类编号</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetDetailTree(string itemCode, string ProjectId)
        {
            var data = ec_dataitemIBLL.GetDetailTree(itemCode, ProjectId);
            return Success(data);
        }
        /// <summary>
        /// 获取数据字典明细树形数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetTreeData(string ProjectId, bool isShowCheck, string DataItemID, string DataItemDetailID)
        {
            var tableName = ProjectSugar.TableName<ec_dataitemdetailEntity>(ProjectId);
            var list = SqlSugarHelper.Db.Queryable<ec_dataitemdetailEntity>().AS(tableName).Where(x => x.DataItemID == DataItemID).ToList();
            var childs = SqlSugarHelper.Db.Queryable<ec_dataitemdetailEntity>().AS(tableName).ToChildList(x => x.UpDataItemDetailID, DataItemDetailID);
            childs.ForEach(x =>
            {
                var item = list.FirstOrDefault(y => y.DataItemDetailID == x.DataItemDetailID);
                list.Remove(item);
            });
            List<TreeModel> treeList = new List<TreeModel>();
            foreach (var item in list)
            {
                TreeModel node = new TreeModel();
                node.id = item.DataItemDetailID;
                node.text = item.DataItemName;
                node.value = item.DataItemDetailID;
                node.showcheck = isShowCheck;
                node.checkstate = 0;
                node.isexpand = false;
                node.parentId = item.UpDataItemDetailID;
                node.NodeExtData = item;
                treeList.Add(node);
            }
            var res = treeList.ToTree();
            return Success(res);
        }
        /// <summary>
        /// 字典明细编号不能重复
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="DataItemCode">字典明细编号</param>
        /// <param name="itemCode">分类编码</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult ExistDetailItemCode(string keyValue, string DataItemCode, string itemCode, string ProjectId)
        {
            bool res = ec_dataitemIBLL.ExistDetailItemCode(keyValue, DataItemCode, itemCode, ProjectId);
            return Success(res);
        }
        /// <summary>
        /// 字典明细名称不能重复
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="DataItemName">字典明细名称</param>
        /// <param name="itemCode">分类编码</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult ExistDetailItemName(string keyValue, string DataItemName, string itemCode, string ProjectId)
        {
            bool res = ec_dataitemIBLL.ExistDetailItemName(keyValue, DataItemName, itemCode, ProjectId);
            return Success(res);
        }

        /// <summary>
        /// 保存明细数据实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="itemCode">分类编码</param>
        /// <param name="entity">实体</param>
        [HttpPost]
        [AjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SaveDetailForm(string keyValue, string itemCode, string strEntity, string ProjectId)
        {
            ec_dataitemdetailEntity entity = strEntity.ToObject<ec_dataitemdetailEntity>();
            ec_dataitemIBLL.SaveDetailEntity(keyValue, entity, ProjectId);
            return Success("保存成功！");
        }

        /// <summary>
        /// 删除明细数据
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteDetailForm(string keyValue, string ProjectId)
        {
            ec_dataitemIBLL.DeleteDetail(keyValue, ProjectId);
            return Success("删除成功！");
        }

        #endregion
    }
}
