using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using DirectService.Tools;
using JLHHJSvr.BLL;
using JLHHJSvr.Com;
using JLHHJSvr.Com.Model;
using JLHHJSvr.Helper;
using JLHHJSvr.LJException;
using JLHHJSvr.LJFramework.Tools;
using JLHHJSvr.Tools;
using LJLib.DAL.SQL;
using LJLib.Net.SPI.Server;
using LJLib.SQLEX;

namespace JLHHJSvr.Excutor
{
    internal sealed class SaveBedNetInterfaceExcutor : ExcutorBase<SaveBedNetInterfaceRequest, SaveBedNetInterfaceResponse>
    {
        Dictionary<string, object> replacements = new Dictionary<string, object>();

        protected override void ExcuteInternal(SaveBedNetInterfaceRequest request, object state, SaveBedNetInterfaceResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (request.bednet == null)
            {
                rslt.ErrMsg = "缺少主表信息";
                return;
            }
            if (request.interfaceList == null || !request.interfaceList.Any())
            {
                rslt.ErrMsg = "缺少产品配置明细";
                return;
            }
            if (request.qdList == null || !request.qdList.Any())
            {
                rslt.ErrMsg = "缺少产品清单明细";
                return;
            }

            using (var con = GlobalVar.ConnectionString.NewSqlConnection())
            using (var cmd = con.CreateCommand())
            {
                con.Open();

                // 初始化属性
                AutoInit.AutoInitS(cmd, request.bednet);

                foreach (var mx in request.interfaceList)
                {
                    AutoInit.AutoInitS(cmd, mx);
                }

                foreach (var mx in request.qdList)
                {
                    AutoInit.AutoInitS(cmd, mx);
                }

                var interfaceHelper = HelperBase.GetHelper<InterfaceHelper>(cmd, new HelperBase.Context() { tokendata = tokendata });

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        interfaceHelper.SaveBedNetInterface(request.bednet, request.interfaceList, request.qdList);

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