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 SaveMattressBcpExcutor : ExcutorBase<SaveMattressBcpRequest, SaveMattressBcpResponse>
    {
        protected override void ExcuteInternal(SaveMattressBcpRequest request, object state, SaveMattressBcpResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }
            if (request.mattress == null)
            {
                rslt.ErrMsg = "缺少主表信息";
                return;
            }
            if(request.mattress.mxlist == null || !request.mattress.mxlist.Any())
            {
                rslt.ErrMsg = "缺少半成品明细";
                return;
            }

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

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

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        var helper = HelperBase.GetHelper<MattressHelper>(cmd, new HelperBase.Context() { tokendata = tokendata });

                        helper.SaveMattressBcp(request.mattress);

                        cmd.Transaction.Commit();

                        rslt.mattress = new u_semi_finished_product() { billid = request.mattress.billid, billcode = request.mattress.billcode };
                    }
                    catch (Exception e)
                    {
                        cmd.Transaction.Rollback();
                        rslt.ErrMsg = e.ToString();
                    }
                }
            }
        }
    }
}
