using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using DirectService.Tools;
using JLHHJSvr.BLL;
using JLHHJSvr.Com;
using JLHHJSvr.Com.Model;
using JLHHJSvr.Helper;
using JLHHJSvr.LJException;
using JLHHJSvr.Tools;
using LJLib.DAL.SQL;
using LJLib.Net.SPI.Server;
using Newtonsoft.Json.Linq;

namespace JLHHJSvr.Excutor
{
    internal sealed class GetMtrlDefListExcutor : ExcutorBase<GetMtrlDefListRequest, GetMtrlDefListResponse>
    {
        protected override void ExcuteInternal(GetMtrlDefListRequest request, object state, GetMtrlDefListResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }

            using (var con = new SqlConnection(GlobalVar.ConnectionString))
            using (var cmd = con.CreateCommand())
            {
                con.Open();

                var selectStr = @"SELECT u_mtrl_price.mtrlid
		                            ,u_mtrl_price.mtrltype
		                            ,u_mtrl_price.name
		                            ,u_mtrl_price.priceunit
		                            ,u_mtrl_price.shrinkage
		                            ,u_mtrl_price.gram_weight
		                            ,u_mtrl_price.cloth_width
		                            ,u_mtrl_price.if_inputqty
		                            ,u_mtrl_price.if_areaprice
		                            ,u_mtrl_price.createtime
		                            ,u_mtrl_price.createby
		                            ,isnull(u_mtrl_price_pricelist.price, 0) AS price
		                            ,u_mtrl_price.thickness
		                            ,u_mtrl_price.dscrp
		                            ,erp_mtrlid
		                            ,u_mtrl_price.fjcnt AS fjcnt
		                            ,u_mtrl_price.isuse AS isuse
		                            ,u_mtrl_price.lastdate AS lastdate
		                            ,u_mtrl_price.handtype AS handtype
		                            ,u_mtrl_price_pricelist.pricelistid
                                    ,u_mtrl_price.if_subspecs
	                            FROM u_mtrl_price
	                            INNER JOIN u_mtrl_price_pricelist ON u_mtrl_price.mtrlid = u_mtrl_price_pricelist.mtrlid";
                var list = new List<u_mtrl_price>();
				var whereList = new List<string>();
				var parms = new Dictionary<string, object>();

				if(request.pricelistid != null && request.pricelistid > 0)
				{
                    whereList.Add("u_mtrl_price_pricelist.pricelistid = @pricelistid");
                    parms.Add("@pricelistid", request.pricelistid);
                }

                if (request.mtrltypeids != null && request.mtrltypeids.Any())
                {
                    whereList.Add($"u_mtrl_price.mtrltype IN {ListEx.getString(request.mtrltypeids)}");
                }

                if (!string.IsNullOrEmpty(request.keyword))
                {
                    whereList.Add(@"(u_mtrl_price.name LIKE @keyword)");
                    parms.Add("@keyword", "%" + request.keyword + "%");
                }

                var outputFields = "mtrlid,mtrltype,name,priceunit,shrinkage,gram_weight,cloth_width,if_inputqty,if_areaprice,createtime,createby,price,thickness,dscrp,erp_mtrlid,fjcnt,isuse,lastdate,handtype,pricelistid,if_subspecs";
                DbSqlHelper.SelectJoin(cmd, selectStr, ListEx.GetWhereStr(whereList), parms, "mtrlid", outputFields, request.pageNum, request.pageSize, list);

                // 
                var selectCntStr = @"SELECT COUNT(0) FROM u_mtrl_price INNER JOIN u_mtrl_price_pricelist ON u_mtrl_price.mtrlid = u_mtrl_price_pricelist.mtrlid";
                if (whereList.Any())
                {
                    selectCntStr += " WHERE ";
                    selectCntStr += ListEx.GetWhereStr(whereList);
                }
                cmd.CommandText = selectCntStr;
                cmd.Parameters.Clear();
                foreach (var item in parms)
                {
                    cmd.Parameters.AddWithValue(item.Key, item.Value);
                }
                var totalcnt = Convert.ToInt32(cmd.ExecuteScalar());
                rslt.totalcnt += totalcnt;

        //        selectStr = @"SELECT u_mtrl_price.mtrlid
								//	,u_mtrl_price.mtrltype
								//	,u_mtrl_price.name
								//	,u_mtrl_price.priceunit
								//	,u_mtrl_price.shrinkage
								//	,u_mtrl_price.gram_weight
								//	,u_mtrl_price.cloth_width
								//	,u_mtrl_price.if_inputqty
								//	,u_mtrl_price.if_areaprice
								//	,u_mtrl_price.createtime
								//	,u_mtrl_price.createby
								//	,0 AS price
								//	,u_mtrl_price.thickness
								//	,u_mtrl_price.dscrp
								//	,erp_mtrlid
								//	,u_mtrl_price.fjcnt AS fjcnt
								//	,u_mtrl_price.isuse AS isuse
								//	,u_mtrl_price.lastdate AS lastdate
								//	,u_mtrl_price.handtype AS handtype
								//	,0 AS pricelistid
								//FROM u_mtrl_price";

        //        whereList.Clear();
        //        parms.Clear();
        //        if (request.pricelistid != null && request.pricelistid > 0)
        //        {
        //            whereList.Add(@"u_mtrl_price.mtrlid NOT IN (
								//			SELECT mtrlid
								//			FROM u_mtrl_price_pricelist
								//			WHERE pricelistid = @pricelistid
								//			)");
        //            parms.Add("@pricelistid", request.pricelistid);
        //        }

        //        if (request.mtrltypeids != null && request.mtrltypeids.Any())
        //        {
        //            whereList.Add($"u_mtrl_price.mtrltype IN {ListEx.getString(request.mtrltypeids)}");
        //        }

        //        DbSqlHelper.SelectJoin(cmd, selectStr, ListEx.GetWhereStr(whereList), parms, "mtrlid", outputFields, request.pageindex, request.pagesize, list);

        //        totalcnt = DbSqlHelper.SelectCount(cmd, "u_mtrl_price", ListEx.GetWhereStr(whereList), parms);
        //        rslt.totalcnt += totalcnt;

                var mtrlids = new List<int>();
                foreach(var mtrl in list)
                {
                    if (mtrl.erp_mtrlid > 0) mtrlids.Add(mtrl.erp_mtrlid.Value);
                }

                //if(mtrlids.Count > 0)
                //{
                //    var mtrldefList = new List<erp_mtrldef>();
                //    var erp_mtrl_dict = new Dictionary<int, erp_mtrldef>();

                //    var erpHelper = HelperBase.GetHelper<ERPHelper>(null);

                //    var parameters = new JObject();
                //    parameters.Add("mtrlids", JToken.FromObject(mtrlids));

                //    mtrldefList = erpHelper.GetERPList<erp_mtrldef>("GetL1Mtrldef", parameters);

                //    foreach (var mtrl in mtrldefList)
                //    {
                //        erp_mtrl_dict.Add(mtrl.mtrlid.Value, mtrl);
                //    }

                //    foreach(var mtrl in list)
                //    {
                //        if(mtrl.erp_mtrlid > 0 && erp_mtrl_dict.TryGetValue(mtrl.erp_mtrlid.Value,out var mtrl_temp))
                //        {
                //            mtrl.erp_mtrlcode = mtrl_temp.mtrlcode;
                //            mtrl.erp_mtrlname = mtrl_temp.mtrlname;
                //            mtrl.erp_mtrlmode = mtrl_temp.mtrlmode;
                //            mtrl.erp_unit = mtrl_temp.unit;
                //            mtrl.erp_mtrlengname = mtrl_temp.mtrlengname;
                //        }
                //    }
                //}

                if (mtrlids.Count > 0)
                {
                    var erpHelper = HelperBase.GetHelper<ERPHelper>(null);
                    var total = 0;
                    var resultList = erpHelper.GetERPMtrldef(cmd, ref total, "", new L1Mtrldef(), 0, 0, 1, mtrlids);

                    if (resultList != null && resultList.Any())
                    {
                        foreach (var mx in list)
                        {
                            var result = resultList.FirstOrDefault(o => o.mtrlid == mx.erp_mtrlid);
                            if (result != null)
                            {
                                mx.erp_mtrlcode = result.mtrlcode;
                                mx.erp_mtrlname = result.mtrlname;
                                mx.erp_mtrlmode = result.mtrlmode;
                                mx.erp_unit = result.unit;
                                mx.erp_mtrlengname = result.zxmtrlmode;
                            }
                        }
                    }
                }

                rslt.list = list;
                rslt.pageindex = request.pageNum;
                rslt.pagesize = request.pageSize;
            }
        }
    }
}
