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 AuditBedNetExcutor : ExcutorBase<AuditBedNetRequest, AuditBedNetResponse>
    {
        protected override void ExcuteInternal(AuditBedNetRequest request, object state, AuditBedNetResponse 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 power63 = UserHelper.CheckFuncPower(cmd, tokendata.empid, 63);
                    if (!power63)
                    {
                        throw new LJCommonException("你没有审核权限");
                    }
                }
                else
                {
                    var power64 = UserHelper.CheckFuncPower(cmd, tokendata.empid, 64);
                    if (!power64)
                    {
                        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 && request.type == 1)
                    {
                        throw new LJCommonException($"查找床网报价单据已审核，不能审核!({bill.bednetid})");
                    }

                    if (bill.flag == 0 && request.type == 0)
                    {
                        throw new LJCommonException($"查找床网报价单据未审核，不能撤审!({bill.bednetid})");
                    }
                }

                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        foreach (var bill in request.list)
                        {
                            bill.flag = request.type;

                            DbSqlHelper.Update(cmd, "u_bednet", null, bill, "bednetid", "flag");
                        }

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