using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using JLHHJSvr.Com;
using JLHHJSvr.Com.Model;
using LJLib.Net.SPI.Server;

namespace JLHHJSvr.Excutor
{
    internal sealed class JLH_FetchPriceExcutor:ExcutorBase<JLH_FetchPriceRequest, JLH_FetchPriceResponse>
    {
        protected override void ExcuteInternal(JLH_FetchPriceRequest request, object state, JLH_FetchPriceResponse rslt)
        {
            if (request.token != "7DEA6FF3-3E81-4EDA-8A02-1F56073A45FD")
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }

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

                rslt.list = new List<u_configure_codemx>();

                cmd.CommandText = @"SELECT
                            MAX(
								CASE WHEN u_mattress_interface_qd.erp_mtrlid > 0 and u_mattress_interface_qd.useqty > 0
								THEN u_mattress_mx_mtrl.costamt / u_mattress_interface_qd.useqty
								ELSE 0 END
							) AS price 
							,MAX(u_mattress_interface_qd.useqty) AS useqty 
							, u_mattress.erp_mtrlcode
                            , u_mtrldef.mtrlcode
                            , u_mattress_interface_qd.wrkgrpcode2
                            from u_mattress_interface_qd
                            INNER JOIN u_mattress_mx_mtrl on u_mattress_mx_mtrl.mattressid = u_mattress_interface_qd.mattressid
													and u_mattress_mx_mtrl.mtrlid = u_mattress_interface_qd.mtrlid
							INNER JOIN u_mtrldef on u_mtrldef.mtrlid  = u_mattress_interface_qd.erp_mtrlid
							INNER JOIN u_mattress on u_mattress.mattressid  = u_mattress_interface_qd.mattressid
							WHERE 
							    u_mattress_interface_qd.erp_mtrlid  > 0
							    and u_mattress_interface_qd.actual_useqty > 0
							    and u_mattress_interface_qd.mtrlid > 0
							
							GROUP BY u_mtrldef.mtrlcode, u_mattress.erp_mtrlcode, u_mattress_interface_qd.wrkgrpcode2
							";
                cmd.Parameters.Clear();

                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        rslt.list.Add(new u_configure_codemx()
                        {
                            mtrlcode = Convert.ToString(reader["mtrlcode"]).Trim(),
                            price = Convert.ToDecimal(reader["price"]),
                            useqty = Convert.ToDecimal(reader["useqty"]),
                            erp_mtrlcode = Convert.ToString(reader["erp_mtrlcode"]).Trim(),
                            wrkgrpcode2 = Convert.ToString(reader["wrkgrpcode2"]).Trim(),
                        });
                    }
                }

            }
        }
    }
}
