using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.Operation;
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.Metadata;
using Kingdee.BOS.Core.Metadata.ConvertElement;
using Kingdee.BOS.Core.Metadata.ConvertElement.ServiceArgs;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Core.Metadata.FormElement;
using Kingdee.BOS.Core.Permission.Objects;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LQKJ.K3.MFG.PRD.BusinessPlugIn
{
    [Kingdee.BOS.Util.HotUpdate]
    [Description("采购计划转采购单")]
    public class PlanTurnPurchasePlugin : AbstractDynamicFormPlugIn
    {
        DataTable dt = new DataTable();
        /// <summary>
        /// 绑定单据体数据
        /// </summary>
        /// <param name="e"></param>
        public void loadDate(string type = "", string billno = "", string date = "", string date2 = "", string material = "", string name = "")
        {
            Logger.Info("开始", "开始");
            //获取当前用户过滤权限
            Kingdee.BOS.Core.Metadata.FormMetadata stockFormMetaData = MetaDataServiceHelper.GetFormMetaData(this.View.Context, "PUR_Requisition");
            DataRuleFilterParamenter filterParameter = new DataRuleFilterParamenter("PUR_Requisition")
            {
                PermissionItemId = Kingdee.BOS.Core.Permission.PermissionConst.View,
                SubSystemId = stockFormMetaData.BusinessInfo.GetForm().SubsysId,
                BusinessInfo = stockFormMetaData.BusinessInfo
            };
            DataRuleFilterObject filterObject = PermissionServiceHelper.LoadDataRuleFilter(this.View.Context, filterParameter);//获取当前用户可以访问哪些仓库（过滤条件）
            Kingdee.BOS.Core.SqlBuilder.QueryBuilderParemeter queryParameter = new Kingdee.BOS.Core.SqlBuilder.QueryBuilderParemeter
            {
                FormId = "PUR_Requisition",
                BusinessInfo = stockFormMetaData.BusinessInfo,
                PermissionItemId = Kingdee.BOS.Core.Permission.PermissionConst.View,
                FilterClauseWihtKey = filterObject.FilterString,//过滤条件          
            };
            DynamicObject[] stockObjects = BusinessDataServiceHelper.Load(this.View.Context, stockFormMetaData.BusinessInfo.GetDynamicObjectType(), queryParameter);
            var FID = "";
            foreach (var item in stockObjects)
            {
                FID += item["Id"].ToString() + ",";//获取到当前用户可查看到的仓库数据
            }
            if (FID == "")
            {
                this.View.ShowWarnningMessage("您的数据权限过滤后无数据！");
                return;
            }
            //根据权限 查询需加载出的数据
            string sql = $@"/*dialect*/ select t2.FMATERIALID,t3_b.FPURCHASEUNITID wlunit,t1.FBILLNO,t8.FNAME FREQUESTTYPE,FREMAINQTY,FSRCBILLNO,FNOTE,t2.FENTRYID,
                                 CONVERT(varchar(100), FAPPLICATIONDATE, 111) FAPPLICATIONDATE,t3.FNUMBER,t4.FNAME,t4.FSPECIFICATION,t2.FREQQTY,
                                 t5.FNAME sqdw,t6.FNAME cgdw,t2.FARRIVALDATE,T1.FID,T2.FENTRYID seq,T2.FSEQ from T_PUR_Requisition t1 
                                inner join T_PUR_ReqEntry t2 on t1.FID=t2.FID
                                inner join T_BD_MATERIAL t3 on t2.FMATERIALID=t3.FMATERIALID
                                left join t_bd_MaterialPurchase t3_b on t3.FMATERIALID=t3_b.FMATERIALID
                                left join (select * from T_BD_MATERIAL_L where FLOCALEID=2052) t4 on t3.FMATERIALID=t4.FMATERIALID
                                left join (select * from T_BD_UNIT_L where FLOCALEID=2052) t5 on t2.FUNITID=t5.FUNITID
                                left join (select ta.FMATERIALID, tb.FNAME from t_bd_MaterialPurchase ta 
                                left join (select * from T_BD_UNIT_L where FLOCALEID=2052) tb on ta.FPURCHASEUNITID=tb.FUNITID) t6 on t6.FMATERIALID=t3.FMATERIALID 
                                left join T_PUR_REQENTRY_R t7 on t7.FENTRYID=t2.FENTRYID 
                                left join (select * from T_BAS_BILLTYPE_L where FLOCALEID=2052) t8 on t8.FBILLTYPEID=t1.FBILLTYPEID
                                 where t1.FDOCUMENTSTATUS='C' and t2.FMRPCLOSESTATUS!='B' and FCLOSESTATUS!='B'
                                 and (FBASEUNITQTY-FORDERJNBASEQTY) >0 and t1.FID in({FID.Remove(FID.LastIndexOf(","))})";//order by FBILLNO DESC
            //过滤条件
            if (type != "")//单据类型
            {
                sql += $@"/*dialect*/and t8.FNAME='{type}'";
            }
            if (billno != "")//单据编号
            {
                sql += $@"/*dialect*/and t1.FBILLNO like '%{billno}%'";
            }
            if (date != "" && date2 == "")//日期范围
            {
                sql += $@"/*dialect*/and CONVERT(varchar(100), FAPPLICATIONDATE, 111) = '{date}'";
            }
            if (date != "" && date2 != "")//日期范围
            {
                sql += $@"/*dialect*/and FAPPLICATIONDATE between '{date}' and '{date2} 23:59:59' ";
            }
            if (material != "")//物料
            {
                sql += $@"/*dialect*/and t3.FNUMBER like '%{material}%' ";
            }
            if (name != "")//物料名称
            {
                sql += $@"/*dialect*/and t4.FNAME like '%{name}%' ";
            }
            sql += "order by FBILLNO DESC";
            dt = DBServiceHelper.ExecuteDataSet(this.Context, sql).Tables[0];//采购申请信息

            //报价信息
            string sql1 = $@"/*dialect*/  select t1.FMATERIALID,FPRICE,FDEFAULTPRICET,FDEFAULTPRICEO,t3.FNAME,FTAXPRICE,t4.minprice from t_PUR_PriceListEntry t1
                                          left join t_PUR_PriceList t2 on t1.FID=t2.FID
                                          left join T_BD_SUPPLIER_L t3 on t2.FSUPPLIERID=t3.FSUPPLIERID
                                          left join (select FMATERIALID,min(FPRICE) minprice from t_PUR_PriceListEntry group by FMATERIALID) 
                                          t4 on t4.FMATERIALID=t1.FMATERIALID
                                          where t1.FEXPIRYDATE>GETDATE() and t1.FEFFECTIVEDATE<GETDATE() and FDOCUMENTSTATUS='C' and FFORBIDSTATUS='A'
                                          order by t1.FEFFECTIVEDATE desc ";
            DataTable dt1 = DBServiceHelper.ExecuteDataSet(this.Context, sql1).Tables[0];//报价
            var dt2 = SelectLYDD();

            //赋值
            this.Model.DeleteEntryData("F_LQKJ_Entity");
            this.Model.BatchCreateNewEntryRow("F_LQKJ_Entity", dt.Rows.Count);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                this.View.Model.SetValue("F_LQKJ_BILLNO", dt.Rows[i]["FBILLNO"].ToString(), i);
                this.View.Model.SetValue("F_LQKJ_TYPE", dt.Rows[i]["FREQUESTTYPE"].ToString(), i);
                this.View.Model.SetValue("F_LQKJ_DATE", dt.Rows[i]["FAPPLICATIONDATE"].ToString(), i);
                this.View.Model.SetValue("F_LQKJ_NUMBER", dt.Rows[i]["FNUMBER"].ToString(), i);
                this.View.Model.SetValue("F_LQKJ_FNAME", dt.Rows[i]["FNAME"].ToString(), i);
                this.View.Model.SetValue("F_LQKJ_SPECIFICATION", dt.Rows[i]["FSPECIFICATION"], i);
                this.View.Model.SetValue("F_LQKJ_NOTE", dt.Rows[i]["FNOTE"].ToString(), i);
                this.View.Model.SetValue("F_LQKJ_REQQTY", Convert.ToDouble(dt.Rows[i]["FREQQTY"].ToString()), i);
                this.View.Model.SetValue("F_LQKJ_SQUNIT", dt.Rows[i]["sqdw"].ToString(), i);
                this.View.Model.SetValue("F_LQKJ_CGUNIT", dt.Rows[i]["cgdw"].ToString(), i);
                this.View.Model.SetValue("F_LQKJ_ARRIVALDATE", dt.Rows[i]["FARRIVALDATE"].ToString(), i);
                this.View.Model.SetValue("F_LQKJ_REMAINQTY", Convert.ToDouble(dt.Rows[i]["FREMAINQTY"]), i);
                this.View.Model.SetValue("F_LQKJ_FID", Convert.ToInt64(dt.Rows[i]["FID"]), i);
                this.View.Model.SetValue("F_LQKJ_Fseq", Convert.ToInt64(dt.Rows[i]["seq"]), i);
                this.View.Model.SetValue("F_LQKJ_ReqSeq", Convert.ToInt64(dt.Rows[i]["FSEQ"]), i);
                this.View.Model.SetValue("F_LQKJ_MATERIALID", Convert.ToInt64(dt.Rows[i]["FMATERIALID"]), i);
                this.View.Model.SetValue("F_LQKJ_wlUnit1", dt.Rows[i]["wlunit"].ToString(), i);

                //查询出最新的数据
                var a = dt1.Select("FMATERIALID=" + dt.Rows[i]["FMATERIALID"].ToString()).FirstOrDefault();
                if (a != null)
                {
                    this.View.Model.SetValue("F_LQKJ_NEWSUPPIER", a["FNAME"], i);//最新报价供应商
                    this.View.Model.SetValue("F_LQKJ_TAXPRICE", Convert.ToDouble(a["FTAXPRICE"]), i);//最新报价（含税单价）
                    this.View.Model.SetValue("F_LQKJ_PRICE", Convert.ToDouble(a["FPRICE"]), i);//最新报价（未税单价）
                    this.View.Model.SetValue("F_LQKJ_CheckBox1", 1, i);//报价否
                    this.View.Model.SetValue("F_LQKJ_minprice", Convert.ToDouble(a["minprice"]), i);//最低报价
                }
                if (dt.Rows[i]["FSRCBILLNO"].ToString().IsNullOrEmptyOrWhiteSpace()) continue;

                //源单信息
                var str = dt.Rows[i]["FENTRYID"].ToString();
                List<DataRow> row;
                dt2.TryGetValue(str, out row);
                if (row != null)
                {
                    this.View.Model.SetValue("F_LQKJ_SOURCSBILLNO", row[0]["xsd"], i);//来源订单号
                    this.View.Model.SetValue("F_LQKJ_SOURCETYPE", row[0]["FNUMBER"], i);//订单型号
                    this.View.Model.SetValue("F_LQKJ_BOM", row[0]["FBOMID"], i);
                    this.View.Model.SetValue("F_LQKJ_BOMEBTRYID", row[0]["BOMEBTRYID"], i);
                }

            }
            this.View.UpdateView("F_LQKJ_Entity");
            Logger.Info("结束", "结束");
        }
        public override void AfterBindData(EventArgs e)
        {
            loadDate();
            base.AfterBindData(e);
        }
        /// <summary>
        /// 物料编码、供应商触发时弹窗及返回数据处理
        /// </summary>
        /// <param name="e"></param>
        public override void BeforeF7Select(BeforeF7SelectEventArgs e)
        {
            int rowIndex = this.View.Model.GetEntryCurrentRowIndex("F_LQKJ_Entity");
            ////点击物料编码  选择替代料
            if (e.FieldKey.Equals("F_LQKJ_NUMBER", StringComparison.OrdinalIgnoreCase))
            {
                var param = new DynamicFormShowParameter();
                param.FormId = "LQKJ_ReplaceSelect";
                var str = this.View.Model.GetValue("F_LQKJ_BOMEBTRYID", rowIndex);
                Logger.Info("F_LQKJ_BOMEBTRYID", "str");
                // 文本编辑器的业务对象标识   
                if (this.View.Model.GetValue("F_LQKJ_NUMBER", rowIndex).IsNullOrEmptyOrWhiteSpace())//物料
                {
                    this.View.ShowWarnningMessage("未查找到相关替代料数据");
                    return;
                }
                else if (this.View.Model.GetValue("F_LQKJ_BOMEBTRYID", rowIndex).IsNullOrEmptyOrWhiteSpace())
                {
                    this.View.ShowWarnningMessage("未查找到相关替代料数据");
                    return;
                }
                param.CustomParams["wl"] = this.View.Model.GetValue("F_LQKJ_NUMBER", rowIndex).ToString();
                param.CustomParams["BOMEBTRYID"] = this.View.Model.GetValue("F_LQKJ_BOMEBTRYID", rowIndex).ToString();
                // 将文本值传递给文本编辑器             
                this.View.ShowForm(param, result =>
                {
                    if (result != null && result.ReturnData != null)
                    {
                        var returnData = (List<string>)result.ReturnData;//获取返回数据

                        //返回选择的物料后，原来的数据清除
                        this.View.Model.SetValue("F_LQKJ_NEWSUPPIER", "", rowIndex);//最新报价供应商
                        this.View.Model.SetValue("F_LQKJ_TAXPRICE", "", rowIndex);//最新报价（含税单价）
                        this.View.Model.SetValue("F_LQKJ_PRICE", "", rowIndex);//最新报价（未税单价）
                        this.View.Model.SetValue("F_LQKJ_CheckBox1", 0, rowIndex);//报价否
                        this.View.Model.SetValue("F_LQKJ_minprice", "", rowIndex);//最低报价
                        this.View.Model.SetValue("F_LQKJ_wlUnit2", "", rowIndex);

                        //赋值返回的数据
                        this.View.Model.SetValue("F_LQKJ_NUMBER", returnData[0], rowIndex);
                        this.View.Model.SetValue("F_LQKJ_FNAME", returnData[1], rowIndex);
                        this.View.Model.SetValue("F_LQKJ_SPECIFICATION", returnData[2], rowIndex);
                        this.View.Model.SetValue("F_LQKJ_MATERIALID", returnData[3], rowIndex);
                        this.View.Model.SetValue("F_LQKJ_wlUnit2", returnData[4], rowIndex);
                        string sqlprice = $@"/*dialect*/select  t1.FMATERIALID,t5_b.FPURCHASEUNITID wlunit,FPRICE,FDEFAULTPRICET,FDEFAULTPRICEO,t3.FNAME,FTAXPRICE,t4.minprice,FCURRENCYID from t_PUR_PriceListEntry t1
                                            left join t_PUR_PriceList t2 on t1.FID = t2.FID
                                            left join T_BD_SUPPLIER_L t3 on t2.FSUPPLIERID = t3.FSUPPLIERID
                                            left join(select FMATERIALID, min(FPRICE) minprice from t_PUR_PriceListEntry group by FMATERIALID)
                                            t4 on t4.FMATERIALID = t1.FMATERIALID
                                            left join T_BD_MATERIAL t5 on t5.FMATERIALID=t1.FMATERIALID
                                            left join t_bd_MaterialPurchase t5_b on t5.FMATERIALID=t5_b.FMATERIALID
                                            where t1.FEXPIRYDATE > GETDATE() and t1.FEFFECTIVEDATE < GETDATE() and t2.FDOCUMENTSTATUS = 'C' and t2.FFORBIDSTATUS = 'A'
                                            and t1.FMATERIALID = {returnData[3]} order by t1.FEFFECTIVEDATE desc ";
                        DataTable dtprcie = DBServiceHelper.ExecuteDataSet(this.Context, sqlprice).Tables[0];//选中物料报价

                        if (dtprcie.Rows.Count > 0)
                        {
                            this.View.Model.SetValue("F_LQKJ_NEWSUPPIER", dtprcie.Rows[0]["FNAME"].ToString(), rowIndex);//最新报价供应商
                            this.View.Model.SetValue("F_LQKJ_TAXPRICE", Convert.ToDouble(dtprcie.Rows[0]["FTAXPRICE"]), rowIndex);//最新报价（含税单价）
                            this.View.Model.SetValue("F_LQKJ_PRICE", Convert.ToDouble(dtprcie.Rows[0]["FPRICE"]), rowIndex);//最新报价（未税单价）
                            this.View.Model.SetValue("F_LQKJ_CheckBox1", 1, rowIndex);//报价否
                            this.View.Model.SetValue("F_LQKJ_minprice", Convert.ToDouble(dtprcie.Rows[0]["minprice"]), rowIndex);//最低报价

                            //选择物料后，需要把对应已带出的供应商信息清除
                            this.View.Model.SetValue("F_LQKJ_SUPPLIER", " ", rowIndex);//供应商
                            this.View.Model.SetValue("F_LQKJ_SUPPLIERID", " ", rowIndex);
                            this.View.Model.SetValue("F_LQKJ_FPRICE", " ", rowIndex);//返点后
                            this.View.Model.SetValue("F_LQKJ_DEFAULTPRICET", " ", rowIndex);//返点前
                            this.View.Model.SetValue("F_LQKJ_DEFAULTPRICEO", " ", rowIndex);//返点额
                            this.View.Model.SetValue("F_LQKJ_Text", " ", rowIndex);//含税单价
                            this.View.Model.SetValue("F_LQKJ_Currency", 0, rowIndex);
                        }
                    }
                });
            }

            //点击供应商  选择供应商
            if (e.FieldKey.Equals("F_LQKJ_SUPPLIER", StringComparison.OrdinalIgnoreCase))//供应商
            {
                var param = new DynamicFormShowParameter();
                param.FormId = "LQKJ_PriceSelect";
                // 文本编辑器的业务对象标识         
                param.CustomParams["gys"] = this.View.Model.GetValue("F_LQKJ_NUMBER", rowIndex).ToString();
                // 将文本值传递给文本编辑器             
                this.View.ShowForm(param, result =>
                {
                    if (result != null && result.ReturnData != null)
                    {
                        var returnData = result.ReturnData;//获取返回数据
                        string sqlselsupplier = $@"/*dialect*/select FMATERIALID,FPRICE,FDEFAULTPRICET,FDEFAULTPRICEO,t3.FNAME,FTAXPRICE,
                                                                FISINCLUDEDTAX,FISPRICEEXCLUDETAX,t2.FSUPPLIERID,FTAXRATE,FCURRENCYID from t_PUR_PriceListEntry t1
                                                                left join t_PUR_PriceList t2 on t1.FID = t2.FID
                                                                left join T_BD_SUPPLIER_L t3 on t2.FSUPPLIERID = t3.FSUPPLIERID
                                                                where t1.FENTRYID = {returnData}";
                        DataTable supplier = DBServiceHelper.ExecuteDataSet(this.Context, sqlselsupplier).Tables[0];//报价

                        this.View.Model.SetValue("F_LQKJ_SUPPLIER", supplier.Rows[0]["FNAME"], rowIndex);//供应商
                        this.View.Model.SetValue("F_LQKJ_SUPPLIERID", supplier.Rows[0]["FSUPPLIERID"], rowIndex);
                        this.View.Model.SetValue("F_LQKJ_FPRICE", Convert.ToDouble(supplier.Rows[0]["FPRICE"]), rowIndex);//返点后
                        this.View.Model.SetValue("F_LQKJ_DEFAULTPRICET", Convert.ToDouble(supplier.Rows[0]["FDEFAULTPRICET"]), rowIndex);//返点前
                        this.View.Model.SetValue("F_LQKJ_DEFAULTPRICEO", Convert.ToDouble(supplier.Rows[0]["FDEFAULTPRICEO"]), rowIndex);//返点额
                        this.View.Model.SetValue("F_LQKJ_Text", Convert.ToDouble(supplier.Rows[0]["FTAXPRICE"]), rowIndex);//含税单价
                        this.View.Model.SetValue("F_LQKJ_ShuiLv1", supplier.Rows[0]["FTAXRATE"], rowIndex);//税率
                        this.View.Model.SetValue("F_LQKJ_Currency", supplier.Rows[0]["FCURRENCYID"], rowIndex);
                        this.View.Model.SetValue("F_LQKJ_ITaxnCluded", supplier.Rows[0]["FISINCLUDEDTAX"], rowIndex);
                        this.View.Model.SetValue("F_LQKJ_IsPriceExcludeTax", supplier.Rows[0]["FISPRICEEXCLUDETAX"], rowIndex);//价外税
                    }
                });
            }
            //点击物料名称  查看相关的采购订单
            if (e.FieldKey.Equals("F_LQKJ_FNAME", StringComparison.OrdinalIgnoreCase))//物料名称
            {
                var param = new ListShowParameter();
                var wl = this.View.Model.GetValue("F_LQKJ_MATERIALID", rowIndex).ToString();
                param.FormId = "PUR_PurchaseOrder";
                param.ListFilterParameter.Filter = " FMATERIALID='" + wl + "'";
                // 文本编辑器的业务对象标识         

                // 将文本值传递给文本编辑器             
                this.View.ShowForm(param);
            }
            base.BeforeF7Select(e);
        }
        /// <summary>
        /// 下推
        /// </summary>
        /// <param name="e"></param>
        public override void AfterDoOperation(AfterDoOperationEventArgs e)
        {
            switch (e.Operation.Operation.ToUpperInvariant())
            {
                //case "SAVE": 表单定义的事件都可以在这里执行，需要通过事件的代码[大写]区分不同事件
                //break;
                case "ALTERNATIVEMATERIAL":
                    //选单弹窗
                    var param = new DynamicFormShowParameter();
                    param.FormId = "LQKJ_SelectTyppe";
                    // 将文本值传递给文本编辑器   
                    var returnData = "";
                    this.View.ShowForm(param, result =>
                    {
                        if (result != null && result.ReturnData != null)
                        {
                            returnData = result.ReturnData.ToString();//获取返回选单数据
                            AlternativeMaterial(returnData);
                        }
                    });

                    break;
                case "BATCHFILL":// 批量填充供应商
                    BatchFill();
                    break;
                case "SELECTDATA"://过滤
                    SELECTDATA();
                    break;
                case "CANCELFILL"://取消批量填充
                    CANCELFILL();
                    break;
                default:
                    break;
            }
            base.AfterDoOperation(e);
        }
        /// <summary>
        /// 取消批量填充
        /// </summary>
        private void CANCELFILL()
        {
            var grid = this.View.GetControl<EntryGrid>("F_LQKJ_Entity");
            var selectedRows = grid.GetSelectedRows();
            int rowIndex = this.View.Model.GetEntryCurrentRowIndex("F_LQKJ_Entity");
            List<int> Check = selectedRows.ToList();
            if (Check.Count < 1 || Check.Count == 1)
            {
                this.View.ShowWarnningMessage("请勾选开始行与结束行");
            }
            else
            {
                for (int i = 0; i < selectedRows.Count(); i++)
                {
                    this.View.Model.SetValue("F_LQKJ_SUPPLIER", " ", selectedRows[i]);//供应商
                    this.View.Model.SetValue("F_LQKJ_SUPPLIERID", " ", selectedRows[i]);
                    this.View.Model.SetValue("F_LQKJ_FPRICE", " ", selectedRows[i]);//返点后
                    this.View.Model.SetValue("F_LQKJ_DEFAULTPRICET", " ", selectedRows[i]);//返点前
                    this.View.Model.SetValue("F_LQKJ_DEFAULTPRICEO", " ", selectedRows[i]);//返点额
                    this.View.Model.SetValue("F_LQKJ_Text", " ", selectedRows[i]);//含税单价
                    this.View.Model.SetValue("F_LQKJ_ShuiLv1", " ", selectedRows[i]);//税率
                    this.View.Model.SetValue("F_LQKJ_Currency", 0, selectedRows[i]);
                    this.View.Model.SetValue("F_LQKJ_ITaxnCluded", 0, selectedRows[i]);
                    this.View.Model.SetValue("F_LQKJ_IsPriceExcludeTax", 0, selectedRows[i]);
                }
            }
        }
        /// <summary>a
        /// 过滤
        /// </summary>
        private void SELECTDATA()
        {
            var type = this.View.Model.GetValue("F_LQKJ_BillType").ToString();
            string typetext = "";
            if (type != "")
            {
                switch (type)
                {
                    case "1":
                        typetext = "标准采购申请";
                        break;
                    case "2":
                        typetext = "直运采购申请";
                        break;
                    case "3":
                        typetext = "资产采购申请单";
                        break;
                    case "4":
                        typetext = "费用采购申请";
                        break;
                }
            }
            string BillNo = "";
            string date = "";
            string date2 = "";
            string material = "";
            string materialName = "";

            if (!this.View.Model.GetValue("F_LQKJ_SelectBillNO").IsNullOrEmptyOrWhiteSpace())
            {
                BillNo = this.View.Model.GetValue("F_LQKJ_SelectBillNO").ToString();
            }
            if (!this.View.Model.GetValue("F_LQKJ_SelectDate").IsNullOrEmptyOrWhiteSpace())
            {
                date = this.View.Model.GetValue("F_LQKJ_SelectDate").ToString();
            }
            if (!this.View.Model.GetValue("F_LQKJ_SelectDate2").IsNullOrEmptyOrWhiteSpace())
            {
                date2 = this.View.Model.GetValue("F_LQKJ_SelectDate2").ToString();
            }
            if (!this.View.Model.GetValue("F_LQKJ_MaterialNumber").IsNullOrEmptyOrWhiteSpace())
            {
                material = this.View.Model.GetValue("F_LQKJ_MaterialNumber").ToString();
            }
            if (!this.View.Model.GetValue("F_LQKJ_MaterailName").IsNullOrEmptyOrWhiteSpace())
            {
                materialName = this.View.Model.GetValue("F_LQKJ_MaterailName").ToString();
            }
            if (date != "")
            {
                DateTime dt = DateTime.Parse(date);
                //获取当前年月日
                date = dt.ToString("yyyy/MM/dd");
            }
            if (date2 != "")
            {
                DateTime dt2 = DateTime.Parse(date2);
                //获取当前年月日
                date2 = dt2.ToString("yyyy/MM/dd");
            }
            if (date == "" && date2 != "")
            {
                this.View.ShowWarnningMessage("请选择开始时间！");
                return;
            }
            if (date != "" && date2 != "")
            {
                if (DateTime.Parse(date) > DateTime.Parse(date2))
                {
                    this.View.ShowWarnningMessage("结束时间不能大于开始时间！");
                    return;
                }
            }
            loadDate(typetext, BillNo, date, date2, material, materialName);
        }
        /// <summary>
        /// 批量填充供应商
        /// </summary>
        private void BatchFill()
        {
            var grid = this.View.GetControl<EntryGrid>("F_LQKJ_Entity");
            var selectedRows = grid.GetSelectedRows();
            if (selectedRows.Length < 1 || selectedRows.Length == 1)
            {
                this.View.ShowWarnningMessage("请选择填充的行");
                return;
            }
            List<int> Check = selectedRows.ToList();
            List<object> supplier = new List<object>();
            for (int i = 0; i < selectedRows.Count(); i++)
            {
                var selectedRow = selectedRows[i];
                var Selectsupplier = this.View.Model.GetValue("F_LQKJ_SUPPLIERID", selectedRow);
                if (!Selectsupplier.IsNullOrEmptyOrWhiteSpace())
                {
                    supplier.Add(Selectsupplier);
                }
            }
            {
                //获取第一个勾选，和最后一个勾选，将这区间范围内的行，全勾选
                var supplierId = "";
                if (supplier.Count == 0)
                {
                    this.View.ShowWarnningMessage("未选择供应商");
                }
                else
                if (supplier.Count > 0)
                {
                    supplierId = supplier[0].ToString();//供应商默认获取第一个
                    string materialId = "";
                    for (int i = 0; i < selectedRows.Count(); i++)
                    {
                        //获取物料，查询出对应数据  F_LQKJ_MATERIALID
                        materialId += this.View.Model.GetValue("F_LQKJ_MATERIALID", selectedRows[i]).ToString() + ",";
                    }
                    //更据物料，供应商查出对应报价信息
                    if (materialId != "") { materialId = materialId.Remove(materialId.LastIndexOf(",")); }
                    string MaterialPriceSql = $@"/*dialect*/select t1.FMATERIALID,t2.* from T_BD_MATERIAL t1 
                                            left join (select t2.FMATERIALID as wlid,FPRICE,FDEFAULTPRICET,FDEFAULTPRICEO,t3.FNAME,FTAXPRICE, FTAXRATE,
                                            t3.FSUPPLIERID,FCURRENCYID,t2.FEFFECTIVEDATE,FROWAUDITSTATUS,FFORBIDSTATUS,FDOCUMENTSTATUS,FISINCLUDEDTAX from t_PUR_PriceList t1
                                            left join t_PUR_PriceListEntry t2 on t1.FID=t2.FID
                                            left join T_BD_SUPPLIER_L t3 on t3.FSUPPLIERID=t1.FSUPPLIERID
                                            where t1.FSUPPLIERID='{supplierId}' and FROWAUDITSTATUS='A'  and FROWAUDITSTATUS='A' and FFORBIDSTATUS='A' AND FDOCUMENTSTATUS='C') t2 on t1.FMATERIALID=t2.wlid
                                            where t1.FMATERIALID in({materialId}) order by t2.FEFFECTIVEDATE desc";
                    DataTable pricedt = DBServiceHelper.ExecuteDataSet(this.Context, MaterialPriceSql).Tables[0];
                    for (int i = 0; i < selectedRows.Count(); i++)
                    {
                        var nowMaterial = this.View.Model.GetValue("F_LQKJ_MATERIALID", selectedRows[i]).ToString();
                        HashSet<string> usedSupplier = new HashSet<string>();
                        for (int j = 0; j < pricedt.Rows.Count; j++)
                        {
                            var currow = pricedt.Rows[j];
                            if (nowMaterial == currow["FMATERIALID"].ToString())
                            {
                                if (currow["FSUPPLIERID"] != DBNull.Value)
                                {
                                    if (usedSupplier.Contains(nowMaterial)) continue;
                                    usedSupplier.Add(currow["wlid"].ToString());
                                    this.View.Model.SetValue("F_LQKJ_SUPPLIER", currow["FNAME"], selectedRows[i]);//供应商
                                    this.View.Model.SetValue("F_LQKJ_SUPPLIERID", currow["FSUPPLIERID"], selectedRows[i]);
                                    this.View.Model.SetValue("F_LQKJ_FPRICE", currow["FPRICE"], selectedRows[i]);//返点后
                                    this.View.Model.SetValue("F_LQKJ_DEFAULTPRICET", currow["FDEFAULTPRICET"], selectedRows[i]);//返点前
                                    this.View.Model.SetValue("F_LQKJ_DEFAULTPRICEO", currow["FDEFAULTPRICEO"], selectedRows[i]);//返点额
                                    this.View.Model.SetValue("F_LQKJ_Text", currow["FTAXPRICE"], selectedRows[i]);//含税单价
                                    this.View.Model.SetValue("F_LQKJ_ShuiLv1", currow["FTAXRATE"], selectedRows[i]);//税率
                                    this.View.Model.SetValue("F_LQKJ_ITaxnCluded", currow["FISINCLUDEDTAX"], selectedRows[i]);
                                    this.View.Model.SetValue("F_LQKJ_Currency", currow["FCURRENCYID"], selectedRows[i]);
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 下推
        /// </summary>
        /// <param name="billtype"></param>
        public void AlternativeMaterial(string billtype)
        {
            var entity = this.View.BillBusinessInfo.GetEntity("F_LQKJ_Entity");
            var entityObjs = this.View.Model.GetEntityDataObject(entity);
            Dictionary<long, object> selrow = new Dictionary<long, object>();
            Dictionary<string, List<ListSelectedRow>> listSelectedRowsDic = new Dictionary<string, List<ListSelectedRow>>();
            if (entityObjs != null)
            {
                foreach (var entityObj in entityObjs)
                {

                    if ((bool)entityObj["F_LQKJ_CheckBox"])
                    {
                        //物料、供应商不能为空，为空的不下推
                        if (entityObj["F_LQKJ_NUMBER"].IsNullOrEmptyOrWhiteSpace())
                        {
                            this.View.ShowWarnningMessage(entityObj["F_LQKJ_NUMBER"] + "请选择物料！");
                            continue;
                        }
                        if (entityObj["F_LQKJ_SUPPLIER"].IsNullOrEmptyOrWhiteSpace())
                        {
                            this.View.ShowWarnningMessage(entityObj["F_LQKJ_NUMBER"] + "请选择供应商！");
                            continue;
                        }
                        if (!entityObj["F_LQKJ_wlUnit2"].IsNullOrEmptyOrWhiteSpace())
                        {
                            var unit1 = Convert.ToInt64(entityObj["F_LQKJ_wlUnit1"]);
                            var unit2 = Convert.ToInt64(entityObj["F_LQKJ_wlUnit2"]);
                            string sql = $@"/*dialect*/SELECT FCURRENTUNITID,FDESTUNITID,FCONVERTNUMERATOR,
                                                FCONVERTDENOMINATOR FROM T_BD_UNITCONVERTRATE 
                                                where FCURRENTUNITID in({unit1},{unit2})";//{unit1},{unit2}
                            Logger.Info("开始下推验证单位", sql);
                            DataTable table = DBServiceHelper.ExecuteDataSet(this.Context, sql).Tables[0];
                            if (table.Rows.Count == 2)
                            {
                                if (table.Rows[0]["FDESTUNITID"].ToString() != table.Rows[1]["FDESTUNITID"].ToString())
                                {
                                    this.View.ShowWarnningMessage(entityObj["F_LQKJ_NUMBER"] + "主料替代料基准单位不同！");
                                    continue;
                                }
                            }
                        }
                        var supplierId = entityObj["F_LQKJ_ITaxnCluded"].ToString() + "," + entityObj["F_LQKJ_SUPPLIERID"].ToString();
                        List<ListSelectedRow> listSelectedRows;
                        if (!listSelectedRowsDic.TryGetValue(supplierId, out listSelectedRows))
                        {
                            listSelectedRows = new List<ListSelectedRow>();
                            listSelectedRowsDic.Add(supplierId, listSelectedRows);
                        }

                        var sid = Convert.ToInt64(entityObj["F_LQKJ_Fseq"]);
                        selrow.Add(sid, entityObj);
                        listSelectedRows.Add(new ListSelectedRow("", entityObj["F_LQKJ_Fseq"].ToString(), entityObjs.IndexOf(entityObj), "PUR_Requisition") { EntryEntityKey = "FEntity" });
                    }
                }
            }
            if (listSelectedRowsDic.Count != 0)
            {
                List<DynamicObject> dynamicObjects = new List<DynamicObject>();
                ConvertOperationResult convertOperationResult = null;
                foreach (string key in listSelectedRowsDic.Keys)
                {
                    var convertRules = ConvertServiceHelper.GetConvertRules(this.View.Context, "PUR_Requisition", "PUR_PurchaseOrder");
                    ConvertRuleElement convertRuleElement2 = convertRules.FirstOrDefault((ConvertRuleElement t) => t.IsDefault);
                    PushArgs serviceArgs = new PushArgs(convertRuleElement2, listSelectedRowsDic[key].ToArray())
                    {
                        TargetBillTypeId = billtype,
                        //TargetOrgId ="1",
                        //CustomParams = customParams,
                        //EntryUpperLimitValue = retInfo.EntryUpperLimitValue
                    };
                    var option = OperateOption.Create();
                    option.SetVariableValue("SelectByBillId", false);
                    option.SetVariableValue("ConvertType", "ManualPush");
                    var innerConvertOperationResult = ConvertServiceHelper.Push(this.View.Context, serviceArgs, option);
                    dynamicObjects.AddRange((from p in innerConvertOperationResult.TargetDataEntities
                                             select p.DataEntity).ToArray<DynamicObject>());
                    if (convertOperationResult == null)
                    {
                        convertOperationResult = innerConvertOperationResult;
                    }
                    else
                    {
                        convertOperationResult.MergeResult(innerConvertOperationResult);
                    }
                }
                var createview = CreateBillView("PUR_PurchaseOrder", 0);
                foreach (var item in dynamicObjects)
                {
                    var objs = item["POOrderEntry"] as DynamicObjectCollection;
                    createview.Model.DataObject = item;
                    var i = 0;
                    DynamicObject firstRow = null;
                    DynamicObject firstRowObj = null;
                    foreach (var obj in objs)
                    {
                        var CGentryobj = obj["FPOOrderEntry_Link"] as DynamicObjectCollection;
                        var sid = Convert.ToInt32(CGentryobj[0]["SId"]);
                        Object objq;
                        var SeleteCGSQ = selrow.TryGetValue(sid, out objq);
                        var cg = objq as DynamicObject;
                        obj["F_LQKJ_MinPrice"] = cg["F_LQKJ_minprice"];//最低报价
                        if (i == 0)
                        {
                            createview.Model.SetValue("FSupplierId", cg["F_LQKJ_SUPPLIERID"], i);
                            createview.InvokeFieldUpdateService("FSupplierId", i);
                            firstRow = cg;
                            firstRowObj = obj;
                            i++;
                            continue;
                        }
                        createview.Model.SetValue("FISINCLUDEDTAX", cg["F_LQKJ_ITaxnCluded"], i);
                        createview.InvokeFieldUpdateService("FISINCLUDEDTAX", i);
                        //createview.Model.SetValue("FISPRICEEXCLUDETAX", cg["F_LQKJ_IsPriceExcludeTax"], i);
                        //createview.InvokeFieldUpdateService("FISPRICEEXCLUDETAX", i);
                        SetPOEntryData(createview, obj, cg, i);
                        Logger.Info("2," + cg["F_LQKJ_MATERIALID"].ToString() + "," + cg["F_LQKJ_REMAINQTY"].ToString(), createview.Model.GetValue("FTaxPrice").ToString());
                        i++;
                    }

                    SetPOEntryData(createview, firstRowObj, firstRow, 0);
                    var onjdy = createview.Model.GetValue("FMaterialId") as DynamicObject;
                    Logger.Info("1," + onjdy["Id"].ToString() + "," + createview.Model.GetValue("FQty").ToString(), createview.Model.GetValue("FTaxPrice").ToString());

                }
                var metadata = MetaDataServiceHelper.Load(this.Context, "PUR_PurchaseOrder") as FormMetadata;

                var arry2 = dynamicObjects.ToArray();
                Kingdee.BOS.ServiceHelper.DBServiceHelper.LoadReferenceObject(this.Context, arry2, metadata.BusinessInfo.GetDynamicObjectType());
                ShowResult(this.View, arry2, "PUR_PurchaseOrder", convertOperationResult);
            }
        }

        private void SetPOEntryData(IBillView createview, DynamicObject curRow, DynamicObject cg, int i)
        {
            if (cg == null) return;
            Logger.Info("单位已验证", "开始替换数据");
            var isIncludedTax = Convert.ToBoolean(cg["F_LQKJ_ITaxnCluded"]);
            curRow["MaterialId_Id"] = cg["F_LQKJ_MATERIALID"];//物料
            createview.InvokeFieldUpdateService("MaterialId_Id", i);
            createview.Model.SetValue("FQty", cg["F_LQKJ_REMAINQTY"], i);
            //后单位为空不需要换算
            //根据物料查出相关带下的数据
            string sql = $@"/*dialect*/select FPURCHASEPRICEUNITID,FRECEIVEADVANCEDAYS,FRECEIVEDELAYDAYS,
FPURCHASEUNITID,FBASEUNITID,FNAME,FCHARGEID,FSALEUNITID,FSTOREUNITID,FGOODBARCODE_CMK
from T_BD_MATERIAL t1
left join t_bd_MaterialPurchase t2 on t1.FMATERIALID=t2.FMATERIALID
left join t_BD_MaterialBase t3 on t3.FMATERIALID=t1.FMATERIALID
left join T_BD_MATERIAL_L t4 on t4.FMATERIALID=t1.FMATERIALID
left join t_BD_MaterialSale t5 on t5.FMATERIALID=t1.FMATERIALID
left join t_BD_MaterialStock t6 on t6.FMATERIALID=t1.FMATERIALID
left join CMK_BD_MATERIAL t7 on t7.FMATERIALID=t1.FMATERIALID 
where t1.FMATERIALID={cg["F_LQKJ_MATERIALID"]}";
            DataTable table1 = DBServiceHelper.ExecuteDataSet(this.Context, sql).Tables[0];
            if (table1.Rows.Count > 0)
            {
                createview.Model.SetValue("FPRICEUNITID", table1.Rows[0]["FPURCHASEPRICEUNITID"], i);
                createview.Model.SetValue("FDELIVERYBEFOREDAYS", table1.Rows[0]["FRECEIVEADVANCEDAYS"], i);
                createview.Model.SetValue("FDELIVERYDELAYDAYS", table1.Rows[0]["FRECEIVEDELAYDAYS"], i);
                createview.Model.SetValue("FUNITID", table1.Rows[0]["FPURCHASEUNITID"], i);
                createview.Model.SetValue("FBASEUNITID", table1.Rows[0]["FBASEUNITID"], i);
                createview.Model.SetValue("FMATERIALDESC", table1.Rows[0]["FNAME"], i);
                createview.Model.SetValue("FCHARGEPROJECTID", table1.Rows[0]["FCHARGEID"], i);
                createview.Model.SetValue("FSALUNITID", table1.Rows[0]["FSALEUNITID"], i);
                createview.Model.SetValue("FSTOCKUNITID", table1.Rows[0]["FSTOREUNITID"], i);
                createview.Model.SetValue("FBARCODE", table1.Rows[0]["FGOODBARCODE_CMK"], i);
            }
            createview.InvokeFieldUpdateService("FQty", i);
            createview.Model.SetValue("FTaxPrice", cg["F_LQKJ_Text"], i);
            if (isIncludedTax)
            {
                Logger.Info(cg["F_LQKJ_MATERIALID"].ToString(), cg["F_LQKJ_Text"].ToString());
                createview.Model.SetValue("FTaxPrice", cg["F_LQKJ_Text"], i);
                createview.InvokeFieldUpdateService("FTaxPrice", i);
            }
            else
            {
                createview.Model.SetValue("FPrice", cg["F_LQKJ_FPRICE"], i);
                createview.InvokeFieldUpdateService("FPrice", i);
            }
            createview.Model.SetValue("F_crh_Price", cg["F_LQKJ_DEFAULTPRICEO"], i);
            createview.Model.SetValue("F_crh_Price1", cg["F_LQKJ_DEFAULTPRICET"], i);
            createview.Model.SetValue("FISINCLUDEDTAX", cg["F_LQKJ_ITaxnCluded"], i);
            createview.InvokeFieldUpdateService("FISINCLUDEDTAX", i);
            Logger.Info("3," + cg["F_LQKJ_MATERIALID"].ToString() + "," + cg["F_LQKJ_REMAINQTY"].ToString(), createview.Model.GetValue("FTaxPrice").ToString());
        }
        public void ShowResult(IDynamicFormView view, DynamicObject[] objs, string targetFormId, ConvertOperationResult operationResult)
        {
            BillShowParameter billShowParameter = new BillShowParameter();
            billShowParameter.ParentPageId = view.PageId;
            if (objs.Length == 1)
            {
                billShowParameter.Status = OperationStatus.ADDNEW;
                billShowParameter.CreateFrom = CreateFrom.Push;
                billShowParameter.AllowNavigation = false;
                string key = "_ConvertSessionKey";
                string text = "ConverOneResult";
                string key2 = "ConvertValidationInfo";
                billShowParameter.CustomParams.Add(key, text);
                view.Session[key2] = operationResult.ValidationErrors;
                view.Session[text] = objs[0];
                billShowParameter.FormId = targetFormId;
                billShowParameter.LayoutId = GetLayoutID(view, targetFormId, objs[0]);
            }
            else
            {
                if (objs.Length <= 1)
                {
                    return;
                }
                billShowParameter.FormId = "BOS_ConvertResultForm";
                string key3 = "ConvertResults";
                string key4 = "ConvertValidationInfo";
                view.Session[key3] = objs;
                view.Session[key4] = operationResult.ValidationErrors;
                billShowParameter.CustomParams.Add("_ConvertResultFormId", targetFormId);
            }
            billShowParameter.OpenStyle.ShowType = ShowType.MainNewTabPage;
            SetShowType(view, billShowParameter);
            view.ShowForm(billShowParameter);
        }

        private string GetLayoutID(IDynamicFormView view, string targetFormId, DynamicObject obj)
        {
            string result = string.Empty;
            BusinessInfo businessInfo = FormMetaDataCache.GetCachedFormMetaData(view.Context, targetFormId).BusinessInfo;
            BillTypeField billTypeField = businessInfo.GetFieldList().FirstOrDefault((Field p) => p is BillTypeField) as BillTypeField;
            if (billTypeField != null)
            {
                DynamicObject dynamicObject = null;
                if (billTypeField.BillTypeInfo.Count > 0)
                {
                    object billTypeID = billTypeField.RefIDDynamicProperty.GetValue(obj);
                    if (!billTypeID.IsNullOrEmptyOrWhiteSpace())
                    {
                        dynamicObject = billTypeField.BillTypeInfo.FirstOrDefault((DynamicObject p) => p["Id"].ToString().Equals(billTypeID));
                        if (!billTypeField.BillTypeIsNormal(dynamicObject))
                        {
                            dynamicObject = null;
                        }
                    }
                    if (dynamicObject == null)
                    {
                        dynamicObject = billTypeField.GetDefaultBillTypeInfo();
                    }
                    if (dynamicObject == null)
                    {
                        List<EnumItem> items = billTypeField.BuildEnumList(false);
                        if (items != null && items.Count > 0)
                        {
                            dynamicObject = billTypeField.BillTypeInfo.Find((DynamicObject p) => p["Id"].Equals(items[0].EnumId));
                        }
                    }
                    if (dynamicObject != null)
                    {
                        DynamicObject dynamicObject2 = dynamicObject["LayoutSolution"] as DynamicObject;
                        if (dynamicObject2 != null)
                        {
                            result = dynamicObject2["Id"].ToString();
                        }
                    }
                }
            }
            return result;
        }
        private void SetShowType(IDynamicFormView view, BillShowParameter param)
        {
            OpenStyle openStyle = view.OpenParameter.GetCustomParameter("openstyle") as OpenStyle;
            if (openStyle != null && openStyle.ShowType == ShowType.Default)
            {
                param.OpenStyle.ShowType = ShowType.Default;
                return;
            }
            if (view.ParentFormView != null)
            {
                OpenStyle openStyle2 = view.ParentFormView.OpenParameter.GetCustomParameter("openstyle") as OpenStyle;
                if (openStyle2 != null && openStyle2.ShowType == ShowType.Default)
                {
                    param.OpenStyle.ShowType = ShowType.Default;
                }
            }
        }

        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);
            billView.LoadData();
            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>
        /// <param name="e"></param>
        public override void DataChanged(DataChangedEventArgs e)
        {

            switch (e.Key)
            {
                case "F_LQKJ_REMAINQTY":
                    int rowIndex = this.View.Model.GetEntryCurrentRowIndex("F_LQKJ_Entity");
                    var num = Convert.ToInt32(this.View.Model.GetValue("F_LQKJ_REMAINQTY", rowIndex));
                    var BeforeNum = Convert.ToInt32(dt.Rows[rowIndex]["FREMAINQTY"]);
                    if (BeforeNum != 0 || num < 0)
                    {
                        if (BeforeNum == 0 || BeforeNum < num || num < 0)
                        {
                            this.View.ShowWarnningMessage("输入数量不正确，不能大于" + num + "或小于等于0");
                            this.View.Model.SetValue("F_LQKJ_REMAINQTY", BeforeNum, rowIndex);
                        }
                    }
                    else if (BeforeNum == 0 || num < 0)
                    {
                        this.View.ShowWarnningMessage("数量为0，不能下推");
                        this.View.Model.SetValue("F_LQKJ_REMAINQTY", BeforeNum, rowIndex);
                    }
                    break;
            }
            base.DataChanged(e);
        }
        /// <summary>
        /// 订单类型、来源单数据查询
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, List<DataRow>> SelectLYDD()
        {
            Dictionary<string, List<DataRow>> YDDic = new Dictionary<string, List<DataRow>>();
            string tab = DBServiceHelper.CreateTemporaryTableName(this.Context);
            string sqldrop = $@"/*dialect*/ IF Object_id('{tab}') IS NOT NULL DROP TABLE {tab}";
            DBUtils.Execute(this.Context, sqldrop);
            string sqll = $@"/*dialect*/select * into {tab} from (
select t3.FID,t1z.FBILLNO,t1.FMATERIALID, t4.FDEMANDTYPE,
FSALEORDERID,FSALEORDERENTRYID,
case t4.FDEMANDTYPE when 1 then '1'
when 2 then '2' when 3 then '3' when 4 then '4'
when 5 then '5' when '' then '6' when 0 then '6'
end typenum
from T_PUR_Requisition T1z
LEFT JOIN T_PUR_ReqEntry t1 on t1.FID = t1z.fid
LEFT JOIN T_PUR_REQENTRY_R T2 on t1.FENTRYID = t2.FENTRYID
LEFT JOIN T_PLN_PLANORDER T3 on t2.FSRCBILLNO = t3.FBILLNO
LEFT JOIN T_PLN_PLANORDER_B T4 ON T3.FID = T4.FID where T3.FID is not null
) as t";
            DBUtils.Execute(this.Context, sqll);
            DBUtils.Execute(this.Context, $@"/*dialect*/ALTER INDEX ALL ON T_MRP_COMPUTEBILL REBUILD");
            DBUtils.Execute(this.Context, $@"/*dialect*/ALTER INDEX ALL ON T_MRP_DEMANDDATA REBUILD");
            DBUtils.Execute(this.Context, $@"/*dialect*/ALTER INDEX ALL ON T_MRP_DEMANDDATA_F REBUILD");
            string sql1 = $@"/*dialect*/select t7.FBASEQTY,t7.FRELATIONBILLNO xsd,t1.FBILLNO sqd,t9.FNUMBER,t1e.FENTRYID,t2.FBOMID,FBOMENTRYID BOMEBTRYID from T_PUR_Requisition  t1
inner join T_PUR_REQENTRY t1e on t1.FID=t1e.FID
inner join T_PUR_REQENTRY_R t3 on t1e.FENTRYID=t3.FENTRYID
inner join T_PLN_PLANORDER t2 on t3.FSRCBILLNO=t2.FBILLNO
inner join T_MRP_COMPUTEBILL t6 on t2.FCOMPUTERNO=t6.FBILLNO
inner join T_MRP_DEMANDDATA t7 on t6.FID=t7.FID and t2.FMATERIALID=t7.FMATERIALID
left join T_MRP_DEMANDDATA_F t8 on t7.FENTRYID=t8.FENTRYID
left join T_ENG_BOMCHILD T10 ON T8.FBOMENTRYID=T10.FENTRYID
LEFT JOIN T_ENG_BOM T11 ON T10.FID=T11.FID
left join T_BD_MATERIAL t9 on t9.FMASTERID=T11.FMATERIALID
where t2.FID in(select FID from {tab} where typenum=6 or FSALEORDERENTRYID=0) and FRELATIONFORMID='PRD_PPBOM'";
            Logger.Info("sql1:", sql1);//7
            DataTable dataTable1 = DBServiceHelper.ExecuteDataSet(this.Context, sql1).Tables[0];
            for (int i = 0; i < dataTable1.Rows.Count; i++)
            {
                var nowRow = dataTable1.Rows[i];
                if (nowRow["FNUMBER"].IsNullOrEmptyOrWhiteSpace()) continue;
                List<DataRow> listRows = new List<DataRow>();
                List<DataRow> addlistRows = new List<DataRow>();
                if (YDDic.Count > 0)
                {
                    if (YDDic.ContainsKey(nowRow["FENTRYID"].ToString()))
                    {
                        listRows = YDDic[nowRow["FENTRYID"].ToString()];
                        var row = listRows[0];
                        if (Convert.ToDouble(row["FBASEQTY"]) < Convert.ToDouble(nowRow["FBASEQTY"]))
                        {
                            addlistRows.Add(nowRow);
                            YDDic[nowRow["FENTRYID"].ToString()] = addlistRows;
                        }
                    }
                    else
                    {
                        listRows.Add(nowRow);
                        YDDic[nowRow["FENTRYID"].ToString()] = listRows;
                    }
                }
                else
                {
                    listRows.Add(nowRow);
                    YDDic[nowRow["FENTRYID"].ToString()] = listRows;
                }


            }



            string sql2 = $@"/*dialect*/
with stepCTE AS 
	( 
	select b.FMATERIALID as f, a.FMATERIALID as z,a.FID,a.FENTRYID,1 AS Lev  from T_ENG_BOMCHILD a inner join ( select * from T_ENG_BOM  where FID in (select FBOMID from T_SAL_ORDERENTRY where FENTRYID in (select FSALEORDERENTRYID from {tab} where typenum=1)) ) b on a.FID=b.FID
	union all
	select c.f as f ,c.z as z,cte.FID,c.FENTRYID,cte.Lev+1  from 
	(
	select a.FMATERIALID z ,b.FMATERIALID f,a.FID,a.FENTRYID  from T_ENG_BOMCHILD a inner join T_ENG_BOM b on a.FID=b.FID  inner join T_BD_MATERIAL ma on a.FMATERIALID=ma.FMATERIALID 
	) c 
	inner join stepCTE cte on cte.z=c.f
	) 
	select t6.FBILLNO xsd,t1.FBILLNO sqd,t8.FNUMBER,t2.FENTRYID,t7.FBOMID,stepCTE.z FMATERIALID,stepCTE.FENTRYID BOMEBTRYID  from T_PUR_Requisition t1
    left join T_PUR_REQENTRY t2 on t1.FID=t2.FID
    left join T_PUR_REQENTRY_R t3 on t2.FENTRYID=t3.FENTRYID
    left join T_PLN_PLANORDER t4 on t3.FSRCBILLNO=t4.FBILLNO
    left join T_PLN_PLANORDER_B t5 on t4.FID=t5.FID
    left join T_SAL_ORDER t6 on t6.FID=t5.FSALEORDERID
    left join T_SAL_ORDERENTRY t7 on t6.FID=t7.FID and t5.FSALEORDERENTRYID=t7.FENTRYID
    left join T_BD_MATERIAL t8 on t7.FMATERIALID=t8.FMATERIALID
    left join (select FSALEORDERENTRYID from {tab} where typenum=1 group by FSALEORDERENTRYID) t9 on t7.FENTRYID=t9.FSALEORDERENTRYID
    left join stepCTE on stepCTE.FID=t7.FBOMID and stepCTE.z=t2.FMATERIALID";
            Logger.Info("sql2", sql2);//3
            DataTable dataTable2 = DBServiceHelper.ExecuteDataSet(this.Context, sql2).Tables[0];
            for (int i = 0; i < dataTable2.Rows.Count; i++)
            {
                var nowRow = dataTable2.Rows[i];
                if (nowRow["FNUMBER"].IsNullOrEmptyOrWhiteSpace()) continue;
                List<DataRow> listRows;
                if (!YDDic.TryGetValue(nowRow["FENTRYID"].ToString(), out listRows))
                {
                    listRows = new List<DataRow>();
                    YDDic.Add(nowRow["FENTRYID"].ToString(), listRows);
                }
                listRows.Add(nowRow);

            }


            string sql3 = $@"/*dialect*/with stepCTE AS 
	( 
	select b.FMATERIALID as f, a.FMATERIALID as z,a.FID,a.FENTRYID,1 AS Lev  from T_ENG_BOMCHILD a inner join ( select * from T_ENG_BOM  where FID in (select FBOMID from T_PLN_FORECASTENTRY where FENTRYID in (select FSALEORDERENTRYID from {tab} where typenum=2)) ) b on a.FID=b.FID
	union all
	select c.f as f ,c.z as z,cte.FID,c.FENTRYID,cte.Lev+1  from 
	(
	select a.FMATERIALID z ,b.FMATERIALID f,a.FID,a.FENTRYID  from T_ENG_BOMCHILD a inner join T_ENG_BOM b on a.FID=b.FID  inner join T_BD_MATERIAL ma on a.FMATERIALID=ma.FMATERIALID 
	) c 
	inner join stepCTE cte on cte.z=c.f
	) 
	select t6.FBILLNO xsd,t1.FBILLNO sqd,t8.FNUMBER,t2.FENTRYID,t7.FBOMID,stepCTE.z FMATERIALID,stepCTE.FENTRYID BOMEBTRYID  from T_PUR_Requisition t1
    left join T_PUR_REQENTRY t2 on t1.FID=t2.FID
    left join T_PUR_REQENTRY_R t3 on t2.FENTRYID=t3.FENTRYID
    left join T_PLN_PLANORDER t4 on t3.FSRCBILLNO=t4.FBILLNO
    left join T_PLN_PLANORDER_B t5 on t4.FID=t5.FID
left join T_PLN_FORECAST t6 on t6.FID=t5.FSALEORDERID
left join T_PLN_FORECASTENTRY t7 on t7.FID=t6.FID and t5.FSALEORDERENTRYID=t7.FENTRYID
left join T_BD_MATERIAL t8 on t7.FMATERIALID=t8.FMATERIALID
left join (select FSALEORDERENTRYID from {tab} where typenum=2 group by FSALEORDERENTRYID) t9 on t7.FENTRYID=t9.FSALEORDERENTRYID
left join stepCTE on stepCTE.FID=t7.FBOMID and stepCTE.z=t2.FMATERIALID";
            //where t7.FENTRYID in (select FSALEORDERENTRYID from {tab} where typenum=2)";
            Logger.Info("sql3", sql3);//14
            DataTable dataTable3 = DBServiceHelper.ExecuteDataSet(this.Context, sql3).Tables[0];
            Logger.Info("sql3", "执行完成");
            for (int i = 0; i < dataTable3.Rows.Count; i++)
            {
                var nowRow = dataTable3.Rows[i];
                if (nowRow["FNUMBER"].IsNullOrEmptyOrWhiteSpace()) continue;
                List<DataRow> listRows;
                if (!YDDic.TryGetValue(nowRow["FENTRYID"].ToString(), out listRows))
                {
                    listRows = new List<DataRow>();
                    YDDic.Add(nowRow["FENTRYID"].ToString(), listRows);
                }
                listRows.Add(nowRow);
            }


            string sql4 = $@"/*dialect*/
with stepCTE AS 
	( 
	select b.FMATERIALID as f, a.FMATERIALID as z,a.FID,a.FENTRYID,1 AS Lev  from T_ENG_BOMCHILD a inner join ( select * from T_ENG_BOM  where FID in (select FBOMID from T_PLN_REQUIREMENTORDER where FID in (select FSALEORDERENTRYID from {tab} where typenum=3)) ) b on a.FID=b.FID
	union all
	select c.f as f ,c.z as z,cte.FID,c.FENTRYID,cte.Lev+1  from 
	(
	select a.FMATERIALID z ,b.FMATERIALID f,a.FID,a.FENTRYID  from T_ENG_BOMCHILD a inner join T_ENG_BOM b on a.FID=b.FID  inner join T_BD_MATERIAL ma on a.FMATERIALID=ma.FMATERIALID 
	) c 
	inner join stepCTE cte on cte.z=c.f
	) 
	select t6.FBILLNO xsd,t1.FBILLNO sqd,t8.FNUMBER,t2.FENTRYID,t6.FBOMID,stepCTE.z FMATERIALID,stepCTE.FENTRYID BOMEBTRYID  from T_PUR_Requisition t1
    left join T_PUR_REQENTRY t2 on t1.FID=t2.FID
    left join T_PUR_REQENTRY_R t3 on t2.FENTRYID=t3.FENTRYID
    left join T_PLN_PLANORDER t4 on t3.FSRCBILLNO=t4.FBILLNO
    left join T_PLN_PLANORDER_B t5 on t4.FID=t5.FID
left join T_PLN_PLANORDER_B t5b on t4.FID=t5b.FID
left join T_PLN_REQUIREMENTORDER t6 on t6.FID=t5.FSALEORDERID and t5.FSALEORDERENTRYID=t6.FID
left join T_BD_MATERIAL t8 on t6.FMATERIALID=t8.FMATERIALID
left join (select FSALEORDERENTRYID from {tab} where typenum=3 group by FSALEORDERENTRYID) t9 on t6.FID=t9.FSALEORDERENTRYID
    left join stepCTE on stepCTE.FID=t6.FBOMID and stepCTE.z=t2.FMATERIALID";
            Logger.Info("sql4", sql4);//0
            DataTable dataTable4 = DBServiceHelper.ExecuteDataSet(this.Context, sql4).Tables[0];
            for (int i = 0; i < dataTable4.Rows.Count; i++)
            {
                var nowRow = dataTable4.Rows[i];
                if (nowRow["FNUMBER"].IsNullOrEmptyOrWhiteSpace()) continue;
                List<DataRow> listRows;
                if (!YDDic.TryGetValue(nowRow["FENTRYID"].ToString(), out listRows))
                {
                    listRows = new List<DataRow>();
                    YDDic.Add(nowRow["FENTRYID"].ToString(), listRows);
                }
                listRows.Add(nowRow);
            }


            string sql5 = $@"/*dialect*/with stepCTE AS 
	( 
	select b.FMATERIALID as f, a.FMATERIALID as z,a.FID,a.FENTRYID,1 AS Lev  from T_ENG_BOMCHILD a inner join ( select * from T_ENG_BOM  where FID in (select FBOMID from T_PRD_MOENTRY where FENTRYID in (select FSALEORDERENTRYID from {tab} where typenum=5)) ) b on a.FID=b.FID
	union all
	select c.f as f ,c.z as z,cte.FID,c.FENTRYID,cte.Lev+1  from 
	(
	select a.FMATERIALID z ,b.FMATERIALID f,a.FID,a.FENTRYID  from T_ENG_BOMCHILD a inner join T_ENG_BOM b on a.FID=b.FID  inner join T_BD_MATERIAL ma on a.FMATERIALID=ma.FMATERIALID 
	) c 
	inner join stepCTE cte on cte.z=c.f
	) 
	select t6.FBILLNO xsd,t1.FBILLNO sqd,t8.FNUMBER,t2.FENTRYID,t7.FBOMID,stepCTE.z FMATERIALID,stepCTE.FENTRYID BOMEBTRYID  from T_PUR_Requisition t1
    left join T_PUR_REQENTRY t2 on t1.FID=t2.FID
    left join T_PUR_REQENTRY_R t3 on t2.FENTRYID=t3.FENTRYID
    left join T_PLN_PLANORDER t4 on t3.FSRCBILLNO=t4.FBILLNO
    left join T_PLN_PLANORDER_B t5 on t4.FID=t5.FID
                                            left join T_PRD_MO t6 on t6.FID=t5.FSALEORDERID
                                            left join T_PRD_MOENTRY t7 on t7.FID=t6.FID and t5.FSALEORDERENTRYID=t7.FENTRYID
                                            left join T_BD_MATERIAL t8 on t7.FMATERIALID=t8.FMATERIALID
                                left join (select FSALEORDERENTRYID from {tab} where typenum=5 group by FSALEORDERENTRYID) t9 on t7.FENTRYID=t9.FSALEORDERENTRYID
    left join stepCTE on stepCTE.FID=t7.FBOMID and stepCTE.z=t2.FMATERIALID";
            Logger.Info("sql5", sql5);//0
            DataTable dataTable5 = DBServiceHelper.ExecuteDataSet(this.Context, sql5).Tables[0];
            for (int i = 0; i < dataTable5.Rows.Count; i++)
            {
                var nowRow = dataTable5.Rows[i];
                if (nowRow["FNUMBER"].IsNullOrEmptyOrWhiteSpace()) continue;
                List<DataRow> listRows;
                if (!YDDic.TryGetValue(nowRow["FENTRYID"].ToString(), out listRows))
                {
                    listRows = new List<DataRow>();
                    YDDic.Add(nowRow["FENTRYID"].ToString(), listRows);
                }
                listRows.Add(nowRow);
            }
            //删除表
            string[] strarr = new string[1];
            strarr[0] = tab;
            DBServiceHelper.DeleteTemporaryTableName(this.Context, strarr);
            return YDDic;
        }
    }
}
