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

            if (request.configure == null)
            {
                rslt.ErrMsg = "未提交床网分区定义";
                return;
            }

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

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        if (request.configure.contfigtypeid <= 0)
                        {
                            request.configure.contfigtypeid = BllHelper.GetID(cmd, "u_configure_type");

                            var fields = @"contfigtypeid,contfigtype,contfigtypename,usechflag,flag,auditemp,auditdate,secflag,secauditemp,secauditdate,modemp,moddate";
                            DbSqlHelper.Insert(cmd, "u_configure_type", null, request.configure, fields);
                        }
                        else
                        {
                            request.configure.moddate = dtNow;
                            request.configure.modemp = tokendata.username;

                            //修改
                            var fields = @"contfigtype,contfigtypename,usechflag,modemp,moddate";
                            DbSqlHelper.Update(cmd, "u_configure_type", null, request.configure, "contfigtypeid", fields);
                        }

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