using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
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;

namespace JLHHJSvr.Excutor
{
    internal sealed class GetComputeMattressExcutor : ExcutorBase<GetComputeMattressRequest, GetComputeMattressResponse>
    {
        protected override void ExcuteInternal(GetComputeMattressRequest request, object state, GetComputeMattressResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }
            if (request.mattress == null)
            {
                rslt.ErrMsg = "缺少主表信息";
                return;
            }

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

                // 初始化属性
                AutoInit.AutoInitS(cmd, request.mattress);

                if (request.mattress.copy_id != null && request.mattress.copy_id > 0)
                {
                    request.mattress.mattressid = 0;
                    request.mattress.mattresscode = string.Empty;

                    foreach (var mx in request.mattressMx)
                    {
                        mx.mattressid = 0;
                        mx.mattressmxid = 0;
                    }
                }

                foreach (var mx in request.mattressMx)
                {
                    AutoInit.AutoInitS(cmd, mx);
                }

                using (cmd.Transaction = con.BeginTransaction())
                {

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

                    try
                    {
                        helper.CalCulateFormula(request.mattress, request.mattressMx,false);
                    }
                    catch (Exception e)
                    {
                        rslt.message = e.Message;
                    }
                    rslt.replace = helper.Replacements;

                    rslt.formulas = helper.FormulaReplacements;

                    //rslt.mattress = request.mattress;
                }
            }
        }
    }
}
