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 LJLib.Net.SPI.Server;

namespace JLHHJSvr.Excutor
{
    internal sealed class DelCarListExcutor : ExcutorBase<DelCarListRequest, DelCarListResponse>
    {
        protected override void ExcuteInternal(DelCarListRequest request, object state, DelCarListResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }
            if (request.carnumList == null || request.carnumList.Count == 0)
            {
                rslt.ErrMsg = "至少提交一条需要删除的记录";
                return;
            }

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

                var idStr = ListEx.getString(request.carnumList);
                cmd.CommandText = @"SELECT COUNT(carnum) AS cnt FROM st_permit WHERE carnum IN " + idStr;
                var cnt = Convert.ToInt32(cmd.ExecuteScalar());
                if (cnt > 0)
                {
                    rslt.ErrMsg = string.Format("有{0}个与所选车牌相关的车位信息，无法删除。", cnt);
                    return;
                }

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        cmd.CommandText = @"DELETE st_car WHERE carnum IN " + idStr;
                        cmd.ExecuteNonQuery();
                        cmd.Transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        cmd.Transaction.Rollback();
                        rslt.ErrMsg = e.ToString();
                    }
                }
            }
        }
    }
}
