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 DeleteMattressBcpExcutor : ExcutorBase<DeleteMattressBcpRequest, DeleteMattressBcpResponse>
    {
        protected override void ExcuteInternal(DeleteMattressBcpRequest request, object state, DeleteMattressBcpResponse 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 power127 = UserHelper.CheckFuncPower(cmd, tokendata.empid, 127);
                if (!power127)
                {
                    throw new LJCommonException("你没有删除权限");
                }

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

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

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        foreach (var bill in request.list)
                        {
                            // 删除半成品明细
                            cmd.CommandText = @"DELETE FROM u_semi_finished_product_mx WHERE billid = @billid";
                            cmd.Parameters.Clear();
                            cmd.Parameters.AddWithValue("@billid", bill.billid.Value);
                            cmd.ExecuteNonQuery();

                            DbSqlHelper.Delete(cmd, bill);
                        }

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