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 SaveConfigureCodeMxExcutor : ExcutorBase<SaveConfigureCodeMxRequest, SaveConfigureCodeMxResponse>
    {
        protected override void ExcuteInternal(SaveConfigureCodeMxRequest request, object state, SaveConfigureCodeMxResponse 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.pzcodemx))
            {
                rslt.ErrMsg = "请输入明细编号";
                return;
            }

            if (string.IsNullOrEmpty(request.configure.namemx))
            {
                rslt.ErrMsg = "请输入明细名称";
                return;
            }

            if (request.configure.pzid <= 0)
            {
                rslt.ErrMsg = "部件选配配置id错误";
                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.printid <= 0)
                        {
                            request.configure.printid = BllHelper.GetID(cmd, "u_configure_codemx");

                            var fields = @"pzid,printid,pzcodemx,namemx,gradestr,mtrlcode,price,ifdft,MCostRate,ProfitRate,dscrp,ifuse,ifnoch,pricerate,packqty,packvol,price_pz,grade";
                            DbSqlHelper.Insert(cmd, "u_configure_codemx", null, request.configure, fields);
                        }
                        else
                        {
                            //修改
                            var fields = @"pzcodemx,namemx,gradestr,mtrlcode,price,ifdft,MCostRate,ProfitRate,dscrp,ifuse,ifnoch,pricerate,packqty,packvol,price_pz,grade";
                            DbSqlHelper.Update(cmd, "u_configure_codemx", null, request.configure, "pzid,printid", fields);
                        }

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