using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using JLHHJSvr.BLL;
using JLHHJSvr.Com;
using JLHHJSvr.LJException;
using JLHHJSvr.Tools;
using LJLib.DAL.SQL;
using LJLib.Net.SPI.Server;

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

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

            //if (string.IsNullOrEmpty(request.mtrltype.typecode))
            //{
            //    rslt.ErrMsg = "请输入编号";
            //    return;
            //}

            if (string.IsNullOrEmpty(request.mtrltype.mtrltype))
            {
                rslt.ErrMsg = "请输入类别名称";
                return;
            }

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

                var dtNow = DateTime.Now;

                AutoInit.AutoInitS(cmd, request.mtrltype);

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        if (request.mtrltype.mtrltypeid < 0)
                        {
                            request.mtrltype.mtrltypeid = BllHelper.GetID(cmd, "u_mtrltype");

                            var fields = @"mtrltypeid,typecode,mtrltype,inuse,parentid,dannum1_rate,dannum2_rate,dannum3_rate,dannum4_rate";
                            DbSqlHelper.Insert(cmd, "u_mtrltype", null, request.mtrltype, fields);
                        }
                        else
                        {
                            //修改
                            var fields = @"typecode,mtrltype,inuse,parentid,dannum1_rate,dannum2_rate,dannum3_rate,dannum4_rate";
                            DbSqlHelper.Update(cmd, "u_mtrltype", null, request.mtrltype, "mtrltypeid", fields);
                        }

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