using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LQKJ.K3.MFG.PRD.BusinessPlugIn
{
    [Kingdee.BOS.Util.HotUpdate]
    [Description("替代资料查询")]
    public class SelectMATERIAL : AbstractDynamicFormPlugIn
    {
        DataTable dt;
        string ids;
        public override void PreOpenForm(PreOpenFormEventArgs e)
        {
            //Logger.Info("查询开始", "查询开始");
            string fid = e.OpenParameter.GetCustomParameter("wl").ToString();
            //string bom = e.OpenParameter.GetCustomParameter("bom").ToString();
            string BOMEBTRYID = e.OpenParameter.GetCustomParameter("BOMEBTRYID").ToString();
            Logger.Info("BOMEBTRYID", BOMEBTRYID.ToString());
            string sql = $@"/*dialect*/select t1.fid,t1.FMATERIALID, t5.FPURCHASEUNITID wlunit,t3.FNUMBER,t4.FNAME,FSPECIFICATION from T_ENG_BOMCHILD t1
left join T_ENG_BOMCHILD_A T2 ON T1.FENTRYID=T2.FENTRYID and t2.FID=(select FID from T_ENG_BOMCHILD where  FENTRYID = {BOMEBTRYID} )
left join T_BD_MATERIAL t3 on t1.FMATERIALID=t3.FMATERIALID
left join T_BD_MATERIAL_L t4 on t3.FMATERIALID=t4.FMATERIALID
left join t_bd_MaterialPurchase t5 on t5.FMATERIALID=t3.FMATERIALID
where 
(
	FPARENTROWID in(
		select FROWID from T_ENG_BOMCHILD t1
		left join T_ENG_BOMCHILD_A T2 ON T1.FENTRYID=T2.FENTRYID
		WHERE t1.FENTRYID={BOMEBTRYID}
	) or FPARENTROWID in
	(
		select
		case  FPARENTROWID when ' ' then '0' else FPARENTROWID end FPARENTROWID from T_ENG_BOMCHILD t1
		left join T_ENG_BOMCHILD_A T2 ON T1.FENTRYID=T2.FENTRYID
		WHERE t1.FENTRYID={BOMEBTRYID}

	)
	or FROWID in
	(
		select
		case  FPARENTROWID when ' ' then '0' else FPARENTROWID end FPARENTROWID from T_ENG_BOMCHILD t1
		left join T_ENG_BOMCHILD_A T2 ON T1.FENTRYID=T2.FENTRYID
		WHERE t1.FENTRYID={BOMEBTRYID}

	)
) or t1.FENTRYID = {BOMEBTRYID}";
            //and t1.FENTRYID<> { BOMEBTRYID}
            //Logger.Info("替代资料查询:", sql);
            dt = DBServiceHelper.ExecuteDataSet(e.Context, sql).Tables[0];
           // Logger.Info(" dt.count:", dt.Rows.Count.ToString());
            if (dt.Rows.Count <= 0)
            {
                e.Cancel = true;
                e.CancelMessage = "未查找到相关替代料数据";
            }
            else
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ids += dt.Rows[i]["FMATERIALID"].ToString() + ",";
                }
            }
            base.PreOpenForm(e);
        }
        public override void AfterBindData(EventArgs e)
        {
            string sql = $@"/*dialect*/select t1.FMATERIALID,FPRICE,t3.FNAME,FISINCLUDEDTAX,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
where t1.FEXPIRYDATE>GETDATE() and t1.FEFFECTIVEDATE<GETDATE() and FDOCUMENTSTATUS='C' and FFORBIDSTATUS='A' and FROWAUDITSTATUS='A'
and t1.FMATERIALID in({ids.Remove(ids.LastIndexOf(","))})
order by t1.FEFFECTIVEDATE desc";
            DataTable bjdt = DBServiceHelper.ExecuteDataSet(this.Context, sql).Tables[0];
            var abc = dt.Rows.Count - 1;
            this.Model.BatchCreateNewEntryRow("F_LQKJ_Entity", dt.Rows.Count );
            //数据绑定到单据体
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //Logger.Info("替代物料:", dt.Rows[i]["FNUMBER"].ToString());
                this.View.Model.SetValue("F_LQKJ_Number", dt.Rows[i]["FNUMBER"].ToString(), i);
                this.View.Model.SetValue("F_LQKJ_Name", dt.Rows[i]["FNAME"].ToString(), i);
                this.View.Model.SetValue("F_LQKJ_Type", dt.Rows[i]["FSPECIFICATION"].ToString(), i);
                this.View.Model.SetValue("F_LQKJ_Text", dt.Rows[i]["FMATERIALID"].ToString(), i);
                this.View.Model.SetValue("F_LQKJ_Unit", dt.Rows[i]["wlunit"].ToString(), i);
                var a = bjdt.Select("FMATERIALID=" + dt.Rows[i]["FMATERIALID"].ToString()).FirstOrDefault();
                if (a != null)
                {
                    this.View.Model.SetValue("F_LQKJ_Price", Convert.ToDouble(a["FPRICE"]), i);
                    this.View.Model.SetValue("F_LQKJ_supplier", a["FNAME"], i);
                    this.View.Model.SetValue("F_LQKJ_CheckBox", a["FISINCLUDEDTAX"], i);
                    this.View.Model.SetValue("F_LQKJ_RMB", a["FCURRENCYID"], i);
                }
               
            }
           
            this.View.UpdateView("F_LQKJ_Entity");
            base.AfterBindData(e);
        }
        /// <summary>
        /// 双击返回数据，关闭弹窗
        /// </summary>
        /// <param name="e"></param>
        public override void EntityRowDoubleClick(EntityRowClickEventArgs e)
        {
            base.EntityRowDoubleClick(e);

            int rowIndex = this.View.Model.GetEntryCurrentRowIndex("F_LQKJ_Entity");
            var entity = this.View.BillBusinessInfo.GetEntity("F_LQKJ_Entity");
            DynamicObjectCollection entityObjs = this.View.Model.GetEntityDataObject(entity);
            //返回选中的供应商
            var wl = entityObjs[rowIndex]["F_LQKJ_Number"].ToString();
            var name = entityObjs[rowIndex]["F_LQKJ_Name"].ToString();
            var gg = entityObjs[rowIndex]["F_LQKJ_Type"].ToString();
            var dw = entityObjs[rowIndex]["F_LQKJ_Unit"].ToString();
            var FMATERIALID = entityObjs[rowIndex]["F_LQKJ_Text"].ToString();
            List<string> list = new List<string>();
            list.Add(wl);//供应商
            list.Add(name);//物料
            list.Add(gg);//规格
            list.Add(FMATERIALID);//物料
            list.Add(dw);//规格
            this.View.ReturnToParentWindow(list);
            this.View.Close();
        }
        public override void BeforeDoOperation(BeforeDoOperationEventArgs e)
        {
            //确定
            if (e.Operation.FormOperation.Id == "but2")
            {
                int rowIndex = this.View.Model.GetEntryCurrentRowIndex("F_LQKJ_Entity");
                var entity = this.View.BillBusinessInfo.GetEntity("F_LQKJ_Entity");
                DynamicObjectCollection entityObjs = this.View.Model.GetEntityDataObject(entity);
                //返回选中的供应商
                var wl = entityObjs[rowIndex]["F_LQKJ_Number"].ToString();
                var name = entityObjs[rowIndex]["F_LQKJ_Name"].ToString();
                var gg = entityObjs[rowIndex]["F_LQKJ_Type"].ToString();
                var FMATERIALID = entityObjs[rowIndex]["F_LQKJ_Text"].ToString();
                List<string> list = new List<string>();
                list.Add(wl);//供应商
                list.Add(name);//物料
                list.Add(gg);//规格
                list.Add(FMATERIALID);//物料
                this.View.ReturnToParentWindow(list);
                this.View.Close();
            }
            //取消
            if (e.Operation.FormOperation.Id == "close")
            {
                this.View.Close();
            }
        }
    }
}
