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 SaveMattressExcutor : ExcutorBase<SaveMattressRequest, SaveMattressResponse>
    {
        protected override void ExcuteInternal(SaveMattressRequest request, object state, SaveMattressResponse 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);

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

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

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        helper.CalCulateFormula(request.mattress, request.mattressMx);

                        helper.SaveMattress(request.mattress, request.mattressMx);
                        
                        cmd.Transaction.Commit();

                        rslt.mattressid = request.mattress.mattressid;
                    }
                    catch (Exception e)
                    {
                        cmd.Transaction.Rollback();
                        rslt.ErrMsg = e.ToString();
                    }
                }
            }
        }
    }
}
