using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.SC.PT;
using APT.MS.Domain.Entities.SK;
using APT.MS.Domain.Enums.SK;
using APT.Utility;
using ICSharpCode.SharpZipLib.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyModel;
using Org.BouncyCastle.Asn1.Ess;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Ubiety.Dns.Core;

namespace APT.SK.WebApi.Controllers.Api
{
    [Route("api/SK/SKMeasure")]
    public partial class MeasureController : AuthorizeApiController<T_SK_MEASURE>
    {

        /// <summary>
        /// 更新或新增数据
        /// </summary>
        /// <param name="entity">对象实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SK_MEASURE entity)
        {
            return WitUpdate(entity);
        }
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost, Route("ImportUpdate")]
        public JsonActionResult<bool> ImportUpdate(IFormCollection files)
        {
            return SafeExecute<bool>(() =>
            {
                bool isOK = true;
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var httpRequest = this.HttpContext.Request;
                string orgIdStr = httpRequest.Form["OrgId"];// 获取 组织        
                var dic = Path.Combine(System.AppContext.BaseDirectory, "tempImportFiles");
                if (!Directory.Exists(dic))
                    Directory.CreateDirectory(dic);
                foreach (var key in httpRequest.Form.Files)  // 文件键
                {
                    var postedFile = key;    // 获取文件键对应的文件对象
                    string filePath = Path.Combine(dic, DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + postedFile.FileName);
                    Byte[] fileData = new Byte[postedFile.Length];
                    Stream sr = postedFile.OpenReadStream();//创建数据流对象 
                    sr.Read(fileData, 0, (int)postedFile.Length);
                    using (FileStream fs = new FileStream(filePath, FileMode.CreateNew))
                    {
                        fs.Write(fileData, 0, fileData.Length);
                        fs.Flush();
                        fs.Close();
                    }

                    //获取数据
                    Dictionary<int, int> startRowIndexs = new Dictionary<int, int>();
                    startRowIndexs.Add(0, 1);//根据Excel格式数据赋值
                    var dataTables = FileUtils.ReadExcelByOledb(filePath, startRowIndexs);
                    string Msg = string.Empty;
                    isOK = InsertModel(dataTables.Tables[0], orgId, ref Msg);
                   
                    try
                    {
                        System.IO.File.Delete(filePath);
                    }
                    catch { }
                }

                return isOK;
            });
        }
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="dtSource"></param>
        /// <param name="orgId"></param>
        /// <param name="Msg"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public bool InsertModel(DataTable dtSource, Guid? orgId, ref string Msg, int rowIndex = 1)
        {
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            if (dtSource == null || dtSource.Rows.Count < rowIndex)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }
            int rowAll = dtSource.Rows.Count;
            if (rowAll == 1)
            {
                throw new Exception("导入必须两条以上，一条请直接新增");
            }
            List<T_SK_MEASURE> contents = new List<T_SK_MEASURE>();
            Guid? checkId=null;
            var baseFilter = new BaseFilter(orgId);
            var oldContents = this.GetEntities<T_SK_MEASURE>(i => i.IS_DELETED == false, baseFilter);
            for (int i = 0; i < rowAll; i++)
            {
                if (!string.IsNullOrEmpty(dtSource.Rows[i][0].ToString().Trim()))
                {
                    var first = oldContents.FirstOrDefault(x => x.NAME == dtSource.Rows[i][0].ToString().Trim());
                    if (first != null)//旧表已存在数据
                    {
                        checkId = first.ID;
                    }
                    else//不存在
                    {
                        T_SK_MEASURE content = new T_SK_MEASURE();
                        content.ORG_ID = orgId;
                        content.NAME = dtSource.Rows[i][0].ToString().Trim();
                        checkId = content.ID;
                        contents.Add(content);
                    }
                }
            }
            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }
            else
            {
                UnifiedCommit(() =>
                {
                    if (contents != null && contents.Any())
                        BantchSaveEntityNoCommit(contents);
                });
                Msg = "导入成功！";
            }
            return true;
        }
    }
}
