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

            if (request.price == null)
            {
                rslt.ErrMsg = "未提交多维度定价资料";
                return;
            }

            if (request.price.coefficient == 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.price);

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        if (request.price.multipriceid <= 0)
                        {
                            request.price.multipriceid = BllHelper.GetID(cmd, "u_multiprice");

                            var fields = @"multipriceid,coefficient,price_formula,dscrp,inuse";
                            DbSqlHelper.Insert(cmd, "u_multiprice", null, request.price, fields);
                        }
                        else
                        {
                            //修改
                            var fields = @"coefficient,price_formula,dscrp,inuse";
                            DbSqlHelper.Update(cmd, "u_multiprice", null, request.price, "multipriceid", fields);
                        }

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