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;

namespace JLHHJSvr.Excutor
{
    internal sealed class MattressYWAuditExcutor : ExcutorBase<MattressYWAuditRequest, MattressYWAuditResponse>
    {
        protected override void ExcuteInternal(MattressYWAuditRequest request, object state, MattressYWAuditResponse 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();

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

                var mattressHelper = HelperBase.GetHelper<MattressHelper>(cmd, new HelperBase.Context() { tokendata = tokendata });

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        foreach (var bill in request.list)
                        {
                            if (request.type == 1) mattressHelper.MattressYWAudit(bill.mattressid);
                            else mattressHelper.MattressYWCancelAudit(bill.mattressid);
                        }

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