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

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

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

                var power76 = UserHelper.CheckFuncPower(cmd, tokendata.empid, 76);
                if (!power76)
                {
                    throw new LJCommonException("你没有删除权限");
                }

                foreach (var bill in request.list)
                {
                    if (DbSqlHelper.SelectOne(cmd, bill, "flag") != 1)
                    {
                        throw new LJCommonException($"查找床网报价单据失败!({bill.bednetid})");
                    }

                    if (bill.flag == 1)
                    {
                        throw new LJCommonException($"查找床网报价单据已审核，不能删除!({bill.bednetid})");
                    }
                }

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        foreach (var bill in request.list)
                        {
                            // 删除床网分区明细
                            cmd.CommandText = @"DELETE FROM u_bednetmx_spring WHERE bednetmxid IN (SELECT bednetmxid FROM u_bednetmx WHERE bednetid = @bednetid)";
                            cmd.Parameters.Clear();
                            cmd.Parameters.AddWithValue("@bednetid", bill.bednetid.Value);
                            cmd.ExecuteNonQuery();

                            // 删除床网明细
                            cmd.CommandText = @"DELETE FROM u_bednetmx WHERE bednetid = @bednetid";
                            cmd.Parameters.Clear();
                            cmd.Parameters.AddWithValue("@bednetid", bill.bednetid.Value);
                            cmd.ExecuteNonQuery();

                            DbSqlHelper.Delete(cmd, bill);
                        }

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