using System;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities.OP;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core;
using APT.Migrations;
using APT.MS.Domain.Entities.WB;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System.Security.Cryptography;
using System.Collections.Generic;
using APT.BaseData.Domain.Enums;
using System.Linq;
using APT.BaseData.Domain.Entities;
using APT.MS.Domain.Enums;

namespace APT.SC.WebApi.Controllers.Api.WB
{
    [Route("api/WB/WBOutsource")]
    public class WBOutsourceController : AuthorizeApiController<T_WB_OUTSOURCE>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public WBOutsourceController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_WB_OUTSOURCE entity)
        {
            return SafeExecute(() =>
            {
                if (!APT.Infrastructure.Api.AppContext.CurrentSession.UserID.HasValue)
                {
                    throw new Exception("获取登录人员信息失败！");
                }
                if (entity.Nav_Tests == null || !entity.Nav_Tests.Any() || entity.Nav_Tests.Count() < 1)
                {
                    throw new Exception("请录入题库！");
                }

                entity.USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                entity.CREATE_TIME = DateTime.Now;

                var videos = entity.Nav_Videos;
                entity.Nav_Videos = null;
                var files = entity.Nav_Files;
                entity.Nav_Files = null;
                var tests = entity.Nav_Tests;
                entity.Nav_Tests = null;
                if (videos != null && videos.Any() && files != null && files.Any())
                {
                    var vc = videos.Select(e => !e.IS_DELETED);
                    var fc = files.Select(e => !e.IS_DELETED);
                    if (vc != null && vc.Count() > 0 && fc != null && fc.Count() > 0)
                        throw new Exception("视频和文件不能同时存在！");
                }
                if (videos != null && videos.Any())
                {
                    foreach (var item in videos)
                    {
                        item.Nav_Video = null;
                    }
                }
                List<int> listResultD = new List<int>() { 1, 2, 4, 8, 17 };
                int rowIndex = 0;

                int allScore = 0;
                List<string> listAnswer = null;
                foreach (var item in tests)
                {
                    if (item.IS_DELETED)
                    {
                        continue;
                    }
                    rowIndex++;
                    if (item.ROW_NO == 0)
                    {
                        item.ROW_NO = rowIndex;
                    }
                    item.TRAINNAME = entity.NAME;
                    allScore += item.SCORE;
                    //ANSWER_SHOW
                    if (string.IsNullOrEmpty(item.ANSWER_SHOW))
                    {
                        throw new Exception("请输入行【" + rowIndex + "】的答案");
                    }

                    switch (item.TYPE)
                    {
                        case MS.Domain.Enums.SETestTypeEnum.是非题:
                            //if (1 != item.ANSWER && 2 != item.ANSWER)
                            //{
                            //    throw new Exception("行【" + rowIndex + "】的答案输入有误！【是:1 否:2 】");
                            //}
                            if (item.ANSWER_SHOW.Trim() == "A")
                            {
                                item.ANSWER = 1;
                            }
                            else if (item.ANSWER_SHOW.Trim() == "B")
                            {
                                item.ANSWER = 2;
                            }
                            else
                            {
                                throw new Exception("行" + rowIndex + "的答案【" + item.ANSWER_SHOW + "】输入有误！【A/B】");
                                //throw new Exception("行【" + rowIndex + "】的答案输入有误！【是:1 否:2 】");
                            }
                            break;
                        case MS.Domain.Enums.SETestTypeEnum.单选题:
                            item.ANSWER = 0;
                            switch (item.ANSWER_SHOW)
                            {
                                case "A":
                                    item.ANSWER = 1;
                                    break;
                                case "B":
                                    item.ANSWER = 2;
                                    break;
                                case "C":
                                    item.ANSWER = 4;
                                    break;
                                case "D":
                                    item.ANSWER = 8;
                                    break;
                                default:
                                    break;
                            }
                            if (item.ANSWER == 0)
                            {
                                throw new Exception("行" + rowIndex + "的答案【" + item.ANSWER_SHOW + "】输入有误！【A/B/C/D】");
                            }
                            //if (!listResultD.Contains(item.ANSWER))
                            //{
                            //    throw new Exception("行【" + rowIndex + "】的答案输入有误！【A:1, B:2, C:4, D:8】");
                            //}
                            break;
                        case MS.Domain.Enums.SETestTypeEnum.多选题:
                            //if (item.ANSWER > 33)
                            //{
                            //    throw new Exception("行【" + rowIndex + "】的答案输入有误！组合【A:1, B:2, C:4, D:8, E:16】相加");
                            //}
                            item.ANSWER = 0;
                            if (item.ANSWER_SHOW.Contains(","))
                            {
                                listAnswer = item.ANSWER_SHOW.Split(",", StringSplitOptions.RemoveEmptyEntries).ToList();
                                foreach (var itemA in listAnswer)
                                {
                                    switch (itemA)
                                    {
                                        case "A":
                                            item.ANSWER += 1;
                                            break;
                                        case "B":
                                            item.ANSWER += 2;
                                            break;
                                        case "C":
                                            item.ANSWER += 4;
                                            break;
                                        case "D":
                                            item.ANSWER += 8;
                                            break;
                                        case "E":
                                            item.ANSWER += 16;
                                            break;
                                        default:
                                            throw new Exception("行" + rowIndex + "的答案【" + item.ANSWER_SHOW + "】输入有误！【A,B,C,D,E】答案用[,]分割");
                                            break;
                                    }
                                }
                                if (item.ANSWER == 1 || item.ANSWER == 2 || item.ANSWER == 4 || item.ANSWER == 8 || item.ANSWER == 16)
                                {
                                    throw new Exception("行" + rowIndex + "的答案【" + item.ANSWER_SHOW + "】输入有误！【A/B/C/D/E】答案用[,]分割，并且不能重复！");
                                }
                            }
                            else
                            {
                                throw new Exception("行" + rowIndex + "的答案【" + item.ANSWER_SHOW + "】输入有误！【A/B/C/D/E】答案用[,]分割");
                            }
                            break;
                        default:
                            break;
                    }
                }

                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (videos != null && videos.Any())
                        BantchSaveEntityNoCommit(videos);
                    if (tests != null && tests.Any())
                        BantchSaveEntityNoCommit(tests);
                });
                return true;
            });
        }

        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetSuit")]
        public JsonActionResult<T_WB_OUTSOURCE> GetSuit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var result = GetEntity<T_WB_OUTSOURCE>(null, filter, null);
                if (result != null && result.Nav_Tests != null && result.Nav_Tests.Any())
                {
                    foreach (var item in result.Nav_Tests)
                    {
                        if (item.TYPE == SETestTypeEnum.是非题)
                        {
                            if (item.ANSWER == 1)
                            {
                                item.ANSWER_SHOW = "A";
                            }
                            else
                            {
                                item.ANSWER_SHOW = "B";
                            }
                        }
                        else if (item.TYPE == SETestTypeEnum.单选题)
                        {
                            switch (item.ANSWER)
                            {
                                case 1:
                                    item.ANSWER_SHOW = "A";
                                    break;
                                case 2:
                                    item.ANSWER_SHOW = "B";
                                    break;
                                case 4:
                                    item.ANSWER_SHOW = "C";
                                    break;
                                case 8:
                                    item.ANSWER_SHOW = "D";
                                    break;
                                default:
                                    break;
                            }
                        }
                        else //多选
                        {
                            switch (item.ANSWER)
                            {
                                case 1:
                                    item.ANSWER_SHOW = "A";
                                    break;
                                case 2:
                                    item.ANSWER_SHOW = "B";
                                    break;
                                case 3:
                                    item.ANSWER_SHOW = "A,B";
                                    break;
                                case 4:
                                    item.ANSWER_SHOW = "C";
                                    break;
                                case 5:
                                    item.ANSWER_SHOW = "A,C";
                                    break;
                                case 6:
                                    item.ANSWER_SHOW = "B,C";
                                    break;
                                case 7:
                                    item.ANSWER_SHOW = "A,B,C";
                                    break;
                                case 8:
                                    item.ANSWER_SHOW = "D";
                                    break;
                                case 9:
                                    item.ANSWER_SHOW = "A,D";
                                    break;
                                case 10:
                                    item.ANSWER_SHOW = "B,D";
                                    break;
                                case 11:
                                    item.ANSWER_SHOW = "A,B,D";
                                    break;
                                case 12:
                                    item.ANSWER_SHOW = "C,D";
                                    break;
                                case 13:
                                    item.ANSWER_SHOW = "A,C,D";
                                    break;
                                case 14:
                                    item.ANSWER_SHOW = "B,C,D";
                                    break;
                                case 15:
                                    item.ANSWER_SHOW = "A,B,C,D";
                                    break;
                                case 16:
                                    item.ANSWER_SHOW = "E";
                                    break;
                                case 17:
                                    item.ANSWER_SHOW = "A,E";
                                    break;
                                case 18:
                                    item.ANSWER_SHOW = "B,E";
                                    break;
                                case 19:
                                    item.ANSWER_SHOW = "A,B,E";
                                    break;
                                case 20:
                                    item.ANSWER_SHOW = "C,E";
                                    break;
                                case 21:
                                    item.ANSWER_SHOW = "A,C,E";
                                    break;
                                case 22:
                                    item.ANSWER_SHOW = "B,C,E";
                                    break;
                                case 23:
                                    item.ANSWER_SHOW = "A,B,C,E";
                                    break;
                                case 24:
                                    item.ANSWER_SHOW = "D,E";
                                    break;
                                case 25:
                                    item.ANSWER_SHOW = "A,D,E";
                                    break;
                                case 26:
                                    item.ANSWER_SHOW = "B,D,E";
                                    break;
                                case 27:
                                    item.ANSWER_SHOW = "A,B,D,E";
                                    break;
                                case 28:
                                    item.ANSWER_SHOW = "C,D,E";
                                    break;
                                case 29:
                                    item.ANSWER_SHOW = "A,C,D,E";
                                    break;
                                case 30:
                                    item.ANSWER_SHOW = "B,C,D,E";
                                    break;
                                case 31:
                                    item.ANSWER_SHOW = "A,B,C,D,E";
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
                return result;
            });
        }


        ///// <summary>
        ///// 查询
        ///// </summary>
        ///// <param name="filter"></param>
        ///// <returns></returns>
        //[HttpPost, Route("GetSource")]
        //public JsonActionResult<T_WB_OUTSOURCE> GetSource([FromBody] KeywordFilter filter)
        //{
        //    return SafeExecute<T_WB_OUTSOURCE>(() =>
        //    {
        //        var RECORD_ID = Guid.Empty;
        //        try
        //        {
        //            if (!string.IsNullOrEmpty(filter.Keyword))
        //            {
        //                RECORD_ID = new Guid(filter.Keyword);
        //            }
        //        }
        //        catch (Exception)
        //        {
        //            RECORD_ID = Guid.Empty;
        //        }
        //        if (RECORD_ID == Guid.Empty)
        //        {
        //            throw new Exception("获取传参有误！");
        //        }
        //        var record = GetEntity<T_WB_OUTSOURCE_TRAIN_RECORD>(e => e.ID == RECORD_ID && e.Nav_Parent.NAME != null, "Nav_Parent");
        //        if (record.Nav_Parent == null)
        //        {
        //            throw new Exception("获取安全培训指派信息失败！");
        //        }
        //        var source = GetEntity<T_WB_OUTSOURCE>(e => e.NAME == record.Nav_Parent.NAME && e.ENABLE_STATUS == FMEnableStatusEnum.启用, "Nav_Files.Nav_ImgFile");
        //        return source;
        //    });
        //}

        /// <summary>
        /// 查询
        /// 提交 答题路由 WB/WBOutsourceTrainRecord/SavePapers
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetSource")]
        public JsonActionResult<T_WB_OUTSOURCE_TRAIN_RECORD_USERS> GetSource([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_WB_OUTSOURCE_TRAIN_RECORD_USERS>(() =>
            {
                var ORDER_ID = Guid.Empty;
                try
                {
                    if (!string.IsNullOrEmpty(filter.Keyword))
                    {
                        ORDER_ID = new Guid(filter.Keyword);
                    }
                }
                catch (Exception)
                {
                    ORDER_ID = Guid.Empty;
                }
                if (ORDER_ID == Guid.Empty)
                {
                    throw new Exception("获取传参有误！");
                }
                var result = GetEntity<T_WB_OUTSOURCE_TRAIN_RECORD_USERS>(ORDER_ID, "Nav_ListUserPaper.Nav_Test");
                if (result.Nav_ListUserPaper != null && result.Nav_ListUserPaper.Any())
                {
                    result.Nav_ListUserPaper = result.Nav_ListUserPaper.OrderBy(e => e.ROW_NO).ToList();
                    var listSourceID = result.Nav_ListUserPaper.Select(e => e.SOURCE_ID).Distinct();
                    var listSource = GetEntities<T_WB_OUTSOURCE>(e => listSourceID.Contains(e.ID), null, "Nav_Files.Nav_ImgFile");
                    foreach (var item in result.Nav_ListUserPaper)
                    {
                        item.Nav_Source = listSource.First(e => e.ID == item.SOURCE_ID);
                    }
                }
                return result;
            });
        }

        /// <summary>
        /// 交卷
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost, Route("SavePapers")]
        public JsonActionResult<bool> SavePapers([FromBody] T_WB_OUTSOURCE_TRAIN_RECORD_USERS entity)
        {
            return SafeExecute(() =>
            {
                if (entity.SCORE.HasValue && entity.SCORE > 0)
                {
                    throw new Exception("试卷已完成");
                }
                if (entity.Nav_ListUserPaper == null || entity.Nav_ListUserPaper.Count() == 0)
                {
                    int onlineCount = entity.Nav_ListUserPaper.Where(e => e.IS_ONLINE).Count();
                    if (onlineCount > 0)
                    {
                        //有些可能 线上直接看视频 不需要做题
                        entity.SCORE = 100;//默认100分
                    }
                    else
                    {
                        throw new Exception("试卷不能为空");
                    }
                }
                else
                {
                    foreach (var item in entity.Nav_ListUserPaper)
                    {
                        if (item.IS_ONLINE)
                        {
                            item.IS_WATCH = true;
                        }
                    }

                    entity.SCORE = 0;
                    var listSourceID = entity.Nav_ListUserPaper.Select(e => e.SOURCE_ID).Distinct();
                    var AllSCORE = 0;
                    foreach (var item in listSourceID)
                    {
                        AllSCORE += entity.Nav_ListUserPaper.Where(e => e.SOURCE_ID == item).Sum(e => e.SCORE.Value);
                    }
                    entity.SCORE = AllSCORE / listSourceID.Count();
                }

                //var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                //var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                //var users = GetEntities<T_WB_OUTSOURCE_TRAIN_RECORD_USERS>(t => t.PARENT_ID == entity.ID, new BaseFilter(orgId));
                //var currUsers = users.Where(t => t.USER_ID == userID);
                //foreach (var user in currUsers)
                //{
                //    user.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                //    user.MODIFY_TIME = DateTime.Now;
                //}

                //var currUser = GetEntity<T_WB_OUTSOURCE_TRAIN_RECORD_USERS>(entity.ID); 
                entity.SIGN_STATUS = FOUserShiftStatusEnum.待处理;//FOUserShiftStatusEnum.已处理;  考试 待老师 确认 后 也是需要再次确认
                entity.DEAL_STATUS = ExamStatusEnum.已处理;
                entity.MODIFY_TIME = DateTime.Now;
                T_WB_OUTSOURCE_TRAIN_RECORD Record = null;

                //#region     如果时间超过了培训结束时间
                ////判断是否有别的 考试 变成超期无需处理

                //#endregion

                var unSign = GetEntity<T_WB_OUTSOURCE_TRAIN_RECORD_USERS>(e => e.PARENT_ID == entity.PARENT_ID && e.ID != entity.ID && e.DEAL_STATUS == 0);
                //var todoCount = users.Count(t => t.DEAL_STATUS == 0);
                //if (todoCount == 0)
                T_FM_NOTIFICATION_TASK task = null;

                if (unSign == null || unSign.ID == Guid.Empty)
                {
                    Record = GetEntity<T_WB_OUTSOURCE_TRAIN_RECORD>(entity.PARENT_ID, "Nav_Parent.Nav_Project", "Nav_Parent.Nav_User");//, "Nav_Parent.Nav_Project" wyw 这个没必要再加入查询啊
                    Record.END_TIME = DateTime.Now;
                    if (Record.TRAIN_TYPE.IndexOf("1") > -1)
                    {
                        Record.ONLINE_END_TIME = Record.END_TIME;
                        Record.ONLINE_TOTAL_TIME = (int)Math.Ceiling((Record.ONLINE_END_TIME.Value - Record.ONLINE_START_TIME.Value).TotalHours);
                        Record.TOTAL_TIME = Record.ONLINE_TOTAL_TIME;//也加上吧
                    }
                    Record.STATUS = SETrainNotifyStatus.通知中;// 签到完成;
                    if (!Record.Nav_Parent.USER_ID.HasValue)
                    {
                        throw new Exception("未获取到培训讲师信息，请联系管理员！");
                    }
                    if (Record.ISEND == false)
                    {
                        Record.ISEND = true;
                        //触发讲师确认  
                        task = NotificationTaskService.InsertUserNoticeTaskModel(Record.Nav_Parent.Nav_Project.UNIT_NAME + "安全培训记录结果确认", Record.ID, Record.ORG_ID, (Guid)Record.Nav_Parent.USER_ID, Record.Nav_Parent.Nav_User.NAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB048");
                    }
                }

                T_FM_NOTIFICATION_TASK finishNotice = null;
                if (entity.TaskID != Guid.Empty)
                    finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID);

                //#region  考试通过才能提交 所以考完直接设置分数 考试通过 可以被选作为 作业监护人等

                //T_WB_REGISTER_2 LoginReg2 = GetEntity<T_WB_REGISTER_2>(e => e.USERID.HasValue && e.USERID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID);
                //if (LoginReg2 != null)
                //{
                //    LoginReg2.SCORE = (double)entity.SCORE;
                //}
                //#endregion

                entity.SIGN_STATUS = FOUserShiftStatusEnum.已处理;//在线考试 默认签到

                UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntity(entity);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (Record != null)
                        UpdateEntity(Record);
                    //if (currUsers != null)
                    //    BantchUpdateEntity(currUsers, "DEAL_STATUS", "MODIFY_TIME");
                    BantchSaveEntityNoCommit(entity.Nav_ListUserPaper);
                    if (task != null)
                        UpdateEntity(task);
                    //if (LoginReg2 != null)
                    //    UpdateEntity(LoginReg2);
                });
                return true;
            });
        }
    }
}
