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

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

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

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        foreach (var mtrl in request.list)
                        {
                            mtrl.isuse = request.type; 
                            DbSqlHelper.Update(cmd, "u_mtrl_price", null, mtrl, "mtrlid", "isuse");
                        }

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