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 System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;

namespace LQKJ.SaveSubmitAudit.ServicePlugIN
{
    /// <summary>
    /// 公用自动提交审核插件
    /// </summary>
    [HotUpdate, Description("保存提交审核")]
    public class SubmitAudit : AbstractOperationServicePlugIn
    {
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            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;
                }
            }
            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;
        }
    }
}
