using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Core.Validation;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System.Data;
using System.Dynamic;
using System.ComponentModel;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Log;

namespace LF.K3.SCM.AppServerPlugin.AuditChecks
{
    [Description("校验器")]
    [HotUpdate]
    public class AuditCheckPlugIn : AbstractValidator
    {

        public override void Validate(ExtendedDataEntity[] dataEntities, ValidateContext validateContext, Context ctx)
        {
            if (validateContext.IgnoreWarning)
            {
                return; // 警告已经被用户忽略，就不需要再次执行了
            }
            if (dataEntities == null || dataEntities.Length <= 0)
            {
                return;
            }
            Logger.Info("dataEntities:", dataEntities.Length.ToString());
            DataTable dt = null;
            List<int> listnumber = new List<int>();
            List<int> ids = new List<int>();
            foreach (var item in dataEntities)
            {
                listnumber.Add(Convert.ToInt32(item.DataEntity["id"]));
            }
            DataTable dataTable= DBServiceHelper.ExecuteDataSet(this.Context, "select distinct FID from T_ENG_BOMCHILD where FENTRYID in (" + string.Join(",",listnumber) + ")").Tables[0];
            foreach (DataRow item in dataTable.Rows)
            {
                ids.Add(Convert.ToInt32(item["FID"]));
            }
            //var number = "";
            //foreach (var item in dataEntities)
            //{
            //    listnumber.Add(item.BillNo);
            //}
            //var numbernew = listnumber.Distinct();   //去掉重复
            //foreach (var item in numbernew)
            //{
            //    number += "'" + item.Trim() + "'" + ',';
            //}
            //number = number.TrimEnd(',');            //去掉最后一个，
            //获取BOM
            dt = bom(ids);
            if (dt == null || dt.Rows.Count <= 0)
            {
                return;
            }
            int i = 0;
            foreach (var et in dataEntities)
            {
                var FCREATEORGID = Convert.ToInt32(dt.Rows[i]["FCREATEORGID"]);//创建组织
                var FUSEORGID = Convert.ToInt32(dt.Rows[i]["FUSEORGID"]);//使用组织
                Logger.Info("创建组织:", FCREATEORGID.ToString());
                Logger.Info("使用组织:", FUSEORGID.ToString());
                if (FCREATEORGID != FUSEORGID)
                {
                    return;
                }
                //if (et.DataEntity[3].ToString() != dt.Rows[i]["BOMFMATERIALID"].ToString()) continue;
                string zt = dt.Rows[i]["FDocumentStatus"].ToString();
                //如果校验不通过，抛出校验异常
                //如果是BOM则判状态是否审核,否者判断是否建了BOM
                Logger.Info("状态:", zt);
                Logger.Info("物料编码:", dt.Rows[i]["BOMFNUMBER"].ToString());
                if (dt.Rows[i]["BOMFNUMBER"].ToString().IsNullOrEmptyOrWhiteSpace() || dt.Rows[i]["BOMFNUMBER"].ToString() == "")
                {
                    string a = dt.Rows[i]["FERPCLSID"].ToString();
                    if (dt.Rows[i]["FERPCLSID"].ToString() == "2" || dt.Rows[i]["FERPCLSID"].ToString() == "3")
                    {
                        validateContext.AddError(et, new ValidationErrorInfo(
                         "",//出错的字段key，可以空
                         et.DataEntity["id"].ToString(),
                         et.DataEntityIndex,
                         et.RowIndex,
                         "E1",
                         "子项物料为" + dt.Rows[i]["FNUMBER"].ToString() + "未建BOM,请建BOM!",
                         "审核:",
                         ErrorLevel.FatalError
                         )
                         );
                    }
                    else
                    {
                        i++;
                        continue;
                    }
                }
                else
                {
                    //if (zt == null || zt == "") continue;
                    if (zt != "C")
                    {
                        //Convert.ToString(et.DataEntity[0]) //数据包内码，必填，后续操作会据此内码避开此数据包
                        validateContext.AddError(et, new ValidationErrorInfo(
                         "",//出错的字段key，可以空
                         et.DataEntity["id"].ToString(),
                         et.DataEntityIndex,
                         et.RowIndex,
                         "E1",
                         "子项BOM版本为" + dt.Rows[i]["BOMFNUMBER"].ToString() + "未审核,请审核!",
                         "审核:"+et.BillNo,
                         ErrorLevel.FatalError
                         )
                         );
                    }
                }
                i++;
            }

        }
        //获取BOM
        public DataTable bom(List<int> ids)
        {
            DataTable dt = null;
            string sql = string.Format(@"/*dialect*/with stepCTE AS 
				 ( 
				   select b.FMATERIALID as f, a.FMATERIALID as z,a.FID,a.FUNITID,a.FENTRYID,a.FSEQ,ma.FNUMBER,1 AS Lev,b.FCREATEORGID,b.FUSEORGID  from T_ENG_BOMCHILD a inner join ( select * from T_ENG_BOM  where FID in({0})) b on a.FID=b.FID 
				   inner join T_BD_MATERIAL ma on a.FMATERIALID=ma.FMATERIALID 
				   union all
				   select c.f as f ,c.z as z,c.FID,c.FUNITID,c.FENTRYID,c.FSEQ,c.FNUMBER,cte.Lev+1,c.FCREATEORGID,c.FUSEORGID  from 
				   (
				   select a.FMATERIALID z ,b.FMATERIALID f,a.FID,a.FUNITID,a.FENTRYID,a.FSEQ,ma.FNUMBER,b.FCREATEORGID,b.FUSEORGID  from T_ENG_BOMCHILD a inner join T_ENG_BOM b on a.FID=b.FID  inner join T_BD_MATERIAL ma on a.FMATERIALID=ma.FMATERIALID 
				   ) c 
				   inner join stepCTE cte on cte.z=c.f
				 ) 
				  select stepCTE.*,f.FERPCLSID,engbom.FDOCUMENTSTATUS,engbom.FNUMBER as BOMFNUMBER,engbom.FMATERIALID as BOMFMATERIALID from stepCTE 
				  left join t_BD_MaterialBase f on stepCTE.z=f.FMATERIALID 	  
				   left join T_ENG_BOM engbom on stepCTE.z=engbom.FMATERIALID where stepCTE.Lev=1", string.Join(",",ids));
            dt = DBServiceHelper.ExecuteDataSet(this.Context, sql).Tables[0];
            Logger.Info("sql:", sql.ToString());
            return dt;
        }
    }

    [Description("BOM审核校验")]
    [HotUpdate]
    public class AuditCheck : AbstractOperationServicePlugIn
    {
        //public override void OnPreparePropertys(PreparePropertysEventArgs e)
        //{
        //    base.OnPreparePropertys(e);
        //    //加载父级物料编码
        //    e.FieldKeys.Add("FCreateOrgId");
        //    e.FieldKeys.Add("FUseOrgId");
        //}

        public override void OnAddValidators(AddValidatorsEventArgs e)
        {
            base.OnAddValidators(e);
            AuditCheckPlugIn auditcheck = new AuditCheckPlugIn();
            //是否需要校验，true需要
            auditcheck.AlwaysValidate = true;
            //校验单据体
            auditcheck.EntityKey = "FTreeEntity";
            //auditcheck.EntityKey = "FBillHead";
            //加载校验器
            e.Validators.Add(auditcheck);

        }
    }
}
