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

namespace JLHHJSvr.Excutor
{
    internal sealed class GetMattressInterfaceListExcutor : ExcutorBase<GetMattressInterfaceListRequest, GetMattressInterfaceListResponse>
    {
        protected override void ExcuteInternal(GetMattressInterfaceListRequest request, object state, GetMattressInterfaceListResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }
            if (request.mattressid == null || request.mattressid <= 0)
            {
                rslt.ErrMsg = "床垫id有误,请检查!";
                return;
            }

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

                cmd.CommandText = @"SELECT u_mattress.mattressid
	                                ,u_mattress.erp_mtrlid
	                                ,u_mattress.mattressname
	                                ,u_mattress.erp_configcodetype
	                                ,u_mattress.mattresscode
	                                ,u_mattress.mattressrelcode
                                    ,mattress_width
									,mattress_length
									,mattress_height
	                                ,erp_mtrltypeid
	                                ,erp_mtrlcode
	                                ,erp_mtrlname
	                                ,erp_mtrlmode
	                                ,erp_mtrlunit
	                                ,erp_mtrltype
	                                ,CASE 
		                                WHEN isnull(erp_mtrlengname, '') = ''
			                                THEN mattressrelcode
		                                ELSE erp_mtrlengname
		                                END AS erp_mtrlengname
	                                ,old_mtrlname AS old_mtrlname
                                    ,deptid
                                    ,yw_flag
                                    ,js1_flag
                                    ,js2_flag
		                            ,ISNULL(parentid, 0) AS parentid
		                            ,vv_mattress.child_count
                                FROM u_mattress
		                        LEFT JOIN (
			                        SELECT
				                        um.mattressid,
				                        COUNT(um2.mattressid) AS child_count
			                        FROM
				                        u_mattress um
			                        LEFT JOIN
				                        u_mattress um2 ON um.mattressid = um2.parentid
			                        GROUP BY um.mattressid
		                        ) AS vv_mattress on vv_mattress.mattressid = u_mattress.mattressid
                                WHERE u_mattress.mattressid = @mattressid";
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@mattressid", request.mattressid);
                using (var reader = cmd.ExecuteReader()) 
                {
                    if (reader.Read()) {

                        rslt.mattress = new u_mattress()
                        {
                            mattressid = request.mattressid.Value,
                            erp_mtrlid = Convert.ToInt32(reader["erp_mtrlid"]),
                            deptid = Convert.ToInt32(reader["deptid"]),
                            mattressname = Convert.ToString(reader["mattressname"]),
                            mattresscode = Convert.ToString(reader["mattresscode"]),
                            mattressrelcode = Convert.ToString(reader["mattressrelcode"]),
                            mattress_width = Convert.ToInt32(reader["mattress_width"]),
                            mattress_length = Convert.ToInt32(reader["mattress_length"]),
                            mattress_height = Convert.ToInt32(reader["mattress_height"]),
                            erp_configcodetype = Convert.ToInt32(reader["erp_configcodetype"]),
                            erp_mtrltypeid = Convert.ToInt32(reader["erp_mtrltypeid"]),
                            erp_mtrlcode = Convert.ToString(reader["erp_mtrlcode"]),
                            erp_mtrlname = Convert.ToString(reader["erp_mtrlname"]),
                            erp_mtrlmode = Convert.ToString(reader["erp_mtrlmode"]),
                            erp_mtrlunit = Convert.ToString(reader["erp_mtrlunit"]),
                            erp_mtrlengname = Convert.ToString(reader["erp_mtrlengname"]),
                            erp_mtrltype = Convert.ToString(reader["erp_mtrltype"]),
                            old_mtrlname = Convert.ToString(reader["old_mtrlname"]),
                            yw_flag = Convert.ToInt32(reader["yw_flag"]),
                            js1_flag = Convert.ToInt32(reader["js1_flag"]),
                            js2_flag = Convert.ToInt32(reader["js2_flag"]),
                            parentid = Convert.ToInt32(reader["parentid"]),
                            child_count = Convert.ToInt32(reader["child_count"])
                        };
                    }
                    else
                    {
                        rslt.ErrMsg = "无法找到床垫报价数据，请确认";
                        return;
                    }
                }

                if(request.isEdit == 1)
                {
                    if (string.IsNullOrEmpty(rslt.mattress.erp_mtrlmode))
                    {
                        rslt.mattress.erp_mtrlmode = rslt.mattress.mattress_width + "*" + rslt.mattress.mattress_length + "*" + rslt.mattress.mattress_height;
                    }

                    if (string.IsNullOrEmpty(rslt.mattress.erp_mtrlname))
                    {
                        rslt.mattress.erp_mtrlname = rslt.mattress.mattressname;
                    }


                    if (rslt.mattress.erp_configcodetype <= 0)
                    {
                        cmd.CommandText = @"SELECT TOP 1 u_configure_type.contfigtypeid
	                                    ,u_configure_type.contfigtypename
	                                    ,u_configure_type.contfigtype
	                                    ,u_configure_type.usechflag
	                                    ,u_configure_type.flag
	                                    ,u_configure_type.auditemp
	                                    ,u_configure_type.auditdate
                                    FROM u_configure_type";
                        cmd.Parameters.Clear();
                        cmd.Parameters.AddWithValue("@empid", tokendata.empid);
                        cmd.Parameters.AddWithValue("@dwname", "dw_mattress_interface_yw_edit");
                        cmd.Parameters.AddWithValue("@itemname", "erp_configcodetype");
                        using (var readerItem = cmd.ExecuteReader())
                        {
                            if (readerItem.Read())
                            {
                                rslt.mattress.erp_configcodetype = Convert.ToInt32(readerItem["contfigtypeid"]);
                            }
                        }
                    }

                    if (rslt.mattress.erp_mtrltypeid <= 0)
                    {
                        int mtrltypeid = 0;
                        if(rslt.mattress.parentid > 0)
                        {
                            cmd.CommandText = @"SELECT erp_mtrltypeid FROM u_mattress WHERE mattressid = @mattressid";
                            cmd.Parameters.Clear();
                            cmd.Parameters.AddWithValue("@mattressid", rslt.mattress.parentid);
                            using (var reader = cmd.ExecuteReader())
                            {
                                if (reader.Read())
                                {
                                    mtrltypeid = Convert.ToInt32(reader["erp_mtrltypeid"]);
                                }
                            }
                        }

                        if(mtrltypeid == 0)
                        {
                            cmd.CommandText = @"SELECT itemvalue FROM sys_user_filestring WHERE dwname = @dwname AND itemname = @itemname AND empid = @empid";
                            cmd.Parameters.Clear();
                            cmd.Parameters.AddWithValue("@empid", tokendata.empid);
                            cmd.Parameters.AddWithValue("@dwname", "dw_mattress_interface_yw_edit");
                            cmd.Parameters.AddWithValue("@itemname", "mtrltypeid");
                            using (var readerItem = cmd.ExecuteReader())
                            {
                                if (readerItem.Read())
                                {
                                    mtrltypeid = Convert.ToInt32(readerItem["itemvalue"]);
                                }
                            }
                        }

                        rslt.mattress.erp_mtrltypeid = mtrltypeid;
                    }

                    if (rslt.mattress.erp_mtrlunit == "")
                    {
                        rslt.mattress.erp_mtrlunit = "张";
                    }
                }

                var interfaceHelper = HelperBase.GetHelper<InterfaceHelper>(cmd, new HelperBase.Context() { tokendata = tokendata });

                var interfaceList = interfaceHelper.GetMattressInterfaceList(request.mattressid.Value, rslt.mattress.erp_configcodetype);
                var qdList = interfaceHelper.GetMattressInterfaceQdList(request.mattressid.Value);

                interfaceHelper.MattressInterfaceFindERPPrdPf(qdList, interfaceList);

                rslt.interfaceList = interfaceList;
                rslt.qdList = qdList;

                if(request.isEdit == 1) Trace.Write($"GetMattressInterfaceListRequest响应数据：\r\n{JsonConvert.SerializeObject(rslt)}", "Request");
            }
        }
    }
}
