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;
using LJLib.SQLEX;

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

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

                var idStr = ListEx.getString(request.roadidList);
                cmd.CommandText = @"SELECT COUNT(pid) AS cnt FROM st_permit WHERE iftmp = 0 AND roadid 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_road WHERE roadid IN " + idStr;
                        cmd.ExecuteNonQuery();
                        cmd.Transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        cmd.Transaction?.Rollback();
                        rslt.ErrMsg = e.Message;
                    }
                }
            }
        }
    }
}
