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 AuditMattressBcpExcutor : ExcutorBase<AuditMattressBcpRequest, AuditMattressBcpResponse>
    {
        protected override void ExcuteInternal(AuditMattressBcpRequest request, object state, AuditMattressBcpResponse 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 power125 = UserHelper.CheckFuncPower(cmd, tokendata.empid, 125);
                    if (!power125)
                    {
                        throw new LJCommonException("你没有审核权限");
                    }
                } else
                {
                    var power126 = UserHelper.CheckFuncPower(cmd, tokendata.empid, 126);
                    if (!power126)
                    {
                        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 && request.type == 1)
                    {
                        throw new LJCommonException($"查找半成品报价单据已审核，不能审核!({bill.billid})");
                    }

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

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

                            DbSqlHelper.Update(cmd, "u_semi_finished_product", null, bill, "billid", "flag");
                        }

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