using APT.Infrastructure.Core;
using APT.BaseData.Domain.Entities.FM;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using APT.BaseData.Domain.IServices.FM;

using APT.Utility;
using APT.BaseData.Domain.Entities.BD;
using System.Linq;
using APT.BaseData.Domain.Enums;
using System;
using System.Linq.Expressions;
using APT.BaseData.Domain.ApiModel;
using System.IO;
using System.Data;

namespace APT.FM.WebApi.Controllers.Api.FM
{
    /// <summary>
    ///  部门排班表
    /// </summary>
    [Route("api/FM/DepartmentScheduling")]
    public partial class DepartmentSchedulingController : AuthorizeApiController<T_FM_DEPARTMENT_SCHEDULING>
    {

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FM_DEPARTMENT_SCHEDULING entity)
        {
            return SafeExecute<bool>(() =>
            {

                var detail = entity.Nav_DepartmentSchedulingDetail;
                var repeatPersonIds = detail.Where(t => t.IS_DELETED == false).GroupBy(x => x.PERSON_ID).Where(x => x.Count() > 1).Select(t => t.Key);
                if (repeatPersonIds.Any())
                {
                    BaseFilter baseFilter = new BaseFilter(entity.ORG_ID);
                    baseFilter.SelectField = new string[] { "NAME" };
                    var repeatPersonNames = GetEntities<T_FM_PERSON>(t => repeatPersonIds.Contains(t.ID), baseFilter);
                    string repeatNames = string.Join(",", repeatPersonNames.Select(i => i.NAME));
                    throw new Exception(repeatNames + "重复,不允许重复添加人员!");
                }
                entity.Nav_DepartmentSchedulingDetail = null;
                if (entity.DATE_TIME == DateTime.MinValue)
                {
                    entity.DATE_TIME = entity.START_TIME;
                }
                UnifiedCommit(() =>
                {
                    this.UpdateEntityNoCommit(entity);
                    this.BantchSaveEntityNoCommit(detail);
                });
                return true;
            });
        }
        /// <summary>
        /// 保存配置信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("ClearRun")]
        public JsonActionResult<bool> ClearRun([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var baseConfig = this.GetEntityByRedis<T_FM_BASE_CONFIG>(filter.GetOrgId().ToString(), filter.GetOrgId());
                if (baseConfig == null)
                    this.ThrowError("010002");
                //清除数据后重新生成
                if (!string.IsNullOrWhiteSpace(filter.Keyword))
                {
                    var configIds = filter.Parameter1?.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(i => Guid.Parse(i));
                    Expression<Func<T_FM_DEPARTMENT_CALENDAR_CONFIG, bool>> express = i => i.DEPARTMENT_ID == new Guid(filter.Keyword)
               && i.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && i.END_TIME > DateTime.Now;
                    if (configIds.Any())
                    {
                        express = express.And(i => configIds.Contains(i.ID));
                    }
                    var departmentConfig = this.GetEntities<T_FM_DEPARTMENT_CALENDAR_CONFIG>(express, new BaseFilter(filter.GetOrgId()));
                    if (departmentConfig != null && departmentConfig.Any())
                    {
                        departmentConfig.ForEach(x => x.CURR_TIME = DateTime.Now.Date.AddDays(1));
                    }
                    this.UnifiedCommit(() =>
                    {
                        this.DeleteEntityNoCommit<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(i => i.Nav_DepartmentScheduling.DEPARTMENT_ID == new Guid(filter.Keyword)
                   && configIds.Contains(i.Nav_DepartmentScheduling.DEPARTMENT_CALENDAR_CONFIG_ID.Value) && i.Nav_DepartmentScheduling.DATE_TIME > DateTime.Now);
                        this.DeleteEntityNoCommit<T_FM_DEPARTMENT_SCHEDULING>(i => i.DEPARTMENT_ID == new Guid(filter.Keyword)
                        && configIds.Contains(i.DEPARTMENT_CALENDAR_CONFIG_ID.Value) && i.DATE_TIME > DateTime.Now);
                        if (departmentConfig != null && departmentConfig.Any())
                        {
                            this.BantchUpdateEntityNoCommit(departmentConfig);
                        }
                    });
                }

                return true;
            });
        }
        /// <summary>
        /// 获取导入数据  
        /// 参考         [Route("api/PF/Import")]
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("GetImportData")]
        public JsonActionResult<ImportDataModel> GetImportDataUser()
        {
            return SafeExecute<ImportDataModel>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var httpRequest = this.HttpContext.Request;
                string orgIdStr = httpRequest.Form["OrgId"];// 获取 组织            
                ImportDataModel result = new ImportDataModel();
                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;

                    bool isOK = InsertModelUser(dataTables.Tables[0], orgId, ref Msg);

                    try
                    {
                        System.IO.File.Delete(filePath);
                    }
                    catch { }

                    result.Data = Msg;
                    result.MessageList = new List<string> { Msg };
                }

                return result;
            });
        }
        /// <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 InsertModelUser(DataTable dtSource, Guid? orgId, ref string Msg, int rowIndex = 1)
        {
            if (dtSource == null || dtSource.Rows.Count < rowIndex)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }
            int rowAll = dtSource.Rows.Count;
            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }
            List<T_FM_DEPARTMENT_SCHEDULING> items = new List<T_FM_DEPARTMENT_SCHEDULING>();
            var teams = GetEntities<T_FM_TEAM>(t => t.IS_DELETED == false, new BaseFilter(orgId));
            for (int i = 0; i < rowAll; i++)
            {
                T_FM_DEPARTMENT_SCHEDULING item = new T_FM_DEPARTMENT_SCHEDULING();
                item.ID = Guid.NewGuid();
                var teamName = dtSource.Rows[i][0].ToString().Trim();
                var team = teams.FirstOrDefault(t => t.NAME == teamName);
                if (team == null)
                {
                    Msg = "未能找到对应班组";
                    throw new Exception(Msg);
                }
                item.TEAM_ID = team.ID;
                item.DATE_TIME = DateTime.Parse(dtSource.Rows[i][1].ToString().Trim());
                item.START_TIME = DateTime.Parse(dtSource.Rows[i][1].ToString().Trim());
                item.END_TIME = DateTime.Parse(dtSource.Rows[i][2].ToString().Trim());
                item.ORG_ID = orgId;
                items.Add(item);
            }
            UnifiedCommit(() =>
            {
                if (items != null && items.Any())
                    BantchAddEntityNoCommit(items);
            });
            Msg = "导入成功！";
            return true;
        }
    }
}
