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

namespace JLHHJSvr.Excutor
{
    internal sealed class MattressJS2AuditExcutor : ExcutorBase<MattressJS2AuditRequest, MattressJS2AuditResponse>
    {
        protected override void ExcuteInternal(MattressJS2AuditRequest request, object state, MattressJS2AuditResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (!request.list.Any())
            {
                rslt.ErrMsg = "至少提交一条需要审核的记录";
                return;
            }

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

                if (request.type == 1)
                {
                    var power86 = UserHelper.CheckFuncPower(cmd, tokendata.empid, 86);
                    if (!power86)
                    {
                        throw new LJCommonException("你没有审核权限");
                    }
                }
                else
                {
                    var power87 = UserHelper.CheckFuncPower(cmd, tokendata.empid, 87);
                    if (!power87)
                    {
                        throw new LJCommonException("你没有撤审权限");
                    }
                }

                var mattressHelper = HelperBase.GetHelper<InterfaceHelper>(cmd, new HelperBase.Context() { tokendata = tokendata });
                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        foreach (var bill in request.list)
                        {
                            if (request.type == 1) mattressHelper.MattressJS2Audit(bill.mattressid);
                            else mattressHelper.MattressJS2CancelAudit(bill.mattressid);
                        }

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