using Kingdee.BOS;
using Kingdee.BOS.Core;
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.Metadata;
using Kingdee.BOS.Core.Metadata.FormElement;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Kingdee.BOS.Orm.DataEntity;
using System.Data;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;

namespace LF.K3.SCM.AppServerPlugin.SaveLeifeiMaterial
{
    [Description("磊飞物料新增到物料列表")]
    [HotUpdate]
    public class SaveMaterialChanges: AbstractOperationServicePlugIn
    {
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            //加载父级物料编码
            e.FieldKeys.Add("FNUMBER");
            base.OnPreparePropertys(e);
        }
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            DynamicObject[] obj = e.DataEntitys;
            //编号
            List<object> number = new List<object>();
            //规格型号
            List<object> ListSpecification = new List<object>();
            List<DynamicObject> materigls = new List<DynamicObject>();
            foreach (var item in obj)
            {
                number.Add(item["id"]);
            }
            //分录主键
            List<object> FEntryID = new List<object>();
            string bm = string.Join("', '", number);
            DataTable dt = setWL(bm);
            //获取最大流水号
            string sqllsh = "select MAX(FSERIALNUMBER) lsh from T_LF_CPMaterials";
            var tb = DBServiceHelper.ExecuteDataSet(this.Context, sqllsh).Tables[0];
            int maxlsh =Convert.ToInt32(tb.Rows[0]["lsh"]);
            //获取点光源编码
            string sqldgyFNUMBER = "select a.FNUMBER,b.FNAME from T_BD_MATERIALCATEGORY a left join T_BD_MATERIALCATEGORY_L b on a.FCATEGORYID=b.FCATEGORYID where FNAME='点光源'";
            var tbdgyFNUMBER = DBServiceHelper.ExecuteDataSet(this.Context, sqldgyFNUMBER).Tables[0];
            var dgyFNUMBER = tbdgyFNUMBER.Rows[0]["FNUMBER"].ToString();

            foreach (DataRow item in dt.Rows)
            {
                FEntryID.Add(item["FEntryID"]);
                //规格型号
                LeifeiMaterialArgs lfmateriaargs = new LeifeiMaterialArgs();
                lfmateriaargs.Name = item["kzfs"].ToString() + item["cpxl"].ToString()+ item["cd"].ToString();
                //拼接规格型号
                ListSpecification.Add(item["cpxh"].ToString());
                ListSpecification.Add(item["kzfs"].ToString());
                ListSpecification.Add(item["dy"].ToString());
                ListSpecification.Add(item["FPOWER"].ToString());
                ListSpecification.Add(item["wbkz"].ToString());
                //ListSpecification.Add(item["FLAMPQUANTITY"].ToString());
                ListSpecification.Add(item["led"].ToString());
                ListSpecification.Add(item["xp"].ToString());
                ListSpecification.Add(item["jdmz"].ToString());
                ListSpecification.Add(item["cd"].ToString());
                ListSpecification.Add(item["zkys"].ToString());
                ListSpecification.Add(item["pj"].ToString());
                ListSpecification.Add(item["azzj"].ToString());
                ListSpecification.Add(item["ljx"].ToString());
                ListSpecification.Add(item["pp"].ToString());
                ListSpecification.Add(item["FSPECIALREQUIREMENTS"].ToString());
                ListSpecification.Add(item["FSCHEME"].ToString());
                for (int i = 0; i < ListSpecification.Count; i++)
                {
                   string a= ListSpecification[5].ToString();
                    if (ListSpecification[i].ToString()==""|| ListSpecification[i].ToString()==" ")
                    {
                        ListSpecification[i]= @"\";
                    }
                }
                string spe = string.Join(", ", ListSpecification);

                lfmateriaargs.Specification = spe;
                lfmateriaargs.F_qaz_Remark = spe;

                //数据状态
                lfmateriaargs.DOCUMENTSTATUS = "C";

                //物料分组
                lfmateriaargs.MaterialGroup = "036";

                //物料编码
                if (item["FNUMBER"].ToString()==" ")
                {
                    //物料编码
                    int count = maxlsh + 1;
                    int kzfs;       //控制方式
                    if (item["kzfs"].ToString()== "上电常亮")
                    {
                        kzfs = 0;
                    }
                    else
                    {
                        kzfs = 1;
                    }
                    string dy;       //电压
                    if (item["dy"].ToString() == "AC220V")
                    {
                        dy = "A";
                    }
                    else
                    {
                        dy = "D";
                    }
                    var wlbm = "C4" + item["cpxh"].ToString()+kzfs+ dy + count.ToString("0000");
                    
                    lfmateriaargs.Materialcoding = wlbm;
                    string sqlupdate = "update T_LF_CPMaterials set FSERIALNUMBER=" + count + " where FEntryID=" + item["FEntryID"] + "";
                    DBServiceHelper.Execute(this.Context, sqlupdate);
                }
                else
                {
                    lfmateriaargs.Materialcoding = item["FNUMBER"].ToString();
                }

                //12NC
                lfmateriaargs.F12NC = item["F12NC"].ToString();

                //物料属性设置为自制：2
                lfmateriaargs.ErpCls = "2";

                //产品系列
                if (item["cpxl"].ToString()== "点状灯" || item["cpxl"].ToString() == "柔性灯")
                {
                    //只有点光源会对应“点状灯”和“柔性灯”
                    //点光源:179900
                    lfmateriaargs.Productseries = dgyFNUMBER;
                }
                else
                {
                    
                    string sqlFNUMBER = "select a.FNUMBER,b.FNAME from T_BD_MATERIALCATEGORY a left join T_BD_MATERIALCATEGORY_L b on a.FCATEGORYID=b.FCATEGORYID where FNAME='" + item["cpxl"].ToString() + "'";
                    var tbFNUMBER = DBServiceHelper.ExecuteDataSet(this.Context, sqlFNUMBER).Tables[0];
                    var FNUMBER = tbFNUMBER.Rows[0]["FNUMBER"].ToString();
                    lfmateriaargs.Productseries = FNUMBER;
                }

                //品牌
                lfmateriaargs.Brand = item["pp"].ToString();

                long pkid =Convert.ToInt64(item["FINTERNALID"]);
                SetVoucherArgsToVoucher(materigls, lfmateriaargs,pkid);
                ListSpecification = new List<object>();
            }
            if (materigls.Count > 0)
            {
                FormMetadata meta = MetaDataServiceHelper.Load(this.Context, "BD_MATERIAL") as FormMetadata;
                IOperationResult saveResult = BusinessDataServiceHelper.Save(this.Context, meta.BusinessInfo, materigls.ToArray());
                //审批成功提示
                int indexs = 0;
                foreach (var item in materigls)
                {
                    //给编号,内码赋值
                    string sql = "update T_LF_CPMaterials set FNUMBER='" + item["Number"] + "',FINTERNALID='" + item["id"]+"' where FEntryID='" + FEntryID[indexs] + "'";
                    var i = DBServiceHelper.Execute(this.Context, sql);

                    //throw new KDBusinessException("","物料"+item["Number"] +"已审核!");
                    IOperationResult operationResult = new OperationResult();
                    operationResult.OperateResult.Add(new OperateResult()
                    {
                        SuccessStatus = false,
                        Message = string.Format("物料" + item["Number"] + "已审核!"),
                        MessageType = MessageType.Normal,
                        PKValue = 0,
                    });
                    this.OperationResult.MergeResult(operationResult);
                    indexs++;
                }
            }
           

            base.AfterExecuteOperationTransaction(e);
        }
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            DynamicObject[] obj = e.DataEntitys;
            List<object> number = new List<object>();
            //规格型号
            List<object> ListSpecification = new List<object>();
            foreach (var item in obj)
            {
                number.Add(item["id"]);
            }
            string bm = string.Join("', '", number);
            DataTable dtwl = setWL(bm);
            string Specification = string.Empty;
            foreach (DataRow item in dtwl.Rows)
            {
                //拼接规格型号
                ListSpecification.Add(item["cpxh"].ToString());
                ListSpecification.Add(item["kzfs"].ToString());
                ListSpecification.Add(item["dy"].ToString());
                ListSpecification.Add(item["FPOWER"].ToString());
                ListSpecification.Add(item["wbkz"].ToString());
                ListSpecification.Add(item["led"].ToString());
                ListSpecification.Add(item["xp"].ToString());
                ListSpecification.Add(item["jdmz"].ToString());
                ListSpecification.Add(item["cd"].ToString());
                ListSpecification.Add(item["zkys"].ToString());
                ListSpecification.Add(item["pj"].ToString());
                ListSpecification.Add(item["azzj"].ToString());
                ListSpecification.Add(item["ljx"].ToString());
                ListSpecification.Add(item["pp"].ToString());
                ListSpecification.Add(item["FSPECIALREQUIREMENTS"].ToString());
                ListSpecification.Add(item["FSCHEME"].ToString());
                for (int i = 0; i < ListSpecification.Count; i++)
                {
                    string a = ListSpecification[5].ToString();
                    if (ListSpecification[i].ToString() == "" || ListSpecification[i].ToString() == " ")
                    {
                        ListSpecification[i] = @"\";
                    }
                }
                string spe = string.Join(", ", ListSpecification);
                Specification = spe;
                ListSpecification = new List<object>();
            }
            string sq1 = "select F_QAZ_REMARK from T_BD_MATERIAL where FMATERIALGROUP='358233'";
            var dt = DBServiceHelper.ExecuteDataSet(this.Context, sq1).Tables[0];
            foreach (DataRow item in dt.Rows)
            {
                if (Specification.Equals(item["F_QAZ_REMARK"].ToString()))
                {
                    throw new KDBusinessException("####", "规格型号:[" + Specification + "]已存在!");
                }
            }
            base.EndOperationTransaction(e);
        }
        private void SetVoucherArgsToVoucher(List<DynamicObject> vouchers, LeifeiMaterialArgs materialarg, long pkid)
        {
            //构建一个IBillView实例
            IBillView billView = CreateBillView("BD_MATERIAL", pkid);
            ((IBillViewService)billView).LoadData();
            vouchers.Add(billView.Model.DataObject);
            FillProperty(billView, FieldValueType.Common, "FNumber", materialarg.Materialcoding, 0);
            FillProperty(billView, FieldValueType.Common, "FName", materialarg.Name, 0);
            FillProperty(billView, FieldValueType.Common, "FSpecification", materialarg.Specification,0);
            FillProperty(billView, FieldValueType.Common, "FDocumentStatus", materialarg.DOCUMENTSTATUS, 0);
            FillProperty(billView, FieldValueType.Common, "F_qaz_Remark", materialarg.F_qaz_Remark, 0);
            FillProperty(billView, FieldValueType.ItemNumber, "FMaterialGroup", materialarg.MaterialGroup, 0);
            FillProperty(billView, FieldValueType.Common, "F_qaz_Text2", materialarg.F12NC, 0);
            FillProperty(billView, FieldValueType.Common, "FErpClsID", materialarg.ErpCls, 0);
            FillProperty(billView, FieldValueType.ItemNumber, "FCategoryID", materialarg.Productseries, 0);
            FillProperty(billView, FieldValueType.Common, "F_qaz_Text", materialarg.Brand, 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.Import.ImportBillView,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;
        }

        /// <summary>
        /// 获取磊飞物料的值
        /// </summary>
        /// <returns></returns>
        private DataTable setWL(string number)
        {
            string sql = @"select cpm.FID,cpm.FEntryID,cpm.FSEQ,cpxl.FDATAVALUE as cpxl,cpxh.FDATAVALUE as cpxh,kzfs.FDATAVALUE as kzfs,dy.FDATAVALUE as dy,cpm.FPOWER,wbkz.FDATAVALUE as wbkz,led.FDATAVALUE as led,jdmz.FDATAVALUE as jdmz,cd.FDATAVALUE as cd,zkys.FDATAVALUE as zkys,pj.FDATAVALUE as pj,azzj.FDATAVALUE as azzj,ljx.FDATAVALUE as ljx,pp.FDATAVALUE as pp,cpm.FSPECIALREQUIREMENTS,xp.FDATAVALUE as xp,cpm.FSCHEME,cpm.FNUMBER,cpm.FINTERNALID,cpm.F12NC from  T_LF_CPMaterials cpm
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FPRODUCTSERIES=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) cpxl on cpm.FEntryID=cpxl.FEntryID     
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FPRODUCTMODEL=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) cpxh on cpm.FEntryID=cpxh.FEntryID
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FCONTROLMODE=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) kzfs on cpm.FEntryID=kzfs.FEntryID
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FVOLTAGE=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) dy on cpm.FEntryID=dy.FEntryID
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FEXTERNALCON=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) wbkz on cpm.FEntryID=wbkz.FEntryID
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FLED=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) led on cpm.FEntryID=led.FEntryID
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FANGLEMASK=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) jdmz on cpm.FEntryID=jdmz.FEntryID
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FLENGTH=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) cd on cpm.FEntryID=cd.FEntryID
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FMAINSHELLCOLOR=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) zkys on cpm.FEntryID=zkys.FEntryID
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FFITTINGS=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) pj on cpm.FEntryID=pj.FEntryID
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FMOUNTINGBRACKET=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) azzj on cpm.FEntryID=azzj.FEntryID
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FCONNECTINGLINE=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) ljx on cpm.FEntryID=ljx.FEntryID
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FBRAND=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) pp on cpm.FEntryID=pp.FEntryID
left join (select a.fid,a.FEntryID,c.FDATAVALUE from T_LF_CPMaterials a left join T_BAS_ASSISTANTDATAENTRY b on a.FCHIP=b.FMASTERID left join T_BAS_ASSISTANTDATAENTRY_L c on b.FENTRYID=c.FENTRYID) xp on cpm.FEntryID=xp.FEntryID 
where cpm.FID in ('" + number+"')";
            //where EXISTS(select 1 from TABLE(fn_StrSplit(@IDS, ',', 2)) B where B.FID=cpm.FID)
            //var tb = DBUtils.ExecuteDataSet(this.Context, sql,new List<SqlParam> {new SqlParam("@IDS",KDDbType.udt_nvarchartable,number)}).Tables[0];
            var tb = DBServiceHelper.ExecuteDataSet(this.Context, sql).Tables[0];
            return tb;
        }
    }
}
