// 警告：某些程序集引用无法自动解析。这可能会导致某些部分反编译错误，
// 例如属性 getter/setter 访问。要获得最佳反编译结果，请手动将缺少的引用添加到加载的程序集列表中。
// Kingdee.K3.MFG.ENG.Business.PlugIn.DynamicForm.BomTree
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using Kingdee.BOS;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Log;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.BarElement;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Core.Metadata.FormElement;
using Kingdee.BOS.Core.NetworkCtrl;
using Kingdee.BOS.Core.Permission;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.Resource;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.K3.BD.ServiceHelper;
using Kingdee.K3.Core.MFG.ENG.BomExpand;
using Kingdee.K3.Core.MFG.ENG.BomTree;
using Kingdee.K3.Core.MFG.ENG.ParamOption;
using Kingdee.K3.Core.MFG.EntityHelper;
using Kingdee.K3.Core.MFG.EnumConst;
using Kingdee.K3.Core.MFG.Utils;
using Kingdee.K3.MFG.BusinessCommon.BillPlugIn;
using Kingdee.K3.MFG.ServiceHelper;
using Kingdee.K3.MFG.ServiceHelper.ENG;
using LF.K3.SCM.BusinessPlugin;

[Description("BOM树形维护1")]
[HotUpdate]
public class BomTree1 : AbstractMFGDynamicFormPlugIn
{
    private const string PanelKey = "FPanel";

    private const string TreeViewKey = "FTreeView";

    private bool IsSaveSuccess { get; set; }

    private BomTreeViewDataManager BomTreeDatasMger { get; set; }

    private BomExpandNodeTreeMode CurSelNodeData { get; set; }

    private TreeView CurTreeView => ((AbstractDynamicFormPlugIn)(object)this).View.GetControl<TreeView>("FTreeView");

    private IDynamicFormView BomView => ((AbstractDynamicFormPlugIn)(object)this).View.GetView(CustomCalendarBillPageId);

    protected string CustomCalendarBillPageId { get; set; }

    private PermissionAuthResult authSynsResult { get; set; }
    private Dictionary<string, ChirdNode> allTree { get; set; }
    public override void OnInitialize(InitializeEventArgs e)
    {
        base.OnInitialize(e);
        CustomCalendarBillPageId = SequentialGuid.NewGuid().ToString();
        BomTreeDatasMger = new BomTreeViewDataManager();
    }

    public override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        allTree = new Dictionary<string, ChirdNode>();
        CurSelNodeData = BomTreeDatasMger.CreateDefCurSelNodeData();
        CurTreeView.SetRootVisible(visible: false);
        long num = MFGBillUtil.GetParam<long>(((AbstractDynamicFormPlugIn)(object)this).View, "BOMID", 0L);
        long num2 = MFGBillUtil.GetParam<long>(((AbstractDynamicFormPlugIn)(object)this).View, "MATERIALID", 0L);
        if (num > 0 && num2 <= 0)
        {
            num2 = GetBomMtrl(num);
        }
        else if (num <= 0 && num2 > 0)
        {
            long[] materialMasterAndUserOrgId = MaterialServiceHelper.GetMaterialMasterAndUserOrgId(((AbstractDynamicFormPlugIn)this).Context, num2);
            num = BOMServiceHelper.GetHightVersionBomKey(((AbstractDynamicFormPlugIn)this).Context, materialMasterAndUserOrgId[0], materialMasterAndUserOrgId[1]);
        }
        if (num > 0)
        {
            List<BomExpandNodeTreeMode> list = DoExpand(num, num2);
            if (!list.IsEmpty())
            {
                BomTreeDatasMger.AddBomNodeMode(BomTreeDatasMger.RootNode.id, list);
                SetViewRootNode();
            }
        }
        else if (num2 > 0)
        {
            FormMetadata formMetaData = MetaDataServiceHelper.GetFormMetaData(((AbstractDynamicFormPlugIn)this).Context, "BD_MATERIAL");
            CurSelNodeData.MaterId = BusinessDataServiceHelper.LoadSingle(((AbstractDynamicFormPlugIn)this).Context, (object)num2, formMetaData.BusinessInfo.GetDynamicObjectType(), (OperateOption)null);
            if (num <= 0)
            {
                CurSelNodeData.SupplyerOrg = CurSelNodeData.MaterUseOrg;
            }
        }
        WriteInLog();
        ShowCustomBomForm(CurSelNodeData);
    }

    public override void AfterBindData(EventArgs e)
    {
        base.AfterBindData(e);
        if (((AbstractDynamicFormPlugIn)this).Context.IsStandardEdition())
        {
            ((AbstractDynamicFormPlugIn)(object)this).View.GetMainBarItem("tbAllocates").Visible = false;
            ((AbstractDynamicFormPlugIn)(object)this).View.GetMainBarItem("tbAllocates").Enabled = false;
            ((AbstractDynamicFormPlugIn)(object)this).View.GetMainBarItem("tbCancelAllocates").Visible = false;
            ((AbstractDynamicFormPlugIn)(object)this).View.GetMainBarItem("tbCancelAllocates").Enabled = false;
            ((AbstractDynamicFormPlugIn)(object)this).View.GetMainBarItem("tbBatchAlloc").Visible = false;
            ((AbstractDynamicFormPlugIn)(object)this).View.GetMainBarItem("tbBatchAlloc").Enabled = false;
            ((AbstractDynamicFormPlugIn)(object)this).View.GetMainBarItem("tbAllocateInquires").Visible = false;
            ((AbstractDynamicFormPlugIn)(object)this).View.GetMainBarItem("tbAllocateInquires").Enabled = false;
        }
    }

    public override void BarItemClick(BarItemClickEventArgs e)
    {
        base.BarItemClick(e);
        switch (e.BarItemKey)
        {
            case "tbSplitNew":
            case "tbNew":
                ShowBomTreeForm();
                break;
            case "tbAllSubmit":
                DoBachOper("Submit");
                break;
            case "tbAllApprove":
                DoBachOper("Audit");
                break;
            case "tbSelectBom":
                ReloadFromBom();
                break;
            case "tbBatchAlloc":
                {
                    if (BomTreeDatasMger.RootNode == null || BomTreeDatasMger.RootNode.children.IsEmpty())
                    {
                        ((AbstractDynamicFormPlugIn)(object)this).View.ShowMessage(ResManager.LoadKDString("没有可分配的BOM.", "015072000012297", SubSystemType.MFG));
                        break;
                    }
                    string id = BomTreeDatasMger.RootNode.children.First().id;
                    BomExpandNodeTreeMode bomExpandNodeTreeMode = BomTreeDatasMger.FindBomNodeMode(id);
                    long bomId_Id = bomExpandNodeTreeMode.BomId_Id;
                    if (bomId_Id == 0)
                    {
                        ((AbstractDynamicFormPlugIn)(object)this).View.ShowMessage(ResManager.LoadKDString("没有可分配的BOM.", "015072000012297", SubSystemType.MFG));
                        break;
                    }
                    string dynamicValue = bomExpandNodeTreeMode.BomId.GetDynamicValue<string>("DocumentStatus");
                    if (dynamicValue != "C")
                    {
                        ((AbstractDynamicFormPlugIn)(object)this).View.ShowMessage(ResManager.LoadKDString("所选BOM版本未经过审核，不能分配.", "015072000012298", SubSystemType.MFG));
                        break;
                    }
                    if (bomExpandNodeTreeMode.BomId.GetDynamicValue("CreateOrgId_Id", 0L) != bomExpandNodeTreeMode.BomId.GetDynamicValue("UseOrgId_Id", 0L))
                    {
                        ((AbstractDynamicFormPlugIn)(object)this).View.ShowErrMessage("", ResManager.LoadKDString("创建组织和使用组织不同，不能执行批量分配!", "015072000012299", SubSystemType.MFG));
                        break;
                    }
                    DynamicFormShowParameter dynamicFormShowParameter = new DynamicFormShowParameter();
                    dynamicFormShowParameter.FormId = "ENG_BOMBatchAllocate";
                    dynamicFormShowParameter.PageId = Guid.NewGuid().ToString();
                    DynamicFormShowParameter dynamicFormShowParameter2 = dynamicFormShowParameter;
                    dynamicFormShowParameter2.OpenStyle.ShowType = ShowType.MainNewTabPage;
                    dynamicFormShowParameter2.CustomParams.Add("CurrentBomId", bomExpandNodeTreeMode.BomId_Id.ToString());
                    ((AbstractDynamicFormPlugIn)(object)this).View.ShowForm(dynamicFormShowParameter2);
                    break;
                }
            case "tbBomSynUpdate":
                ShowListDatas();
                break;
            case "tbTreeCopy":
                TreeCopy();
                break;
            default:
                DoChildOper(e.BarItemKey);
                break;
            case "tbPara":
            case "tbParaList":
            case "tbClose":
                break;
        }
    }

    public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
    {
        base.AfterBarItemClick(e);
        if ((!(e.BarItemKey != "tbSplitSave") || !(e.BarItemKey != "tbSave") || !(e.BarItemKey != "tbSaveTemp")) && IsSaveSuccess)
        {
            //ReExpandBom();
        }
    }

    private void ReExpandBom()
    {
        foreach (TreeNode child in CurSelNodeData.CurTreeNode.children)
        {
            CurTreeView.RemoveNode(child.id);
        }
        DynamicObject dataObject = BomView.Model.DataObject;
        long dynamicObjectItemValue = dataObject.GetDynamicObjectItemValue("Id", 0L);
        long dynamicObjectItemValue2 = dataObject.GetDynamicObjectItemValue("MATERIALID_Id", 0L);
        if (dynamicObjectItemValue <= 0 || dynamicObjectItemValue2 <= 0)
        {
            return;
        }
        List<BomExpandNodeTreeMode> list = DoExpand(dynamicObjectItemValue, dynamicObjectItemValue2);
        if (!list.IsEmpty())
        {
            if (BomTreeDatasMger.IsLstBomNodeModeEmpty())
            {
                BomTreeDatasMger.AddBomNodeMode(BomTreeDatasMger.RootNode.id, list);
                SetViewRootNode();
                ((AbstractDynamicFormPlugIn)(object)this).View.Session["FormInputParam"] = CurSelNodeData;
            }
            else
            {
                BomTreeDatasMger.AddBomNodeMode(CurSelNodeData.CurTreeNode.id, list);
                BomTreeDatasMger.ToTreeNodeObject(CurSelNodeData.CurTreeNode);
                CurTreeView.AddNodes(CurSelNodeData.CurTreeNode.id, CurSelNodeData.CurTreeNode.children);
                CurTreeView.RefreshNode(CurSelNodeData.CurTreeNode.id, CurSelNodeData.CurTreeNode);
            }
        }
    }

    public override void BeforeClosed(BeforeClosedEventArgs e)
    {
        base.BeforeClosed(e);
        if (BomView == null || !BomView.Model.DataChanged)
        {
            return;
        }
        e.Cancel = true;
        BomView.ShowMessage(ResManager.LoadKDString("内容已经修改，是否保存？", "015072000002230", SubSystemType.MFG), MessageBoxOptions.YesNoCancel, delegate (MessageBoxResult result)
        {
            switch (result)
            {
                case MessageBoxResult.Yes:
                    DoChildOper("tbSave");
                    break;
                case MessageBoxResult.No:
                    BomView.Model.DataChanged = false;
                    ((AbstractDynamicFormPlugIn)(object)this).View.Close();
                    break;
            }
            BomView.SendDynamicFormAction(((AbstractDynamicFormPlugIn)(object)this).View);
        });
        ((AbstractDynamicFormPlugIn)(object)this).View.SendDynamicFormAction(BomView);
    }

    public override void TreeNodeClick(TreeNodeArgs e)
    {
        base.TreeNodeClick(e);
        if (BomView != null && BomView.Model.DataChanged)
        {
            e.Cancel = true;
            BomView.ShowMessage(ResManager.LoadKDString("内容已经修改，是否保存？", "015072000002230", SubSystemType.MFG), MessageBoxOptions.YesNoCancel, delegate (MessageBoxResult result)
            {
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        DoChildOper("tbSave");
                        if (IsSaveSuccess)
                        {
                            //ReExpandBom();
                        }
                        if (CurSelNodeData != null)
                        {
                            CurTreeView.Select(CurSelNodeData.EntryId);
                        }
                        break;
                    case MessageBoxResult.No:
                        BomView.Model.DataChanged = false;
                        return;
                }
                BomView.SendDynamicFormAction(((AbstractDynamicFormPlugIn)(object)this).View);
            });
            ((AbstractDynamicFormPlugIn)(object)this).View.SendDynamicFormAction(BomView);
        }
        BomExpandNodeTreeMode bomExpandNodeTreeMode = BomTreeDatasMger.FindBomNodeMode(e.NodeId);
        if (bomExpandNodeTreeMode == null)
        {
            var MaterialNumber = e.NodeId;
            string sql = $@"/*dialect*/select T1.FID,t1.FMATERIALID from T_eng_bom T1 LEFT JOIN T_BD_MATERIAL T2 ON T1.FMATERIALID = T2.FMATERIALID WHERE T2.FNUMBER ='{MaterialNumber}'";
            DataTable dt = DBServiceHelper.ExecuteDataSet(this.Context, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                long BomFid = Convert.ToInt64(dt.Rows[0]["FID"]);
                var a = ShowCustomBomForm1(BomFid);
                FormMetadata formMetadata = MetaDataServiceHelper.Load(((AbstractDynamicFormPlugIn)this).Context, "ENG_BOM", true) as FormMetadata;
                DynamicObjectType dynamicObjectType = formMetadata.BusinessInfo.GetDynamicObjectType();
                DynamicObject[] col = BusinessDataServiceHelper.LoadFromCache(((AbstractDynamicFormPlugIn)this).Context, new object[1] { BomFid }, dynamicObjectType);
                //MetaDataServiceHelper.Load()
                // BusinessDataServiceHelper.Load()
                if (col.Count() > 0)
                {
                    CurSelNodeData = new BomExpandNodeTreeMode();
                    CurSelNodeData.EntryId = e.NodeId;
                    var bom = col[0];
                    CurSelNodeData.BomId = bom;
                    CurSelNodeData.MaterId = bom["MATERIALID"] as DynamicObject;
                    CurSelNodeData.SupplyerOrg = CurSelNodeData.MaterUseOrg;
                    TreeNode treeNode = new TreeNode();
                    if (allTree.ContainsKey(e.NodeId))
                    {
                        ChirdNode chirds;
                        allTree.TryGetValue(e.NodeId, out chirds);
                        treeNode.Number = chirds.Number;
                        treeNode.Name = chirds.Name;
                        treeNode.parentid = chirds.parentid;
                        treeNode.text = chirds.text;
                        treeNode.id = chirds.MaterialNumber;
                    }
                    CurSelNodeData.CurTreeNode = treeNode;
                    //CurTreeView.Select(BomFid.ToString());
                }
                //CurSelNodeData.SupplyerOrg
                //MaterId
                //BomId
                //CurTreeNode
                //EntryId  MATERIALID

            }
            else
            {
                ShowCustomBomForm1(0);
                FormMetadata formMetadata = MetaDataServiceHelper.Load(((AbstractDynamicFormPlugIn)this).Context, "ENG_BOM", true) as FormMetadata;
                DynamicObjectType dynamicObjectType = formMetadata.BusinessInfo.GetDynamicObjectType();
                DynamicObject[] col = BusinessDataServiceHelper.LoadFromCache(((AbstractDynamicFormPlugIn)this).Context, new object[1] { 0 }, dynamicObjectType);
                CurSelNodeData = new BomExpandNodeTreeMode();
                CurSelNodeData.EntryId = e.NodeId;
                if (col.Count() > 0)
                {
                    var bom = col[0];
                    CurSelNodeData.BomId = bom;
                    CurSelNodeData.MaterId = bom["MATERIALID"] as DynamicObject;
                    CurSelNodeData.SupplyerOrg = CurSelNodeData.MaterUseOrg;
                }
                TreeNode treeNode = new TreeNode();
                if (allTree.ContainsKey(e.NodeId))
                {
                    ChirdNode chirds;
                    allTree.TryGetValue(e.NodeId, out chirds);
                    treeNode.Number = chirds.Number;
                    treeNode.Name = chirds.Name;
                    treeNode.parentid = chirds.parentid;
                    treeNode.text = chirds.text;
                    treeNode.id = chirds.MaterialNumber;
                }
                CurSelNodeData.CurTreeNode = treeNode;
            }
        }
        if (bomExpandNodeTreeMode == null || !(bomExpandNodeTreeMode.EntryId != CurSelNodeData.EntryId))
        {
            return;
        }
        if (bomExpandNodeTreeMode.BomId_Id <= 0 && !ValidatePermission("fce8b1aca2144beeb3c6655eaf78bc34"))
        {
            e.Cancel = true;
            ((AbstractDynamicFormPlugIn)(object)this).View.ShowMessage(string.Format(ResManager.LoadKDString("没有“物料清单”的“新增”权限！", "015072000002209", SubSystemType.MFG)));
        }
        if (!e.Cancel)
        {
            if (bomExpandNodeTreeMode.BomId_Id > 0 && CheckBOMIsDeleted(bomExpandNodeTreeMode.BomId_Id))
            {
                e.Cancel = true;
                ((AbstractDynamicFormPlugIn)(object)this).View.ShowMessage(string.Format(ResManager.LoadKDString("您要读取的数据在系统中不存在，可能已经被删除！[ID={0},Type=ENG_BOM]", "015072000018150", SubSystemType.MFG), bomExpandNodeTreeMode.BomId_Id), MessageBoxType.Error);
            }
            else
            {
                e.Cancel = !ShowCustomBomForm(bomExpandNodeTreeMode);
            }
        }
        if (!e.Cancel)
        {
            CurSelNodeData = bomExpandNodeTreeMode;
        }
        else
        {
            CurTreeView.Select(CurSelNodeData.EntryId);
        }
    }

    private bool CheckBOMIsDeleted(long bomId)
    {
        FormMetadata formMetadata = MetaDataServiceHelper.Load(((AbstractDynamicFormPlugIn)this).Context, "ENG_BOM", true) as FormMetadata;
        DynamicObjectType dynamicObjectType = formMetadata.BusinessInfo.GetDynamicObjectType();
        DynamicObject[] col = BusinessDataServiceHelper.LoadFromCache(((AbstractDynamicFormPlugIn)this).Context, new object[1] { bomId }, dynamicObjectType);
        return col.IsEmpty();
    }

    public override void CustomEvents(CustomEventsArgs e)
    {
        base.CustomEvents(e);
        if (e.EventName == "ReflashBomData" && e.EventArgs == "1")
        {
            // BomTreeDatasMger.ReSetBomData(CurTreeView, BomView.Model.DataObject, CurSelNodeData.CurTreeNode.id);
            SetViewRootNode();
            IsSaveSuccess = true;
        }
        if (e.EventName == "ChangeTreeBySupplyOrg")
        {
            DeleteChildNote(e.EventArgs);
        }
        if (e.EventName == "BOMTREETOBOM")
        {
            ((AbstractDynamicFormPlugIn)(object)this).View.Close();
        }
    }

    private void SetViewRootNode()
    {
        BomTreeDatasMger.ToTreeNodeObject();
        string id = BomTreeDatasMger.RootNode.children.First().id;
        string txt = BomTreeDatasMger.RootNode.children.First().text;
        var parameterDate = this.Model.ParameterData;//获取  物料清单-树形维护用户参数
        char SplitStr = Convert.ToChar(parameterDate["SplitCode"]);
        var strarry = txt.Split(SplitStr);
        string sqlParameter = "";
        string text1 = "";
        string text2 = "";
        if (strarry.Length > 0)
        {
            var IsBomId = parameterDate["BomId"].ToString();
            var Number = parameterDate["Number"].ToString();
            var Name = parameterDate["Name"].ToString();
            Logger.Info("IsBomId", "IsBomId");
            if (Number == "False" || Name == "False")//物料编码是否勾选
            {
                this.View.ShowErrMessage("用户参数中物料编码和物料名称必须勾选！");
                return;
            }
            if (IsBomId == "True")//BOM版本是否勾选
            {
                sqlParameter = $@"where wlnumber='{strarry[1]}'";
                text1 = $@"'{SplitStr}'+ma.FNUMBER+'{SplitStr}'+mc.FNAME";
                text2 = $@"'{SplitStr}'+wl.FNUMBER+'{SplitStr}'+wlmc.FNAME";
            }
            else
            {
                sqlParameter = $@"where wlnumber='{strarry[0]}'";
                text1 = $@"ma.FNUMBER+'{SplitStr}'+mc.FNAME";
                text2 = $@"wl.FNUMBER+'{SplitStr}'+wlmc.FNAME";
            }
        }
        if (sqlParameter != "" && text1 != "" && text2 != "")
        {
            string sql = $@"/*dialect*/with stepCTE AS ( 
select b.FMATERIALID as 父项物料, a.FMATERIALID as 子项物料,a.FID 父项BOMID,a.FENTRYID 子项ID,b.TreeValue 父项名称,b.wlnumber,b.FNUMBER,({text1}) 子项名称,a.FREPLACEGROUP as 项次,a.FSEQ as 序号,
1 AS Lev  from T_ENG_BOMCHILD a inner join 
( select * from
(select ({text2}) TreeValue,wl.FNUMBER as wlnumber,bom.* from T_ENG_BOM bom 
left join T_BD_MATERIAL wl on bom.FMATERIALID=wl.FMATERIALID
left join (select * from T_BD_MATERIAL_L where FLOCALEID=2052) wlmc on wl.FMATERIALID=wlmc.FMATERIALID and bom.FMATERIALID=wlmc.FMATERIALID) 
as T0   {sqlParameter}) b on a.FID=b.FID 
inner join T_BD_MATERIAL ma on a.FMATERIALID=ma.FMATERIALID 
inner join (select * from T_BD_MATERIAL_L where FLOCALEID=2052) mc on a.FMATERIALID=mc.FMATERIALID 
union all
select c.f as 父项物料 ,c.z as 子项物料,c.FID 父项BOMID,c.FENTRYID 子项ID,c.TreeValue 父项名称,wlnumbe,c.FNUMBER,c.子项名称,c.FREPLACEGROUP  as 项次,c.FSEQ 序号,cte.Lev+1  from 
(
select a.FMATERIALID z ,b.FMATERIALID f,a.FID ,a.FENTRYID,b.TreeValue ,({text1}) 子项名称 ,b.FNUMBER,b.wlnumber as wlnumbe,a.FREPLACEGROUP,a.FSEQ
from T_ENG_BOMCHILD a inner join 
( select * from
(select ({text2}) TreeValue,wl.FNUMBER as wlnumber,bom.* from T_ENG_BOM bom 
inner join T_BD_MATERIAL wl on bom.FMATERIALID=wl.FMATERIALID
inner join (select * from T_BD_MATERIAL_L where FLOCALEID=2052) wlmc on wl.FMATERIALID=wlmc.FMATERIALID and bom.FMATERIALID=wlmc.FMATERIALID) 
as T0  )b on a.FID=b.FID  
inner join T_BD_MATERIAL ma on a.FMATERIALID=ma.FMATERIALID 
inner join (select * from T_BD_MATERIAL_L where FLOCALEID=2052) mc on a.FMATERIALID=mc.FMATERIALID 
) c 
inner join stepCTE cte on cte.子项物料=c.f
) 
select stepCTE.*,
 case b.FDOCUMENTSTATUS when 'C' then '已审核' else '未审核' end states,
case b.FFORBIDSTATUS when 'B' then '禁用' else '未禁用' end Disables,
case f.FERPCLSID when '2' then '1' when '3' then '1' else '2' end  FERPCLSID,w.FNUMBER as materilnumber,l.FNAME from stepCTE 
left join t_BD_MaterialBase f on stepCTE.子项物料=f.FMATERIALID 
left join T_ENG_BOM b on stepCTE.父项BOMID=b.FID 
left join T_BD_MATERIAL w on stepCTE.子项物料=w.FMATERIALID 
left join (select * from T_BD_MATERIAL_L where FLOCALEID=2052) l on stepCTE.子项物料=l.FMATERIALID order by Lev,父项BOMID,项次,序号";
            DataTable dt = DBServiceHelper.ExecuteDataSet(this.Context, sql).Tables[0];
            Logger.Info("sql", sql);
            Dictionary<string, List<ChirdNode>> all = new Dictionary<string, List<ChirdNode>>();//所有
            Dictionary<string, List<ChirdNode>> Examine = new Dictionary<string, List<ChirdNode>>();//未审核
            Dictionary<string, List<ChirdNode>> Disable = new Dictionary<string, List<ChirdNode>>();//禁用
            allTree = new Dictionary<string, ChirdNode>();
            HashSet<string> hs = new HashSet<string>();//自制
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var wl = dt.Rows[i]["materilnumber"].ToString();

                if (!allTree.ContainsKey(wl))
                {
                    ChirdNode node = new ChirdNode();
                    node.parentid = dt.Rows[i]["父项物料"].ToString();
                    node.Name = dt.Rows[i]["FNAME"].ToString();
                    node.Number = dt.Rows[i]["FNUMBER"].ToString();
                    node.text = dt.Rows[i]["子项名称"].ToString();
                    node.MaterialNumber = dt.Rows[i]["materilnumber"].ToString();
                    allTree.Add(wl, node);
                }
                //所有数据
                if (!all.ContainsKey(dt.Rows[i]["wlnumber"].ToString()))
                {
                    List<ChirdNode> list = new List<ChirdNode>();
                    string ID = dt.Rows[i]["父项物料"].ToString();
                    DataRow[] dr = dt.Select("父项物料='" + ID + "'");
                    for (int j = 0; j < dr.Length; j++)
                    {
                        ChirdNode node = new ChirdNode();
                        node.parentid = dr[j]["父项物料"].ToString();
                        node.Name = dr[j]["FNAME"].ToString();
                        node.Number = dr[j]["FNUMBER"].ToString();
                        node.text = dr[j]["子项名称"].ToString();
                        node.MaterialNumber = dr[j]["materilnumber"].ToString();
                        list.Add(node);
                    }
                    if (list.Count > 0)
                    {
                        all.Add(dt.Rows[i]["wlnumber"].ToString(), list);
                    }
                }
                //自制委外
                if (dt.Rows[i]["FERPCLSID"].ToString() == "1")
                {
                    string ID = dt.Rows[i]["子项物料"].ToString();
                    DataRow[] dr = dt.Select("父项物料='" + ID + "'");
                    if (dr.Length <= 0)
                    {
                        hs.Add(dt.Rows[i]["materilnumber"].ToString());
                    }
                }
                //未审核
                if (dt.Rows[i]["states"].ToString() == "未审核")
                {
                    if (!Examine.ContainsKey(dt.Rows[i]["wlnumber"].ToString()))
                    {
                        string ID = dt.Rows[i]["父项物料"].ToString();
                        DataRow[] dr = dt.Select("父项物料='" + ID + "'");
                        List<ChirdNode> list = new List<ChirdNode>();
                        for (int j = 0; j < dr.Length; j++)
                        {
                            ChirdNode node = new ChirdNode();
                            node.parentid = dr[j]["父项物料"].ToString();
                            node.Name = dr[j]["FNAME"].ToString();
                            node.Number = dr[j]["FNUMBER"].ToString();
                            node.text = dr[j]["子项名称"].ToString();
                            node.MaterialNumber = dr[j]["materilnumber"].ToString();
                            list.Add(node);
                        }
                        if (list.Count > 0)
                        {
                            Examine.Add(dt.Rows[i]["wlnumber"].ToString(), list);

                        }
                    }
                }
                //禁用
                if (dt.Rows[i]["Disables"].ToString() == "禁用")
                {
                    if (!Disable.ContainsKey(dt.Rows[i]["wlnumber"].ToString()))
                    {
                        string ID = dt.Rows[i]["父项物料"].ToString();
                        DataRow[] dr = dt.Select("父项物料='" + ID + "'");
                        List<ChirdNode> list = new List<ChirdNode>();
                        for (int j = 0; j < dr.Length; j++)
                        {
                            ChirdNode node = new ChirdNode();
                            node.parentid = dr[j]["父项物料"].ToString();
                            node.Name = dr[j]["FNAME"].ToString();
                            node.Number = dr[j]["FNUMBER"].ToString();
                            node.text = dr[j]["子项名称"].ToString();
                            node.MaterialNumber = dr[j]["materilnumber"].ToString();
                            list.Add(node);
                        }
                        if (list.Count > 0)
                        {
                            Disable.Add(dt.Rows[i]["wlnumber"].ToString(), list);
                        }
                    }
                }
            }
            TreeNode treeNodeLst1 = BomTreeDatasMger.RootNode.children.First();
            WalkNode1(treeNodeLst1, all, Examine, Disable, hs);

            //CurSelNodeData = BomTreeDatasMger.FindBomNodeMode(id);
            CurTreeView.SetRootNode(BomTreeDatasMger.RootNode);
            CurTreeView.SetRootVisible(visible: false);
            CurTreeView.Select(id);
            //if (MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "IsExpandTree", false))
            //{
            //    TreeNode treeNodeLst = BomTreeDatasMger.RootNode.children.First();
            //    WalkNode(CurTreeView, treeNodeLst);
            //    CurTreeView.InvokeControlMethod("ExpandTree");
            //}
        }
    }
    private void WalkNode1(TreeNode treeNodeLst, Dictionary<string, List<ChirdNode>> all, Dictionary<string, List<ChirdNode>> Examine, Dictionary<string, List<ChirdNode>> Disable, HashSet<string> hs)
    {
        Logger.Info("all.count", all.Count.ToString());
        Logger.Info("Examine.count", Examine.Count.ToString());
        Logger.Info("Disable.count", Disable.Count.ToString());
        Logger.Info("hs.count", hs.Count.ToString());

        var txt = "";
        var parameterDate = this.Model.ParameterData;//获取  物料清单-树形维护用户参数
        char SplitStr = Convert.ToChar(parameterDate["SplitCode"]);
        var strarry = treeNodeLst.text.Split(SplitStr);
        var IsBomId = parameterDate["BomId"].ToString();
        if (strarry.Length > 0)
        {
            Logger.Info("IsBomId", IsBomId);
            if (IsBomId == "True")//BOM版本是否勾选
            {
                txt = strarry[1];
            }
            else
            {
                txt = strarry[0];
            }
            Logger.Info("txt", txt);
        }

        if (Examine.ContainsKey(txt))
        {
            treeNodeLst.Forecolor = "#0000FF";
            List<TreeNode> nodes = new List<TreeNode>();
            //var a = Examine[treeNodeLst.text.Split('*')[0]].Count;
            for (int i = 0; i < Examine[txt].Count; i++)
            {
                TreeNode treeNode = new TreeNode();
                if (IsBomId == "True")//BOM版本是否勾选
                {
                    if (all.ContainsKey(Examine[txt][i].MaterialNumber))
                    {
                        List<ChirdNode> chirds;
                        all.TryGetValue(Examine[txt][i].MaterialNumber, out chirds);
                        ChirdNode chird = chirds.First();
                        treeNode.Number = Examine[txt][i].Number;
                        treeNode.Name = Examine[txt][i].Name;
                        treeNode.parentid = Examine[txt][i].parentid;
                        treeNode.text = chird.Number + Examine[txt][i].text;
                        treeNode.id = Examine[txt][i].MaterialNumber;
                    }
                    else
                    {
                        treeNode.Number = Examine[txt][i].Number;
                        treeNode.Name = Examine[txt][i].Name;
                        treeNode.parentid = Examine[txt][i].parentid;
                        treeNode.text = Examine[txt][i].text;
                        treeNode.id = Examine[txt][i].MaterialNumber;
                    }
                }
                else
                {
                    treeNode.Number = Examine[txt][i].Number;
                    treeNode.Name = Examine[txt][i].Name;
                    treeNode.parentid = Examine[txt][i].parentid;
                    treeNode.text = Examine[txt][i].text;
                    treeNode.id = Examine[txt][i].MaterialNumber;
                }

                nodes.Add(treeNode);
            }
            treeNodeLst.children = nodes;
        }
        else
        if (Disable.ContainsKey(txt))
        {
            treeNodeLst.Forecolor = "#EE0000";
            List<TreeNode> nodes = new List<TreeNode>();
            // var a = Disable[treeNodeLst.text.Split('*')[0]].Count;
            for (int i = 0; i < Disable[txt].Count; i++)
            {
                TreeNode treeNode = new TreeNode();
                if (IsBomId == "True")//BOM版本是否勾选
                {
                    if (all.ContainsKey(Disable[txt][i].MaterialNumber))
                    {
                        List<ChirdNode> chirds;
                        all.TryGetValue(Disable[txt][i].MaterialNumber, out chirds);
                        ChirdNode chird = chirds.First();
                        treeNode.Number = Disable[txt][i].Number;
                        treeNode.Name = Disable[txt][i].Name;
                        treeNode.parentid = Disable[txt][i].parentid;
                        treeNode.text = chird.Number + Disable[txt][i].text;
                        treeNode.id = Disable[txt][i].MaterialNumber;
                    }
                    else
                    {
                        treeNode.Number = Disable[txt][i].Number;
                        treeNode.Name = Disable[txt][i].Name;
                        treeNode.parentid = Disable[txt][i].parentid;
                        treeNode.text = Disable[txt][i].text;
                        treeNode.id = Disable[txt][i].MaterialNumber;
                    }
                }
                else
                {
                    treeNode.Number = Disable[txt][i].Number;
                    treeNode.Name = Disable[txt][i].Name;
                    treeNode.parentid = Disable[txt][i].parentid;
                    treeNode.text = Disable[txt][i].text;
                    treeNode.id = Disable[txt][i].MaterialNumber;
                }

                nodes.Add(treeNode);
            }
            treeNodeLst.children = nodes;
        }
        else
        if (hs.Contains(txt))
        {
            treeNodeLst.Forecolor = "#FF00FF";
        }
        else
        if (all.ContainsKey(txt))
        {
            List<TreeNode> nodes = new List<TreeNode>();
            //var a = Examine[treeNodeLst.text.Split('*')[0]].Count;
            for (int i = 0; i < all[txt].Count; i++)
            {
                TreeNode treeNode = new TreeNode();
                if (IsBomId == "True")//BOM版本是否勾选
                {
                    if (all.ContainsKey(all[txt][i].MaterialNumber))
                    {
                        List<ChirdNode> chirds;
                        all.TryGetValue(all[txt][i].MaterialNumber, out chirds);
                        ChirdNode chird = chirds.First();
                        treeNode.Number = all[txt][i].Number;
                        treeNode.Name = all[txt][i].Name;
                        treeNode.parentid = all[txt][i].parentid;
                        treeNode.text = chird.Number + all[txt][i].text ;
                        treeNode.id = all[txt][i].MaterialNumber;
                    }
                    else
                    {
                        treeNode.Number = all[txt][i].Number;
                        treeNode.Name = all[txt][i].Name;
                        treeNode.parentid = all[txt][i].parentid;
                        treeNode.text = all[txt][i].text ;
                        treeNode.id = all[txt][i].MaterialNumber;
                    }
                }
                else
                {
                    treeNode.Number = all[txt][i].Number;
                    treeNode.Name = all[txt][i].Name;
                    treeNode.parentid = all[txt][i].parentid;
                    treeNode.text = all[txt][i].text ;
                    treeNode.id = all[txt][i].MaterialNumber;
                }
                nodes.Add(treeNode);
            }
            treeNodeLst.children = nodes;
        }
        if (treeNodeLst.children.Count <= 0)
        {
            return;
        }
        foreach (TreeNode child in treeNodeLst.children)
        {
            CurTreeView.InvokeControlMethod("ExpandNode", child.id);
            WalkNode1(child, all, Examine, Disable, hs);
        }
    }
    private void WalkNode(TreeView CurTreeView, TreeNode treeNodeLst)
    {
        if (treeNodeLst.children.Count <= 0)
        {
            return;
        }
        foreach (TreeNode child in treeNodeLst.children)
        {
            CurTreeView.InvokeControlMethod("ExpandNode", child.id);
            WalkNode(CurTreeView, child);
        }
    }

    private void DeleteChildNote(string materialId)
    {
        BomExpandNodeTreeMode bomExpandNodeTreeMode = BomTreeDatasMger.FindBomNodeModeByMaterail(Convert.ToInt64(materialId));
        if (bomExpandNodeTreeMode == null)
        {
            return;
        }
        foreach (TreeNode child in bomExpandNodeTreeMode.CurTreeNode.children)
        {
            CurTreeView.RemoveNode(child.id);
        }
    }

    private List<BomExpandNodeTreeMode> DoExpand(long bomId_Id, long materialId_Id)
    {
        MemBomExpandOption_ForPSV memBomExpandOption_ForPSV = BuildBomExpandOption();
        List<DynamicObject> list = BuildBomExpandSourceData(bomId_Id, materialId_Id);
        List<DynamicObject> bomQueryForwardResult = BomQueryServiceHelper.GetBomQueryForwardResult(((AbstractDynamicFormPlugIn)this).Context, list, memBomExpandOption_ForPSV);
        FormMetadata formMetaData = MetaDataServiceHelper.GetFormMetaData(((AbstractDynamicFormPlugIn)this).Context, "BD_MATERIAL");
        FormMetadata formMetaData2 = MetaDataServiceHelper.GetFormMetaData(((AbstractDynamicFormPlugIn)this).Context, "ENG_BOM");
        ComboField erpClsIdField = formMetaData.BusinessInfo.GetField("FErpClsID") as ComboField;
        ComboField dosageTypeField = formMetaData2.BusinessInfo.GetField("FDOSAGETYPE") as ComboField;
        bool[] isTreeNameItemsShow = new bool[11]
        {
            MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "BomId", false),
            MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "Number", false),
            MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "Name", false),
            MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "Specification", false),
            MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "ErpClsID", false),
            MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "DosageType", false),
            MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "ChildUnitId", false),
            MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "Numerator", false),
            MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "Denominator", false),
            MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "FixScrapQty", false),
            MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "ScrapRate", false)
        };
        string userParam = MFGBillUtil.GetUserParam<string>(((AbstractDynamicFormPlugIn)(object)this).View, "SplitCode", (string)null);
        bool userParam2 = MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "OnlyShowIsMainPrd", false);
        bool userParam3 = MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "IsShowSubMtrl", false);
        List<BomExpandNodeTreeMode> list2 = new List<BomExpandNodeTreeMode>();
        foreach (DynamicObject item in bomQueryForwardResult)
        {
            BomExpandNodeTreeMode bomExpandNodeTreeMode = new BomExpandNodeTreeMode(userParam2, erpClsIdField, dosageTypeField, isTreeNameItemsShow, userParam, userParam3, item);
            if (Convert.ToInt64(item["BomLevel"]) == 0 && CurSelNodeData != null)
            {
                bomExpandNodeTreeMode.ParentBomEntryId = CurSelNodeData.ParentBomEntryId;
            }
            list2.Add(bomExpandNodeTreeMode);
        }
        return list2;
    }

    private MemBomExpandOption_ForPSV BuildBomExpandOption()
    {
        MemBomExpandOption_ForPSV memBomExpandOption_ForPSV = new MemBomExpandOption_ForPSV();
        memBomExpandOption_ForPSV.ExpandLevelTo = 0;
        memBomExpandOption_ForPSV.ExpandVirtualMaterial = true;
        memBomExpandOption_ForPSV.DeleteVirtualMaterial = false;
        memBomExpandOption_ForPSV.ExpandSkipRow = true;
        memBomExpandOption_ForPSV.DeleteSkipRow = false;
        memBomExpandOption_ForPSV.IsShowOutSource = true;
        memBomExpandOption_ForPSV.BomExpandId = SequentialGuid.NewGuid().ToString();
        memBomExpandOption_ForPSV.ParentCsdYieldRate = false;
        memBomExpandOption_ForPSV.ChildCsdYieldRate = false;
        memBomExpandOption_ForPSV.Mode = Enums.BomExpand.Enu_BomExpandMode.KdMemoryOnly;
        bool flag = (memBomExpandOption_ForPSV.CsdSubstitution = MFGBillUtil.GetUserParam<bool>(((AbstractDynamicFormPlugIn)(object)this).View, "IsShowSubMtrl", false));
        memBomExpandOption_ForPSV.BomExpandCalType = Enums.Enu_BomExpandCalType.kdBySystemProfile;
        memBomExpandOption_ForPSV.Option.SetVariableValue("requireDataPermission", true);
        return memBomExpandOption_ForPSV;
    }

    private List<DynamicObject> BuildBomExpandSourceData(long bomId, long materialId)
    {
        List<DynamicObject> list = new List<DynamicObject>();
        BomForwardSourceDynamicRow bomForwardSourceDynamicRow = BomForwardSourceDynamicRow.CreateInstance();
        bomForwardSourceDynamicRow.MaterialId_Id = materialId;
        bomForwardSourceDynamicRow.BomId_Id = bomId;
        bomForwardSourceDynamicRow.NeedQty = 0m;
        bomForwardSourceDynamicRow.TimeUnit = 1.ToString();
        list.Add(bomForwardSourceDynamicRow.DataEntity);
        return list;
    }
    private bool ShowCustomBomForm1(long bomFormParam, bool isFromSelectBill = false)
    {
        if (!ValidatePermission("6e44119a58cb4a8e86f6c385e14a17ad"))
        {
            ((AbstractDynamicFormPlugIn)(object)this).View.ShowMessage(string.Format(ResManager.LoadKDString("没有“物料清单”的“查看”权限！", "015072000002210", SubSystemType.MFG)));
            return false;
        }
        OperationStatus status = OperationStatus.VIEW;
        if (bomFormParam > 0 && ValidatePermission("f323992d896745fbaab4a2717c79ce2e"))
        {
            status = OperationStatus.EDIT;
        }
        if (bomFormParam <= 0)
        {
            if (!ValidatePermission("fce8b1aca2144beeb3c6655eaf78bc34"))
            {
                ((AbstractDynamicFormPlugIn)(object)this).View.ShowMessage(string.Format(ResManager.LoadKDString("没有“物料清单”的“新增”权限！", "015072000002209", SubSystemType.MFG)));
                return false;
            }
            status = OperationStatus.ADDNEW;
        }
        IDynamicFormView view = ((AbstractDynamicFormPlugIn)(object)this).View.GetView(CustomCalendarBillPageId);
        if (view == null)
        {
            BillShowParameter billShowParameter = new BillShowParameter();
            billShowParameter.OpenStyle.ShowType = ShowType.InContainer;
            billShowParameter.OpenStyle.TagetKey = "FPanel";
            billShowParameter.FormId = "ENG_BOM";
            billShowParameter.ParentPageId = ((AbstractDynamicFormPlugIn)(object)this).View.PageId;
            billShowParameter.PageId = CustomCalendarBillPageId;
            billShowParameter.PKey = bomFormParam.ToString();
            billShowParameter.Status = status;
            billShowParameter.AddBillOptionParameter("FSaveAndNew", false);
            billShowParameter.AddBillOptionParameter("FSaveAndSubmit", false);
            billShowParameter.CustomParams["ShowConfirmDialogWhenChangeOrg"] = "false";
            // ShowBillForm(((AbstractDynamicFormPlugIn)(object)this).View, billShowParameter, bomFormParam);
            view.ShowForm(billShowParameter);
        }
        else
        {
            // ((AbstractDynamicFormPlugIn)(object)this).View.Session["FormInputParam"] = bomFormParam;
            BillOpenParameter billOpenParameter = (BillOpenParameter)view.OpenParameter;
            billOpenParameter.PkValue = bomFormParam.ToString();
            billOpenParameter.Status = status;
            billOpenParameter.CreateFrom = CreateFrom.Default;
            billOpenParameter.SetCustomParameter("ShowConfirmDialogWhenChangeOrg", "false");
            if (isFromSelectBill)
            {
                billOpenParameter.SetCustomParameter("IsFromSelectBill", "true");
            }
            view.Refresh();
            ((AbstractDynamicFormPlugIn)(object)this).View.SendDynamicFormAction(view);
        }
        return true;
    }
    private bool ShowCustomBomForm(BomExpandNodeTreeMode bomFormParam, bool isFromSelectBill = false)
    {
        if (!ValidatePermission("6e44119a58cb4a8e86f6c385e14a17ad"))
        {
            ((AbstractDynamicFormPlugIn)(object)this).View.ShowMessage(string.Format(ResManager.LoadKDString("没有“物料清单”的“查看”权限！", "015072000002210", SubSystemType.MFG)));
            return false;
        }
        OperationStatus status = OperationStatus.VIEW;
        if (bomFormParam.BomId_Id > 0 && ValidatePermission("f323992d896745fbaab4a2717c79ce2e"))
        {
            status = OperationStatus.EDIT;
        }
        if (bomFormParam.BomId_Id <= 0)
        {
            if (!ValidatePermission("fce8b1aca2144beeb3c6655eaf78bc34"))
            {
                ((AbstractDynamicFormPlugIn)(object)this).View.ShowMessage(string.Format(ResManager.LoadKDString("没有“物料清单”的“新增”权限！", "015072000002209", SubSystemType.MFG)));
                return false;
            }
            status = OperationStatus.ADDNEW;
        }
        IDynamicFormView view = ((AbstractDynamicFormPlugIn)(object)this).View.GetView(CustomCalendarBillPageId);
        if (view == null)
        {
            BillShowParameter billShowParameter = new BillShowParameter();
            billShowParameter.OpenStyle.ShowType = ShowType.InContainer;
            billShowParameter.OpenStyle.TagetKey = "FPanel";
            billShowParameter.FormId = "ENG_BOM";
            billShowParameter.ParentPageId = ((AbstractDynamicFormPlugIn)(object)this).View.PageId;
            billShowParameter.PageId = CustomCalendarBillPageId;
            billShowParameter.PKey = bomFormParam.BomId_Id.ToString();
            billShowParameter.Status = status;
            billShowParameter.AddBillOptionParameter("FSaveAndNew", false);
            billShowParameter.AddBillOptionParameter("FSaveAndSubmit", false);
            billShowParameter.CustomParams["ShowConfirmDialogWhenChangeOrg"] = "false";
            ShowBillForm(((AbstractDynamicFormPlugIn)(object)this).View, billShowParameter, bomFormParam);
        }
        else
        {
            ((AbstractDynamicFormPlugIn)(object)this).View.Session["FormInputParam"] = bomFormParam;
            BillOpenParameter billOpenParameter = (BillOpenParameter)view.OpenParameter;
            billOpenParameter.PkValue = bomFormParam.BomId_Id.ToString();
            billOpenParameter.Status = status;
            billOpenParameter.CreateFrom = CreateFrom.Default;
            billOpenParameter.SetCustomParameter("ShowConfirmDialogWhenChangeOrg", "false");
            if (isFromSelectBill)
            {
                billOpenParameter.SetCustomParameter("IsFromSelectBill", "true");
            }
            view.Refresh();
            ((AbstractDynamicFormPlugIn)(object)this).View.SendDynamicFormAction(view);
        }
        return true;
    }

    public void ShowBillForm(IDynamicFormView view, BillShowParameter billShowPara, object inputParam = null, Action<FormResult> action = null)
    {
        if (view == null || billShowPara == null)
        {
            return;
        }
        if (inputParam != null)
        {
            view.Session["FormInputParam"] = inputParam;
        }
        if (string.IsNullOrWhiteSpace(billShowPara.ParentPageId))
        {
            billShowPara.ParentPageId = view.PageId;
        }
        view.ShowForm(billShowPara, delegate (FormResult result)
        {
            if (action != null)
            {
                action(result);
            }
            if (inputParam != null)
            {
                view.Session["FormInputParam"] = null;
            }
        });
    }

    private bool DoStartParentBomNetworkCtrl(string entityId, out List<NetworkCtrlResult> networkCtrlResults)
    {
        DynamicObject item = null;
        if (!string.IsNullOrWhiteSpace(entityId))
        {
            item = BomTreeDatasMger.FindBomNodeMode(entityId).ParentBomId;
        }
        return DoStartBomNetworkCtrl(new List<DynamicObject> { item }, out networkCtrlResults);
    }

    private bool DoStartParentBomNetworkCtrl(List<DynamicObject> lstBomId, out List<NetworkCtrlResult> networkCtrlResults)
    {
        if (CurSelNodeData.BomId != null && lstBomId.Contains(CurSelNodeData.BomId) && BomView.OpenParameter.Status == OperationStatus.VIEW)
        {
            return DoStartBomNetworkCtrl(new List<DynamicObject> { CurSelNodeData.BomId }, out networkCtrlResults);
        }
        return DoStartBomNetworkCtrl(lstBomId.Where((DynamicObject w) => w != CurSelNodeData.BomId).ToList(), out networkCtrlResults);
    }

    private bool DoStartBomNetworkCtrl(List<DynamicObject> lstBomId, out List<NetworkCtrlResult> networkCtrlResults)
    {
        networkCtrlResults = new List<NetworkCtrlResult>();
        Dictionary<object, string> dictionary = (from w in lstBomId.Distinct()
                                                 where w != null
                                                 select w).ToDictionary((DynamicObject w) => w.GetDynamicObjectItemValue<object>("Id"), (DynamicObject w) => w.GetDynamicObjectItemValue<string>("Number"));
        if (dictionary.IsEmpty())
        {
            return true;
        }
        List<NetworkCtrlResult> list = MFGCommonUtil.DoStartNetworkCtrl(((AbstractDynamicFormPlugIn)(object)this).View.Context, BomView.BusinessInfo, dictionary);
        if (!list.IsEmpty())
        {
            networkCtrlResults.AddRange(list);
            IEnumerable<NetworkCtrlResult> enumerable = list.Where((NetworkCtrlResult w) => !w.StartSuccess);
            if (!enumerable.IsEmpty())
            {
                BomView.ShowMessage(enumerable.First().Message);
                ((AbstractDynamicFormPlugIn)(object)this).View.SendDynamicFormAction(BomView);
                return false;
            }
        }
        return true;
    }

    private void WriteInLog()
    {
        if (((AbstractDynamicFormPlugIn)(object)this).View.ParentFormView != null)
        {
            Form form = ((AbstractDynamicFormPlugIn)(object)this).View.ParentFormView.BillBusinessInfo.GetForm();
            Form form2 = ((AbstractDynamicFormPlugIn)(object)this).View.BillBusinessInfo.GetForm();
            if (form.Id == "BD_MATERIAL" || form.Id == "ENG_BOM" || form.Id == "ENG_BOMTREE")
            {
                ((AbstractDynamicFormPlugIn)(object)this).Model.WriteLog(new LogObject
                {
                    Description = string.Format(ResManager.LoadKDString("{0}进入{1}", "015072000002166", SubSystemType.MFG), form.Name, form2.Name),
                    Environment = OperatingEnvironment.IntoBizObject,
                    OperateName = ResManager.LoadKDString("进入业务对象", "015072000002167", SubSystemType.MFG),
                    SubSystemId = form2.SubsysId,
                    ObjectTypeId = form2.Id
                });
            }
        }
    }

    private long GetBomMtrl(long bomId)
    {
        string text = string.Format("{0}={1}", "FID", bomId);
        List<SelectorItemInfo> list = new List<SelectorItemInfo>();
        list.Add(new SelectorItemInfo("FMATERIALID"));
        List<SelectorItemInfo> list2 = list;
        List<DynamicObject> baseBillInfo = MFGServiceHelper.GetBaseBillInfo(((AbstractDynamicFormPlugIn)this).Context, "ENG_BOM", list2, text, "");
        if (!baseBillInfo.IsEmpty())
        {
            return baseBillInfo.First().GetDynamicObjectItemValue("MATERIALID_Id", 0L);
        }
        return 0L;
    }

    private void DoBachOper(string oper)
    {
        FormOperation operation = BomView.BillBusinessInfo.GetForm().GetOperation(oper);
        if (!VaildatePermission(operation))
        {
            return;
        }
        List<long> lstParentBomEntryId;
        List<DynamicObject> bachDealOper = BomTreeDatasMger.GetBachDealOper(oper, out lstParentBomEntryId);
        if (bachDealOper.IsEmpty())
        {
            BomView.ShowMessage(string.Format(ResManager.LoadKDString("没有可{0}的数据！", "015072000002154", SubSystemType.MFG), operation.OperationName));
            ((AbstractDynamicFormPlugIn)(object)this).View.SendDynamicFormAction(BomView);
            return;
        }
        List<NetworkCtrlResult> networkCtrlResults = null;
        try
        {
            //if (!DoStartParentBomNetworkCtrl(bachDealOper, out networkCtrlResults))
            //{
            //    return;
            //}
            IOperationResult operationResult = null;
            List<KeyValuePair<object, object>> list = null;
            List<object> list2 = null;
            switch (oper)
            {
                case "Submit":
                    if (BomView.Model.DataChanged)
                    {
                        operationResult = BusinessDataServiceHelper.Save(((AbstractDynamicFormPlugIn)(object)this).View.Context, BomView.BillBusinessInfo, new DynamicObject[1] { BomView.Model.DataObject }, OperateOption.Create(), "Save");
                        if (!operationResult.IsSuccess)
                        {
                            break;
                        }
                    }
                    operationResult = BusinessDataServiceHelper.Submit(((AbstractDynamicFormPlugIn)(object)this).View.Context, BomView.BillBusinessInfo, bachDealOper.Select((DynamicObject w) => w.GetDynamicObjectItemValue<object>("Id")).ToArray(), oper, (OperateOption)null);
                    break;
                case "Audit":
                    {
                        list = bachDealOper.Select((DynamicObject w) => new KeyValuePair<object, object>(w.GetDynamicObjectItemValue<object>("Id"), "")).ToList();
                        List<object> list3 = new List<object>();
                        list3.Add("1");
                        list3.Add("");
                        list2 = list3;
                        OperateOption operateOption = OperateOption.Create();
                        operateOption.SetVariableValue("lstParentBomEntryId", lstParentBomEntryId);
                        operationResult = BusinessDataServiceHelper.SetBillStatus(((AbstractDynamicFormPlugIn)(object)this).View.Context, BomView.BillBusinessInfo, list, list2, oper, operateOption);
                        break;
                    }
            }
            if (operationResult != null)
            {
                MFGCommonUtil.BatchWriteLog(((AbstractDynamicFormPlugIn)(object)this).View.Context, BomView.BillBusinessInfo, operationResult, operation);
                MFGBillUtil.ShowOperateResult(BomView, operationResult, operation);
                ((AbstractDynamicFormPlugIn)(object)this).View.SendDynamicFormAction(BomView);
                if (!operationResult.SuccessDataEnity.IsEmpty())
                {
                    ShowCustomBomForm(CurSelNodeData);
                    BomTreeDatasMger.ReSetBomData(CurTreeView, operationResult.SuccessDataEnity.ToList());
                }
            }
        }
        finally
        {
            //MFGCommonUtil.DoCommitNetworkCtrl(((AbstractDynamicFormPlugIn)(object)this).View.Context, networkCtrlResults);
        }
    }

    private void DoChildOper(string barItemKey)
    {
        List<NetworkCtrlResult> networkCtrlResults = null;
        try
        {
            if (barItemKey == "tbSaveTemp" && !ValidateSaveTemp())
            {
                return;
            }
            switch (barItemKey)
            {
                case "tbSaveTemp":
                case "tbSave":
                case "tbSplitSave":
                    //if (!DoStartParentBomNetworkCtrl(CurSelNodeData.EntryId, out networkCtrlResults))
                    //{
                    //    return;
                    //}
                    break;
            }
            switch (barItemKey)
            {
                case "tbSaveTemp":
                case "tbSave":
                case "tbSplitSave":
                    IsSaveSuccess = false;
                    break;
            }
            BarItem childBarItem = GetChildBarItem(barItemKey);
            foreach (FormBusinessService clickAction in childBarItem.ClickActions)
            {
                BomView.InvokeFormOperation(clickAction.GetJsonParameters().First().ToString());
            }
            ((AbstractDynamicFormPlugIn)(object)this).View.SendDynamicFormAction(BomView);
        }
        finally
        {
            //MFGCommonUtil.DoCommitNetworkCtrl(((AbstractDynamicFormPlugIn)(object)this).View.Context, networkCtrlResults);
        }
    }

    private bool ValidateSaveTemp()
    {
        if (MFGBillUtil.GetValue<long>(BomView.Model, "FMATERIALID", -1, 0L, (string)null) <= 0)
        {
            BomView.ShowMessage(ResManager.LoadKDString("当前物料不可为主产品，无法暂存BOM！", "015072000003342", SubSystemType.MFG));
            ((AbstractDynamicFormPlugIn)(object)this).View.SendDynamicFormAction(BomView);
            return false;
        }
        return true;
    }

    private bool ValidatePermission(string permission)
    {
        PermissionAuthResult permissionAuthResult = PermissionServiceHelper.FuncPermissionAuth(((AbstractDynamicFormPlugIn)this).Context, new BusinessObject
        {
            Id = "ENG_BOM",
            SubSystemId = ((AbstractDynamicFormPlugIn)(object)this).View.Model.SubSytemId
        }, permission);
        return permissionAuthResult.Passed;
    }

    private bool VaildatePermission(FormOperation operation)
    {
        bool flag = ValidatePermission(operation.PermissionItemId);
        if (!flag)
        {
            BomView.ShowMessage(string.Format(ResManager.LoadKDString("没有“物料清单”的“{0}”权限！", "015072000002211", SubSystemType.MFG), operation.OperationName));
            ((AbstractDynamicFormPlugIn)(object)this).View.SendDynamicFormAction(BomView);
        }
        return flag;
    }

    private BarItem GetChildBarItem(string barItemKey)
    {
        Dictionary<string, BarItem> allBarItems = BomView.LayoutInfo.GetFormAppearance().Menu.GetAllBarItems();
        return allBarItems[barItemKey];
    }

    private void ShowBomTreeForm()
    {
        Form form = ((AbstractDynamicFormPlugIn)(object)this).View.BusinessInfo.GetForm();
        DynamicFormShowParameter dynamicFormShowParameter = new DynamicFormShowParameter();
        dynamicFormShowParameter.OpenStyle.ShowType = ShowType.MainNewTabPage;
        dynamicFormShowParameter.FormId = form.Id;
        dynamicFormShowParameter.Caption = form.Name;
        ((AbstractDynamicFormPlugIn)(object)this).View.ShowForm(dynamicFormShowParameter);
    }

    private void ReloadFromBom()
    {
        ListShowParameter listShowParameter = new ListShowParameter();
        listShowParameter.FormId = "ENG_BOM";
        listShowParameter.PermissionItemId = "6e44119a58cb4a8e86f6c385e14a17ad";
        long num = Convert.ToInt64(MFGBillUtil.GetValue<long>(((AbstractDynamicFormPlugIn)(object)this).View.GetView(CustomCalendarBillPageId).Model, "FUseOrgId", -1, 0L, (string)null));
        if (num == 0)
        {
            num = ((AbstractDynamicFormPlugIn)this).Context.CurrentOrganizationInfo.ID;
        }
        string empty = string.Empty;
        empty = $" FUseOrgId = '{num}'";
        listShowParameter.ListFilterParameter.Filter = empty;
        listShowParameter.IsIsolationOrg = false;
        listShowParameter.ListType = 2;
        listShowParameter.IsShowApproved = false;
        listShowParameter.IsShowUsed = true;
        listShowParameter.MultiSelect = false;
        listShowParameter.IsLookUp = true;
        ((AbstractDynamicFormPlugIn)(object)this).View.ShowForm(listShowParameter, delegate (FormResult result)
        {
            object returnData = result.ReturnData;
            if (returnData is ListSelectedRowCollection)
            {
                ListSelectedRowCollection listSelectedRowCollection = (ListSelectedRowCollection)returnData;
                if (listSelectedRowCollection.Count != 0)
                {
                    long num2 = Convert.ToInt64(listSelectedRowCollection[0].FieldValues["FBillHead"]);
                    if (num2 > 0)
                    {
                        long bomMtrl = GetBomMtrl(num2);
                        List<BomExpandNodeTreeMode> list = DoExpand(num2, bomMtrl);
                        if (!list.IsEmpty())
                        {
                            BomTreeDatasMger.AddBomNodeMode(BomTreeDatasMger.RootNode.id, list);
                            SetViewRootNode();
                            ShowCustomBomForm(CurSelNodeData);
                        }
                    }
                }
            }
        });
    }

    private void ShowListDatas()
    {
        if (authSynsResult.IsNullOrEmpty())
        {
            authSynsResult = PermissionServiceHelper.FuncPermissionAuth(((AbstractDynamicFormPlugIn)(object)this).View.Context, new BusinessObject
            {
                Id = "ENG_BOM"
            }, "55488307023b99");
        }
        if (!authSynsResult.Passed)
        {
            return;
        }
        if (BomTreeDatasMger.RootNode == null || BomTreeDatasMger.RootNode.children.IsEmpty())
        {
            ((AbstractDynamicFormPlugIn)(object)this).View.ShowMessage(ResManager.LoadKDString("没有可同步更新的BOM", "015072000033346", SubSystemType.MFG));
            return;
        }
        List<long> list = new List<long>();
        List<long> list2 = new List<long>();
        List<DynamicObject> list3 = new List<DynamicObject>();
        List<BomExpandNodeTreeMode> lstBomNodeMode = BomTreeDatasMger.LstBomNodeMode;
        foreach (BomExpandNodeTreeMode item in lstBomNodeMode)
        {
            if (item.BomId != null)
            {
                list.Add(item.BomId_Id);
                long dynamicValue = item.BomId.GetDynamicValue("UseOrgId_Id", 0L);
                list2.Add(dynamicValue);
                list3.Add(item.BomId);
            }
        }
        if (list.IsEmpty())
        {
            ((AbstractDynamicFormPlugIn)(object)this).View.ShowMessage(ResManager.LoadKDString("没有可同步更新的BOM", "015072000033346", SubSystemType.MFG));
            return;
        }
        FormMetadata formMetadata = (FormMetadata)MetaDataServiceHelper.Load(((AbstractDynamicFormPlugIn)(object)this).View.Context, "ENG_BOM", true);
        list3 = BusinessDataServiceHelper.LoadFromCache(((AbstractDynamicFormPlugIn)(object)this).View.Context, ((IEnumerable<long>)list).Select((Func<long, object>)((long s) => s)).ToArray(), formMetadata.BusinessInfo.GetDynamicObjectType()).ToList();
        list3 = list3.Where((DynamicObject w) => w.GetDynamicValue<string>("DocumentStatus") == "C" && w.GetDynamicValue<string>("ForbidStatus") == "A").ToList();
        if (list3.Count == 0)
        {
            ((AbstractDynamicFormPlugIn)(object)this).View.ShowErrMessage(ResManager.LoadKDString("选择的BOM数据状态不为已审核或禁用状态为禁用，请重新选择数据", "015072000018123", SubSystemType.MFG));
            return;
        }
        list = list3.Select((DynamicObject x) => x.GetDynamicValue("Id", 0L)).Distinct().ToList();
        list2 = list3.Select((DynamicObject x) => x.GetDynamicValue("UseOrgId_Id", 0L)).Distinct().ToList();
        FormMetadata formMetadata2 = (FormMetadata)MetaDataServiceHelper.Load(((AbstractDynamicFormPlugIn)(object)this).View.Context, "ENG_BOM_BILLPARAM", true);
        DynamicObject dynamicObject = UserParamterServiceHelper.Load(((AbstractDynamicFormPlugIn)(object)this).View.Context, formMetadata2.BusinessInfo, ((AbstractDynamicFormPlugIn)(object)this).View.Context.UserId, "ENG_BOM", "UserParameter");
        string dynamicValue2 = dynamicObject.GetDynamicValue<string>("UpdateRange");
        string dynamicValue3 = dynamicObject.GetDynamicValue<string>("ConSultDate");
        bool dynamicValue4 = dynamicObject.GetDynamicValue("IsSkipExpand", defValue: false);
        List<long> list4 = new List<long>();
        if (dynamicValue2 == "2")
        {
            list4 = (from w in list3
                     where w.GetDynamicValue("UseOrgId_Id", 0L) == w.GetDynamicValue("CreateOrgId_Id", 0L)
                     select w into s
                     select s.GetDynamicValue("MsterId", 0L)).ToList();
            List<DynamicObject> allocatedBOM = GetAllocatedBOM(list4);
            if (!allocatedBOM.IsEmpty())
            {
                list2.AddRange(allocatedBOM.Select((DynamicObject s) => s.GetDynamicValue("UseOrgId_Id", 0L)).ToList().Except(list2));
                list.AddRange(allocatedBOM.Select((DynamicObject s) => s.GetDynamicValue("Id", 0L)).ToList().Except(list));
                foreach (DynamicObject item2 in allocatedBOM)
                {
                    long bomId = item2.GetDynamicValue("Id", 0L);
                    if (!list3.Any((DynamicObject a) => a.GetDynamicValue("Id", 0L) == bomId))
                    {
                        list3.Add(item2);
                    }
                }
            }
        }
        DynamicFormShowParameter dynamicFormShowParameter = new DynamicFormShowParameter();
        dynamicFormShowParameter.OpenStyle.ShowType = ShowType.Floating;
        dynamicFormShowParameter.FormId = "ENG_SYNSUPDATEPPBOM";
        dynamicFormShowParameter.CustomComplexParams.Add("BomData", list3);
        dynamicFormShowParameter.CustomComplexParams.Add("BomId", list);
        dynamicFormShowParameter.CustomComplexParams.Add("IsShowPrdList", true);
        dynamicFormShowParameter.CustomComplexParams.Add("IsShowSubList", true);
        dynamicFormShowParameter.CustomComplexParams.Add("UserOrgId", list2);
        dynamicFormShowParameter.CustomComplexParams.Add("ConSultDate", dynamicValue3);
        dynamicFormShowParameter.CustomComplexParams.Add("IsSkipExpand", dynamicValue4);
        dynamicFormShowParameter.CustomComplexParams.Add("IsShowPlnList", true);
        ((AbstractDynamicFormPlugIn)(object)this).View.ShowForm(dynamicFormShowParameter);
    }

    private List<DynamicObject> GetAllocatedBOM(List<long> bomMasterIds)
    {
        FormMetadata formMetadata = (FormMetadata)MetaDataServiceHelper.Load(((AbstractDynamicFormPlugIn)(object)this).View.Context, "ENG_BOM", true);
        QueryBuilderParemeter queryBuilderParemeter = new QueryBuilderParemeter();
        queryBuilderParemeter.BusinessInfo = formMetadata.BusinessInfo;
        queryBuilderParemeter.ExtJoinTables.Add(new ExtJoinTableDescription
        {
            TableName = "table(fn_StrSplit(@msterId,',',1))",
            TableNameAs = "tms",
            FieldName = "FID",
            ScourceKey = "FMASTERID"
        });
        queryBuilderParemeter.FilterClauseWihtKey = "FCreateOrgId<>FUseOrgId";
        queryBuilderParemeter.SqlParams.Add(new SqlParam("@msterId", KDDbType.udt_inttable, bomMasterIds.Distinct().ToArray()));
        return BusinessDataServiceHelper.Load(((AbstractDynamicFormPlugIn)(object)this).View.Context, queryBuilderParemeter.BusinessInfo.GetDynamicObjectType(), queryBuilderParemeter).ToList();
    }

    private void TreeCopy()
    {
        List<BomExpandNodeTreeMode> lstBomNodeMode = BomTreeDatasMger.LstBomNodeMode;
        if (!lstBomNodeMode.IsEmpty())
        {
            DynamicFormShowParameter dynamicFormShowParameter = new DynamicFormShowParameter();
            dynamicFormShowParameter.FormId = "ENG_BOMTREECOPY";
            dynamicFormShowParameter.PageId = Guid.NewGuid().ToString();
            DynamicFormShowParameter dynamicFormShowParameter2 = dynamicFormShowParameter;
            dynamicFormShowParameter2.OpenStyle.ShowType = ShowType.MainNewTabPage;
            dynamicFormShowParameter2.CustomComplexParams.Add("treeNodeDatas", lstBomNodeMode);
            ((AbstractDynamicFormPlugIn)(object)this).View.ShowForm(dynamicFormShowParameter2);
            ((AbstractDynamicFormPlugIn)(object)this).View.Close();
        }
    }

    public BomTree1()
        : base()
    {
    }
}
