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.Core.Bill;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.FormElement;
using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.WebApi.ServicesStub;
using Kingdee.BOS.Orm;

namespace LF.K3.SCM.AppServerPlugin.CreateBOM
{
    [Description("自动生成BOM")]
    [HotUpdate]
    public class CreateBOM:AbstractOperationServicePlugIn
    {
        //AfterExecuteOperationTransaction:操作执行后，事务结束后
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            if (this.Context.CurrentOrganizationInfo.ID == -1) return;
            Kingdee.BOS.Orm.DataEntity.DynamicObject[] obj =e.DataEntitys;
            List<object> bm = new List<object>();
            HashSet<object> ids = new HashSet<object>();
            List<Kingdee.BOS.Orm.DataEntity.DynamicObject> materigls = new List<Kingdee.BOS.Orm.DataEntity.DynamicObject>();
            foreach (var item in obj)
            {
               ids.Add(item["id"]);
            }
            //判断是否为主产品
            string sql = string.Format("select FNUMBER,FIsMainPrd from T_BD_MATERIAL a inner join t_BD_MaterialProduce b on a.FMATERIALID=b.FMATERIALID  where a.FMATERIALID in('{0}')", string.Join("', '", ids));
            var tb = DBServiceHelper.ExecuteDataSet(this.Context, sql).Tables[0];
            foreach (DataRow row in tb.Rows)
            {
                if (row["FIsMainPrd"].ToString() != "1")
                {
                    continue;
                }
                else
                {
                    bm.Add(row["FNUMBER"].ToString());
                }
                  
            }
            if (bm == null || bm.Count==0) return;
            //StartsWith
            //判断编码是否为"JW"开头且描述中是否有"铝挤"2个字
            string sqll = string.Format("select * from T_BD_MATERIAL where fnumber in ('{0}')", string.Join("', '", bm));
            var table = DBServiceHelper.ExecuteDataSet(this.Context, sqll).Tables[0];
            for (int i = 0; i < table.Rows.Count; i++)
            {
                if (table.Rows[i]["FNUMBER"].ToString().StartsWith("JW")&&table.Rows[i]["F_QAZ_REMARK"].ToString().Contains("铝挤"))
                {
                    //自动生成BOM
                    MaterialArgs materiglgrg = new MaterialArgs();
                    materiglgrg.MATERIALID = table.Rows[i]["FNUMBER"].ToString();
                    materiglgrg.MATERIALIDCHILD = "J001";
                    materiglgrg.Group = "4";
                    //materiglgrg.DOCUMENTSTATUS = "C";
                    SetVoucherArgsToVoucher(materigls,materiglgrg);
                    if (materigls.Count>0)
                    {
                        FormMetadata meta = MetaDataServiceHelper.Load(this.Context, "ENG_BOM") as FormMetadata;
                        BusinessDataServiceHelper.Save(this.Context, meta.BusinessInfo, materigls.ToArray());
                        var bomIds = materigls.Select(t => t["Id"]).ToArray();
                        BusinessDataServiceHelper.Submit(this.Context, meta.BusinessInfo, bomIds, "Submit");
                        BusinessDataServiceHelper.Audit(this.Context, meta.BusinessInfo, bomIds, OperateOption.Create());

                    }
                }
            }
            base.AfterExecuteOperationTransaction(e);
        }
        private void SetVoucherArgsToVoucher(List<Kingdee.BOS.Orm.DataEntity.DynamicObject> vouchers,MaterialArgs materialarg)
        {
            
            //构建一个IBillView实例
            IBillView billView = CreateBillView("ENG_BOM", 0);
            ((IBillViewService)billView).LoadData();
            vouchers.Add(billView.Model.DataObject);

            FillProperty(billView, FieldValueType.ItemNumber, "FMATERIALID", materialarg.MATERIALID, 0);
            FillProperty(billView, FieldValueType.ItemNumber, "FGroup", materialarg.Group, 0);
            //FillProperty(billView,FieldValueType.Common, "FDocumentStatus", materialarg.DOCUMENTSTATUS,0);
            //FillProperty(billView, FieldValueType.ItemNumber, "FITEMMODEL", materialarg.ITEMMODEL, 0);

            //billView.Model.DeleteEntryData("FTreeEntity");

            //billView.Model.BatchCreateNewEntryRow("FTreeEntity", materialarg.MaterialEntrys.Count);

            FillProperty(billView, FieldValueType.ItemNumber, "FMATERIALIDCHILD", materialarg.MATERIALIDCHILD, 0);
      
        }
        private void FillProperty(IBillView dyView, FieldValueType type, string key, object value, int row)
        {
            switch (type)
            {
                case FieldValueType.Common:
                    dyView.Model.SetValue(key, value, row);
                    break;
                case FieldValueType.ItemNumber:
                    dyView.Model.SetItemValueByNumber(key, value.ToString(), row);
                    dyView.Model.GetValue(key, row);
                    if (dyView.Model.GetValue(key, row) == null)
                    {
                        var yc = dyView.BillBusinessInfo.GetField(key).Name;
                        throw new KDBusinessException("####", yc + "未填充编码：" + value);
                    }
                    break;
                case FieldValueType.ItemId:
                    dyView.Model.SetItemValueByID(key, value, row);
                    if (dyView.Model.GetValue(key, row) == null)
                    {
                        var yc = dyView.BillBusinessInfo.GetField(key).Name;
                        throw new KDBusinessException("####", yc + "未填充编码:" + value);
                    };
                    break;
                //case FieldValueType.FlexNumber:
                //    var flexValue = value as string;
                //    if (string.IsNullOrWhiteSpace(flexValue)) break;
                //    DynamicFormService dynamicFormService = new DynamicFormService(context);
                //    var flexResult = dynamicFormService.FlexSave("BD_FLEXITEMDETAILV", flexValue);
                //    var returnStatus = ((Dictionary<string, object>)((Dictionary<string, object>)(flexResult as Dictionary<string, object>)["Result"])["ResponseStatus"]);
                //    object id;

                //    if (returnStatus["IsSuccess"].Equals(true))
                //    {
                //        id = ((Dictionary<string, object>)((List<object>)returnStatus["SuccessEntitys"])[0])["Id"];
                //        dyView.Model.SetItemValueByID(key, id, row);
                //    }
                //    else
                //    {

                //        var errors = ((List<object>)((Dictionary<string, object>)returnStatus)["Errors"]);
                //        string message = string.Empty;
                //        foreach (var item in errors)
                //        {
                //            message += ((Dictionary<string, object>)item)["Message"] + ";";
                //        }
                //        throw new KDBusinessException("####", message);

                //    }
                //    break;
                default:
                    break;
            }
            var billView = dyView as IBillView;
            billView.InvokeFieldUpdateService(key, row);
        }
        private IBillView CreateBillView(string formId, long pkId)
        {
            //读取物料的元数据
            FormMetadata meta = MetaDataServiceHelper.Load(this.Context, formId) as FormMetadata;
            Form form = meta.BusinessInfo.GetForm();
            //创建用于引入数据的单据view
            Type type = Type.GetType("Kingdee.BOS.Web.Bill.BillView,Kingdee.BOS.Web");
            var billView = (IDynamicFormViewService)Activator.CreateInstance(type);
            //开始初始化billView：
            //创建视图加载参数对象，指定各种参数，如FormId, 视图(LayoutId)等
            BillOpenParameter openParam = CreateOpenParameter(meta, pkId);
            //动态领域模型服务提供类，通过此类，构建MVC实例
            var provider = form.GetFormServiceProvider();
            billView.Initialize(openParam, provider);
            return billView as IBillView;
        }

        private BillOpenParameter CreateOpenParameter(FormMetadata meta, long pkId)
        {
            Form form = meta.BusinessInfo.GetForm();
            //指定FormId, LayoutId
            BillOpenParameter openParam = new BillOpenParameter(form.Id, meta.GetLayoutInfo().Id);
            //数据库上下文
            openParam.Context = this.Context;
            //本单据模型使用的MVC框架
            openParam.ServiceName = form.FormServiceName;
            //随机产生一个不重复的PageId，作为视图的标识
            openParam.PageId = Guid.NewGuid().ToString();
            //元数据
            openParam.FormMetaData = meta;
            //界面状态：新增 (修改、查看)
            if (Convert.ToInt64(pkId) == 0)
            {
                openParam.Status = OperationStatus.ADDNEW;
            }
            else
            {
                openParam.Status = OperationStatus.EDIT;
                //单据主键：本案例演示新建物料，不需要设置主键
                openParam.PkValue = pkId;
            }
            //界面创建目的：普通无特殊目的 （为工作流、为下推、为复制等）
            openParam.CreateFrom = CreateFrom.Default;
            var plugs = form.CreateFormPlugIns();
            openParam.SetCustomParameter(FormConst.PlugIns, plugs);
            PreOpenFormEventArgs args = new PreOpenFormEventArgs(this.Context, openParam);
            foreach (var plug in plugs)
            { //触发插件PreOpenForm事件，供插件确认是否允许打开界面
                plug.PreOpenForm(args);
            }
            return openParam;
        }
    }

}
