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.actual_useqty > 0
								THEN u_mattress_mx_mtrl.costamt / u_mattress_interface_qd.actual_useqty
								ELSE 0 END
							) AS price 
                            ,u_mattress_interface_qd.mtrlid, u_mattress_interface_qd.erp_mtrlid
                            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
							where 
							u_mattress_interface_qd.mattressid = 17493977
							and 
							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_mattress_interface_qd.mtrlid, u_mattress_interface_qd.erp_mtrlid
							";
                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"]),
                        });
                    }
                }

            }
        }
    }
}
