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;
using LJLib.SQLEX;

namespace JLHHJSvr.Excutor
{
    internal sealed class SaveConfigureCodeExcutor : ExcutorBase<SaveConfigureCodeRequest, SaveConfigureCodeResponse>
    {
        protected override void ExcuteInternal(SaveConfigureCodeRequest request, object state, SaveConfigureCodeResponse 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.name))
            {
                rslt.ErrMsg = "类型名称";
                return;
            }

            if(request.configure.typeid <= 0)
            {
                rslt.ErrMsg = "部件选配类型ID错误";
                return;
            }

            using (var con = GlobalVar.ConnectionString.NewSqlConnection())
            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.pzid <= 0)
                        {
                            request.configure.pzid = BllHelper.GetID(cmd, "u_configure_code");

                            var fields = @"typeid,pzid,pzcode,inputtype,name,configtype,ifcross,ifcheck,ifuse,rulestr,ifnum,decnum,maxnum,minnum,pricestr,priceratestr,ifpack,zj_special";
                            DbSqlHelper.Insert(cmd, "u_configure_code", null, request.configure, fields);
                        }
                        else
                        {
                            //修改
                            var fields = @"pzcode,inputtype,name,configtype,ifcross,ifcheck,ifuse,rulestr,ifnum,decnum,maxnum,minnum,pricestr,priceratestr,ifpack,zj_special";
                            DbSqlHelper.Update(cmd, "u_configure_code", null, request.configure, "typeid,pzid", fields);
                        }

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