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 SaveMattressFormulaExcutor : ExcutorBase<SaveMattressFormulaRequest, SaveMattressFormulaResponse>
    {
        protected override void ExcuteInternal(SaveMattressFormulaRequest request, object state, SaveMattressFormulaResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }

            if (request.mattress == null)
            {
                rslt.ErrMsg = "未提交床垫类别定义信息";
                return;
            }

            if (string.IsNullOrEmpty(request.mattress.sortcode))
            {
                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.mattress);

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        if (request.mattress.formulaid <= 0)
                        {
                            request.mattress.formulaid = BllHelper.GetID(cmd, "u_mattress_formula");

                            request.mattress.createtime = dtNow;
                            request.mattress.createby = tokendata.username;

                            var fields = @"formulaid,formulakind,formulatype,sortcode,if_mtrl,formula,usetype,if_packtype0,if_packtype1,if_packtype2,default_mtrlid,
                                        createtime,createby,useformula,gydscrp,mtrltype";
                            DbSqlHelper.Insert(cmd, "u_mattress_formula", null, request.mattress, fields);
                        }
                        else
                        {
                            //修改
                            var fields = @"formulakind,formulatype,sortcode,if_mtrl,formula,usetype,if_packtype0,if_packtype1,if_packtype2,default_mtrlid,
                                        useformula,gydscrp,mtrltype";
                            DbSqlHelper.Update(cmd, "u_mattress_formula", null, request.mattress, "formulaid", fields);
                        }

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