using System;
using System.Data.SqlClient;
using System.Linq;
using JLHHJSvr.BLL;
using JLHHJSvr.Com;
using JLHHJSvr.Com.Model;
using JLHHJSvr.Helper;
using JLHHJSvr.LJException;
using LJLib.DAL.SQL;
using LJLib.Net.SPI.Server;
using LJLib.SQLEX;

namespace JLHHJSvr.Excutor
{
    internal sealed class AuditBedNetExcutor : ExcutorBase<AuditBedNetRequest, AuditBedNetResponse>
    {
        protected override void ExcuteInternal(AuditBedNetRequest request, object state, AuditBedNetResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }
            if (!request.list.Any())
            {
                rslt.ErrMsg = "至少提交一条需要审核的记录";
                return;
            }

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

                var bednetHelper = HelperBase.GetHelper<BedNetHelper>(cmd, new HelperBase.Context() { tokendata = tokendata });
                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        foreach (var bill in request.list)
                        {
                            if (request.type == 1)
                            {
                                bednetHelper.BedNetAudit(bill.bednetid.Value);
                            }
                            else
                            {
                                bednetHelper.BedNetCAudit(bill.bednetid.Value);
                            }
                        }

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