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

            if (request.shrinkage == null)
            {
                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.shrinkage);

                if (request.shrinkage.minvalue > request.shrinkage.maxvalue)
                {
                    rslt.ErrMsg = "裥棉收缩率错误，下限不能大于上限!";
                    return;
                }

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        if (request.shrinkage.shrinkageid <= 0)
                        {
                            request.shrinkage.shrinkageid = BllHelper.GetID(cmd, "u_shrinkage");

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

                            var fields = @"shrinkageid,minvalue,maxvalue,shrinkage,createtime,createby";
                            DbSqlHelper.Insert(cmd, "u_shrinkage", null, request.shrinkage, fields);
                        }
                        else
                        {
                            //修改
                            request.shrinkage.createtime = dtNow;
                            request.shrinkage.createby = tokendata.username;
                            var fields = @"minvalue,maxvalue,shrinkage,createtime,createby";
                            DbSqlHelper.Update(cmd, "u_shrinkage", null, request.shrinkage, "shrinkageid", fields);
                        }

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