using Kingdee.BOS.App.Core;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using LQKJ.LicVerify;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;

namespace LQKJ.XiBU.ServicePlugIN
{
    [HotUpdate,Description("保存提交审核")]
   public class SubmitAudit: AbstractOperationServicePlugIn
   {
        /// <summary>
        /// 枚举
        /// </summary>
        /*public enum DataType
        {
            LQKJ_Class,
            LQKJ_StudentsInfo,
            LQKJ_TrainingProgram,
            LQKJ_ClassDetails,
            LQKJ_Teacher,
            LQKJ_Course,
            LQKJ_SceneTeaching
        }*/
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            if (!LicScheduler.LicVerify())
                throw new Exception("lic过期");
            base.AfterExecuteOperationTransaction(e);
            var saveResult = this.OperationResult;
            // 筛选出保存成功的单据内码
            var successPKs = saveResult.OperateResult.Where(o => o.SuccessStatus == true).Select(x => x.PKValue).Distinct().ToArray();
            if (successPKs.Length == 0)
            {
                // 没有保存成功的结果，直接退出
                return;
            }
            for (int i= 0; i <successPKs.Count();i++)
            {
                if (e.DataEntitys[i]["DocumentStatus"].ToString()=="B"|| e.DataEntitys[i]["DocumentStatus"].ToString() == "C")
                {
                    return;
                }
            }
            /*IEnumerable<IDataRecord> dataTable;
            string result = string.Join(",", successPKs);
            string id = this.BusinessInfo.GetForm().Id;
            DataType dataType;
            if (Enum.TryParse(id, out dataType))
            {
                switch (dataType)
                {
                    case DataType.LQKJ_Class://班级
                        dataTable = DBUtils.ExecuteEnumerable(this.Context, $"select FCLASSID  as PKValue,FDOCUMENTSTATUS From T_PX_CLASS where FCLASSID in ({result}) and (FDOCUMENTSTATUS='A' OR FDOCUMENTSTATUS='D')");
                        successPKs = saveResult.OperateResult.Where(o => o.SuccessStatus == true && dataTable.Any(f => f.GetInt32(0).ToString() == o.PKValue.ToString())).Select(x => x.PKValue).Distinct().ToArray();
                        break;
                    case DataType.LQKJ_StudentsInfo://学员
                        dataTable = DBUtils.ExecuteEnumerable(this.Context, $"select FSTUDENTID  as PKValue,FDOCUMENTSTATUS From T_PX_StudentsInfo where FSTUDENTID in ({result}) and (FDOCUMENTSTATUS='A' OR FDOCUMENTSTATUS='D')");
                        successPKs = saveResult.OperateResult.Where(o => o.SuccessStatus == true && dataTable.Any(f => f.GetInt32(0).ToString() == o.PKValue.ToString())).Select(x => x.PKValue).Distinct().ToArray();
                        break;
                    case DataType.LQKJ_TrainingProgram://培训项目
                        dataTable = DBUtils.ExecuteEnumerable(this.Context, $"select FITEMID  as PKValue,FDOCUMENTSTATUS From T_PX_TRAININGPROINFO where FITEMID in ({result}) and (FDOCUMENTSTATUS='A' OR FDOCUMENTSTATUS='D')");
                        successPKs = saveResult.OperateResult.Where(o => o.SuccessStatus == true && dataTable.Any(f => f.GetInt32(0).ToString() == o.PKValue.ToString())).Select(x => x.PKValue).Distinct().ToArray();
                        break;
                    case DataType.LQKJ_ClassDetails://班级通讯录
                        dataTable = DBUtils.ExecuteEnumerable(this.Context, $"select FID  as PKValue,FDOCUMENTSTATUS From T_PX_ADDRESSBOOK where FID in ({result}) and (FDOCUMENTSTATUS='A' OR FDOCUMENTSTATUS='D')");
                        successPKs = saveResult.OperateResult.Where(o => o.SuccessStatus == true && dataTable.Any(f => f.GetInt64(0).ToString() == o.PKValue.ToString())).Select(x => x.PKValue).Distinct().ToArray();
                        break;
                    case DataType.LQKJ_Teacher://教师
                        dataTable = DBUtils.ExecuteEnumerable(this.Context, $"select FTEACHERID  as PKValue,FDOCUMENTSTATUS From T_PX_TEACHER where FTEACHERID in ({result}) and (FDOCUMENTSTATUS='A' OR FDOCUMENTSTATUS='D')");
                        successPKs = saveResult.OperateResult.Where(o => o.SuccessStatus == true && dataTable.Any(f => f.GetInt32(0).ToString() == o.PKValue.ToString())).Select(x => x.PKValue).Distinct().ToArray();
                        break;
                    case DataType.LQKJ_Course://课程
                        dataTable = DBUtils.ExecuteEnumerable(this.Context, $"select FCOURSEID  as PKValue,FDOCUMENTSTATUS From T_PX_COURSE where FCOURSEID in ({result}) and (FDOCUMENTSTATUS='A' OR FDOCUMENTSTATUS='D')");
                        successPKs = saveResult.OperateResult.Where(o => o.SuccessStatus == true && dataTable.Any(f => f.GetInt32(0).ToString() == o.PKValue.ToString())).Select(x => x.PKValue).Distinct().ToArray();
                        break;
                    case DataType.LQKJ_SceneTeaching://现场教学
                        dataTable = DBUtils.ExecuteEnumerable(this.Context, $"select FID  as PKValue,FDOCUMENTSTATUS From T_PX_SCENETEACHING where FID in ({result}) and (FDOCUMENTSTATUS='A' OR FDOCUMENTSTATUS='D')");
                        successPKs = saveResult.OperateResult.Where(o => o.SuccessStatus == true && dataTable.Any(f => f.GetInt64(0).ToString() == o.PKValue.ToString())).Select(x => x.PKValue).Distinct().ToArray();
                        break;
                    default:
                        return;
                }
            }
            else
            {
                return;
            }*/
            //判断全部单据都处于处于审核中或已审核状态
            if (!successPKs.Any())
            {
                return;
            }
            // 提交处理
            var submitService = new SubmitService();
            var submitResult = submitService.Submit(Context, BusinessInfo, successPKs, FormOperationEnum.Submit.ToString(), Option.Copy());
            var isExit = CheckResult(saveResult, submitResult);
            saveResult.MergeResult(submitResult);
            if (isExit)
            {
                // 有提交失败的结果，直接退出
                return;
            }
            // 审核处理
            // 再次筛选中保存成功并且提交也成功的结果
            successPKs = saveResult.OperateResult.Where(o => o.SuccessStatus == true).Select(x => x.PKValue).Distinct().ToArray();
            if (successPKs.Length == 0)
            {
                // 没有提交成功的结果，直接退出
                return;
            }
            var paras = new List<object>() { "1" }; //审核所需参数
            var auditPKs = successPKs.Select(x => new KeyValuePair<object, object>(x, "")).ToList();
            var statusService = new SetStatusService();
            var auditResult = statusService.SetBillStatus(Context, BusinessInfo, auditPKs, paras, FormOperationEnum.Audit.ToString(), Option.Copy());
            isExit = CheckResult(saveResult, auditResult);
            saveResult.MergeResult(auditResult);
            if (isExit)
            {
                //有审核失败的结果，直接退出
                return;
            }
            // 操作完成后刷新单据状态数据
            var billStatusField = this.BusinessInfo.GetBillStatusField();
            var billStatusPropertyName = billStatusField.PropertyName;
            var objs = new BusinessDataReader(Context).Load(e.DataEntitys.Select(o => o[0]).ToArray()
                ,BusinessInfo.GetSubBusinessInfo(new List<string>(new[] { billStatusField.Key })).GetDynamicObjectType());
            foreach (var obj in objs)
            {
                var saveObj = e.DataEntitys.FirstOrDefault(o => o[0].ToString() == obj[0].ToString());
                if (saveObj != null)
                {
                    saveObj[billStatusPropertyName] = obj[billStatusPropertyName];
                }
            }
        }
        /// <summary>
        /// 检查操作结果，判断是否需要退出
        /// </summary>
        /// <param name="saveResult"></param>
        /// <param name="nextResult"></param>
        /// <returns></returns>
        private bool CheckResult(IOperationResult saveResult, IOperationResult nextResult)
        {
            if (nextResult == null)
            {
                saveResult.IsSuccess = false;
                return true;
            }
            if (!nextResult.IsSuccess)
            {
                // 操作失败
                saveResult.IsSuccess = false;
                return true;
            }
            if (nextResult.InteractionContext != null)
            {
                // 交互异常
                saveResult.IsSuccess = false;
                return true;
            }
            var failResults = nextResult.OperateResult.Where(e => e.SuccessStatus == false).ToArray();
            if (failResults.Length > 0 || nextResult.ValidationErrors.Count > 0)
            {
                // 操作异常，校验异常
                saveResult.IsSuccess = false;
                return true;
            }
            return false;
        }
    }
}
