using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.SE;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using APT.Infrastructure.Core;
using APT.BaseData.Domain.ApiModel;
using System.Data;
using System.IO;
using APT.BaseData.Domain.Entities.FM;
using Castle.Core.Internal;
using static APT.SC.WebApi.Controllers.Api.BI.BIController;

namespace APT.SE.WebApi.Controllers.Api
{
    [Route("api/SE/SETest")]
    public partial class SETestController : AuthorizeApiController<T_SE_TEST>
    {
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_SE_TEST> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            string POST_NAME = "";
            string POINT_NAME = "";
            if (pageFilter.Parameter1 != null)
            {
                POST_NAME = (string)pageFilter.Parameter1;
            }
            if (pageFilter.Parameter2 != null)
            {
                POINT_NAME = (string)pageFilter.Parameter2;
            }
            PagedActionResult<T_SE_TEST> ret = WitOrderPaged(t => (POST_NAME == "" ||
            (POST_NAME != "" && t.Nav_Posts.Any(it => it.Nav_Post.NAME.Contains(POST_NAME)))) &&
            (POINT_NAME == "" ||
            (POINT_NAME != "" && t.Nav_Points.Any(it => it.Nav_Point.NAME.Contains(POINT_NAME))))
            , pageFilter);
            return ret;
        }
        public class notifyName
        {

            public string NAME { get; set; }
        }
        /// <summary>
        /// 查询培训名称
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("getNotifyNames")]
        public JsonActionResult<List<notifyName>> getNotifyNames([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeExecute<List<notifyName>>(() =>
            {
                BaseFilter filter = new BaseFilter(pageFilter.GetOrgId());
                filter.SelectField = new string[] { "NAME" };
                var notifys = GetEntities<T_SE_TRAIN_NOTIFY>(t => t.IS_DELETED == false, filter).DistinctBy(t=>t.NAME);
                List<notifyName> ret = new List<notifyName>();
                foreach (var notify in notifys)
                {
                    notifyName notifyName = new notifyName();
                    notifyName.NAME = notify.NAME;
                    ret.Add(notifyName);
                }
                return ret;
            });
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SE_TEST entity)
        {
            return SafeExecute(() =>
            {
                if (entity.ID == null || entity.ID == Guid.Empty)
                {
                    entity.ID = Guid.NewGuid();
                }
                if (string.IsNullOrEmpty(entity.NAME))
                {
                    throw new Exception("题目不可为空");
                }
                if (entity.TYPE is SETestTypeEnum.单选题 or SETestTypeEnum.多选题)
                {
                    if ((entity.ANSWER) == 0)
                    {
                        throw new Exception("答案不可为空");
                    }
                    if (string.IsNullOrEmpty(entity.OPTION_A) ||
                        string.IsNullOrEmpty(entity.OPTION_B) ||
                        string.IsNullOrEmpty(entity.OPTION_C) ||
                        string.IsNullOrEmpty(entity.OPTION_D)
                        )
                    {
                        throw new Exception("选择题选项不可为空");
                    }
                    if (entity.TYPE == SETestTypeEnum.单选题 &&
                        entity.ANSWER != 1 && entity.ANSWER != 2 && entity.ANSWER != 4 && entity.ANSWER != 8 && entity.ANSWER != 16)
                    {
                        throw new Exception("单选题只能有一个正确选项");
                    }
                    if (entity.TYPE == SETestTypeEnum.多选题 && (entity.ANSWER < 3 || entity.ANSWER == 4 || entity.ANSWER == 8 || entity.ANSWER == 16))
                    {
                        throw new Exception("多选题至少有两个正确选项");
                    }
                }
                if (entity.TYPE == SETestTypeEnum.是非题)
                {
                    if (entity.ANSWER != 1 && entity.ANSWER != 2)
                    {
                        throw new Exception("是非题答案只能为是或否");
                    }
                }
                var points = entity.Nav_Points;
                entity.Nav_Points = null;
                if (points == null || points.Count == 0)
                {
                    throw new Exception("知识点不可为空");
                }
                points.ForEach(t =>
                {
                    t.ORG_ID = entity.ORG_ID;
                    t.TEST_ID = entity.ID;
                });

                var posts = entity.Nav_Posts;
                entity.Nav_Posts = null;
                if (posts != null)
                {
                    posts.ForEach(t =>
                    {
                        t.TEST_ID = entity.ID;
                        t.ORG_ID = entity.ORG_ID;
                    });
                }
                this.UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (posts != null)
                        BantchSaveEntityNoCommit(posts);
                    if (points != null)
                        BantchSaveEntityNoCommit(points);
                });
                return true;
            });
        }
        /// <summary>
        /// 获取导入数据  
        /// 参考         [Route("api/PF/Import")]
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("GetImportData")]
        public JsonActionResult<ImportDataModel> GetImportData()
        {
            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 = InsertModel(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 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;
            List<T_SE_TEST> mainTables = new List<T_SE_TEST>();
            List<T_SE_TEST_LIST_POST> sub1s = new List<T_SE_TEST_LIST_POST>();
            List<T_SE_TEST_LIST_POINT> sub2s = new List<T_SE_TEST_LIST_POINT>();

            var posts = GetEntities<T_FM_USER_POST>(t => t.IS_DELETED == false, new BaseFilter(orgId));
            var points = GetEntities<T_SE_TEST_ENUM_POINT>(t => t.IS_DELETED == false, new BaseFilter(orgId));

            DateTime dtNow = DateTime.Now;
            for (int i = 0; i < rowAll; i++)
            {
                T_SE_TEST mainTable = new T_SE_TEST();
                mainTable.ID = Guid.NewGuid();
                mainTable.ORG_ID = orgId;
                if (!string.IsNullOrEmpty(dtSource.Rows[i][0].ToString().Trim()))
                {
                    mainTable.NAME = dtSource.Rows[i][0].ToString().Trim();
                }
                else
                {
                    throw new Exception("名称不能为空!");
                }
                var testType = dtSource.Rows[i][1].ToString().Trim();
                if (!string.IsNullOrEmpty(testType))
                {
                    if (dtSource.Rows[i][1].ToString().Trim() == "是非题")
                    {
                        mainTable.TYPE = SETestTypeEnum.是非题;
                    }
                    else if (dtSource.Rows[i][1].ToString().Trim() == "单选题")
                    {
                        mainTable.TYPE = SETestTypeEnum.单选题;
                    }
                    else if (dtSource.Rows[i][1].ToString().Trim() == "多选题")
                    {
                        mainTable.TYPE = SETestTypeEnum.多选题;
                    }
                    else
                    {
                        throw new Exception("没有《"+ testType+"》类型");
                    }
                }
                else
                {
                    throw new Exception("题型不能为空!");
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][2].ToString().Trim()))
                {
                    mainTable.OPTION_A = (dtSource.Rows[i][2].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][3].ToString().Trim()))
                {
                    mainTable.OPTION_B = (dtSource.Rows[i][3].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][4].ToString().Trim()))
                {
                    mainTable.OPTION_C = (dtSource.Rows[i][4].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][5].ToString().Trim()))
                {
                    mainTable.OPTION_D = (dtSource.Rows[i][5].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][6].ToString().Trim()))
                {
                    mainTable.OPTION_E = (dtSource.Rows[i][6].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][7].ToString().Trim()))
                {
                    if (mainTable.TYPE == SETestTypeEnum.是非题)
                    {
                        if (dtSource.Rows[i][7].ToString().Trim() == "是")
                        {
                            mainTable.ANSWER = 1;
                        }
                        else if (dtSource.Rows[i][7].ToString().Trim() == "否")
                        {
                            mainTable.ANSWER = 2;
                        }
                    }

                    if (mainTable.TYPE == SETestTypeEnum.单选题)
                    {
                        if (dtSource.Rows[i][7].ToString().Trim() == "A")
                        {
                            mainTable.ANSWER = 1;
                        }
                        else if (dtSource.Rows[i][7].ToString().Trim() == "B")
                        {
                            mainTable.ANSWER = 2;
                        }
                        else if (dtSource.Rows[i][7].ToString().Trim() == "C")
                        {
                            mainTable.ANSWER = 4;
                        }
                        else if (dtSource.Rows[i][7].ToString().Trim() == "D")
                        {
                            mainTable.ANSWER = 8;
                        }
                    }
                    if (mainTable.TYPE == SETestTypeEnum.多选题)
                    {
                        int answer = 0;
                        if (dtSource.Rows[i][7].ToString().Trim().Contains("A"))
                        {
                            answer = answer + 1;
                        }
                        if (dtSource.Rows[i][7].ToString().Trim().Contains("B"))
                        {
                            answer = answer + 2;
                        }
                        if (dtSource.Rows[i][7].ToString().Trim().Contains("C"))
                        {
                            answer = answer + 4;
                        }
                        if (dtSource.Rows[i][7].ToString().Trim().Contains("D"))
                        {
                            answer = answer + 8;
                        }
                        if (dtSource.Rows[i][7].ToString().Trim().Contains("E"))
                        {
                            answer = answer + 16;
                        }
                        mainTable.ANSWER = answer;
                    }
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][8].ToString().Trim()))
                {
                    int k = 0;
                    if (dtSource.Rows[i][8].ToString().Contains("安全意识调查"))
                    {
                        k = k + 1;
                    }
                    if (dtSource.Rows[i][8].ToString().Contains("培训"))
                    {
                        k = k + 2;
                    }
                    if (dtSource.Rows[i][8].ToString().Contains("事故事件"))
                    {
                        k = k + 4;
                    }
                    mainTable.USAGE = k;
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][9].ToString().Trim()))
                {
                    var testPosts = dtSource.Rows[i][9].ToString().Trim().Split(';');
                    foreach (var postName in testPosts)
                    {
                        if (!string.IsNullOrEmpty(postName))
                        {
                            T_SE_TEST_LIST_POST sub1 = new T_SE_TEST_LIST_POST
                            {
                                ID = Guid.NewGuid(),
                                ORG_ID = orgId,
                                TEST_ID = mainTable.ID,
                                POST_ID = posts.FirstOrDefault(t => t.NAME == postName).ID
                            };
                            sub1s.Add(sub1);
                        }
                    }
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][10].ToString().Trim()))
                {
                    var testPoints = dtSource.Rows[i][10].ToString().Trim().Split(';');
                    foreach (var pointName in testPoints)
                    {
                        if (!string.IsNullOrEmpty(pointName))
                        {
                            var pointid = points.FirstOrDefault(t => t.NAME == pointName);
                            if (pointid != null)
                            {
                                T_SE_TEST_LIST_POINT sub2 = new T_SE_TEST_LIST_POINT
                                {
                                    ID = Guid.NewGuid(),
                                    ORG_ID = orgId,
                                    TEST_ID = mainTable.ID,
                                    POINT_ID = pointid.ID,
                                };
                                sub2s.Add(sub2);
                            }
                            else
                            {
                                throw new Exception(i + "行 未找到:" + pointName);
                            }
                        }
                    }
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][11].ToString().Trim()))
                {
                    mainTable.TRAINNAME = dtSource.Rows[i][11].ToString().Trim();
                }
                mainTables.Add(mainTable);
            }
            UnifiedCommit(() =>
            {
                if (mainTables != null && mainTables.Any())
                    BantchAddEntityNoCommit(mainTables);
                if (sub1s != null && sub1s.Any())
                    BantchAddEntityNoCommit(sub1s);
                if (sub2s != null && sub2s.Any())
                    BantchAddEntityNoCommit(sub2s);
            });
            Msg = "导入成功！";
            return true;
        }
    }
}
