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;
using LJLib.SQLEX;
using static JLHHJSvr.Helper.CacheHelper;

namespace JLHHJSvr.Excutor
{
    internal sealed class SaveMtrlDefExcutor : ExcutorBase<SaveMtrlDefRequest, SaveMtrlDefResponse>
    {
        protected override void ExcuteInternal(SaveMtrlDefRequest request, object state, SaveMtrlDefResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }

            if (request.mtrl == null)
            {
                rslt.ErrMsg = "未提交物料类别定义";
                return;
            }

            if (string.IsNullOrEmpty(request.mtrl.name))
            {
                rslt.ErrMsg = "请输入物料名称";
                return;
            }

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

                var dtNow = DateTime.Now;

                AutoInit.AutoInitS(cmd, request.mtrl);

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

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        helper.SaveMtrlDef(request.mtrl);
                        cmd.Transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        cmd.Transaction?.Rollback();
                        rslt.ErrMsg = e.Message;
                    }
                }
            }
        }
    }
}
