using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using System.ComponentModel;
using Kingdee.BOS.Util;
using System.Data;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Log;
using Kingdee.BOS.Core.Bill.PlugIn.Args;

namespace LF.K3.SCM.BusinessPlugin
{
    [Description("干预套打数据")]
    [HotUpdate]
    public class BOMPrintPlugin : AbstractBillPlugIn
    {
       
        public override void OnPrepareNotePrintData(PreparePrintDataEventArgs e)
        {
            if (e.DataSourceId == "FTreeEntity" && e.NotePrintTplId== "0db49095-f986-47b4-b511-ade3acdefdee")
            {
                //存储子项
                Dictionary<long, DataRow[]> dicdr = new Dictionary<long, DataRow[]>();
                DataRow[] dr = null;
                //获取父项fid
                string id = e.DataObjects[0][0].ToString();
                //获取父项
                DynamicObject[] obj = e.DataObjects;
                Logger.Info("获取实体", "实体类型:" + obj);
                //创建空的DynamicObject
                DynamicObject tra = new DynamicObject(e.DynamicObjectType);
                //DynamicObject集合
                List<DynamicObject> result = new List<DynamicObject>();
                //存储已经添加过的物料
                HashSet<string> hs = new HashSet<string>();
                DataTable dt = null;
                //动态字段注册
                DynamicObjectType dot = e.DataObjects[0].DynamicObjectType;
                dot.RegisterSimpleProperty(
                "bh",
                typeof(object),
                attributes: new SimplePropertyAttribute() { Alias = "bh" }
                 );
                dot.RegisterSimpleProperty(
                    "Dosage",
                    typeof(object),
                    attributes: new SimplePropertyAttribute() { Alias = "Dosage" }
                );
                for (int i = 0; i < obj.Length; i++)
                {
                    DynamicObject qureyObjs = new DynamicObject(dot);
                    foreach (var p in e.DataObjects[i].DynamicObjectType.Properties)
                    {
                        qureyObjs[p] = e.DataObjects[i][p];
                    }
                    qureyObjs["Dosage"] = Math.Round(Convert.ToDouble(qureyObjs["FNUMERATOR"]) / Convert.ToDouble(qureyObjs["FDENOMINATOR"]), 4);
                    qureyObjs["bh"] = qureyObjs["FTreeEntity_FSEQ"];
                    e.DataObjects[i] = qureyObjs;
                }
                dt = Material(id);
                if (dt.Rows.Count <= 0 || dt == null)return ;
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    if (Convert.ToInt32(dt.Rows[j]["Lev"]) == 1) continue;
                    int a = Convert.ToInt32(dt.Rows[j]["f"]);
                    int dtCount = dt.Rows.Count;
                    if (j == dtCount-1)
                    {
                        int Last = Convert.ToInt32(dt.Rows[j]["f"]);
                        dr = dt.Select("f=" + Last + "");
                        dicdr.Add(Last, dr);
                        break;
                    }
                    int b= Convert.ToInt32(dt.Rows[j + 1]["f"]);
                    if (a == b) continue;
                        dr = dt.Select("f="+a+ "");
                        dicdr.Add(a,dr);
                }
                while (obj.Length != result.Count)
                {
                    foreach (DynamicObject item in obj)
                    {
                        //item["Dosage"] = Math.Round(Convert.ToDouble(item["FNUMERATOR"]) / Convert.ToDouble(item["FDENOMINATOR"]), 4);
                        result.Add(item);
                        //循环子项集合
                        foreach (var dic in dicdr)
                        {
                            if (hs.Contains(dic.Key.ToString())) continue;
                            long d = dic.Key;
                            int idd = Convert.ToInt32(item["FMATERIALIDCHILD_Id"]);
                            if (d == idd)
                            {
                                DataRow[] a = dic.Value;
                                for (int i = 0; i < a.Length; i++)
                                {
                                    object[] s = a[i].ItemArray;
                                    tra["FID"] = s[2];
                                    tra["FCHILDUNITID_U"] = "0";
                                    tra["Dosage"] = Math.Round(Convert.ToDouble(s[13]),4);
                                    tra["FPOSITIONNO"] = s[5];
                                    tra["FMATERIALIDCHILD_Id"] = s[1];
                                    tra["FCHILDUNITID_Id"] = s[6];
                                    tra["FENTRYID"] = s[7];
                                    tra["FTreeEntity_FSEQ"] = s[8];
                                    tra["FUseOrgId"] = "1";
                                    tra["FMATERIALIDCHILD_FNumber"] = s[9];
                                    //tra["FCHILDUNITID_FName"] = "Pce";
                                    tra["FMEMO"] = s[12];
                                    tra["bh"] = item["bh"]+"."+ s[8];
                                    result.Add(tra);
                                    hs.Add(dic.Key.ToString());   //把添加的存在已添加集合
                                    tra = new DynamicObject(e.DynamicObjectType);
                                }
                            }
                        }
                    }
                    obj = result.ToArray();
                    if (hs.Count!= dicdr.Count)
                    {
                        result = new List<DynamicObject>();
                    }
                }
                Kingdee.BOS.ServiceHelper.DBServiceHelper.LoadReferenceObject(this.Context, result.ToArray(), e.DynamicObjectType);
                e.DataObjects = result.ToArray();
                //DynamicObject a = e.DataObjects[0].DynamicObjectType.CreateInstance() as DynamicObject;
            }
            base.OnPrepareNotePrintData(e);
        }

        //查询子项物料
        public DataTable Material(string id)
        {

            string sql = string.Format(@"/*dialect*/with stepCTE AS 
				 ( 
				   select b.FMATERIALID as f, a.FMATERIALID as z,a.FID,a.FNUMERATOR,a.FDENOMINATOR,a.FPOSITIONNO,a.FUNITID,a.FENTRYID,a.FSEQ,ma.FNUMBER,1 AS Lev,row_number() over(partition by b.FMATERIALID order by FSEQ) as rank  from T_ENG_BOMCHILD a inner join ( select * from T_ENG_BOM  where fid={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.FNUMERATOR,c.FDENOMINATOR,c.FPOSITIONNO,c.FUNITID,c.FENTRYID,c.FSEQ,c.FNUMBER,cte.Lev+1,row_number() over(partition by c.f order by c.FSEQ) as rank  from 
				   (
				   select a.FMATERIALID z ,b.FMATERIALID f,a.FID,a.FNUMERATOR,a.FDENOMINATOR,a.FPOSITIONNO,a.FUNITID,a.FENTRYID,a.FSEQ,ma.FNUMBER  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.*,T_ENG_BOMCHILD_l.FMEMO,convert(decimal(18,4),(stepCTE.FNUMERATOR/stepCTE.FDENOMINATOR)) Dosage from stepCTE left join T_ENG_BOMCHILD_l on stepCTE.FENTRYID=T_ENG_BOMCHILD_l.FENTRYID order by Lev", id);
            return DBUtils.ExecuteDataSet(this.Context, sql).Tables[0];
        }
    }
}
