using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using DirectService.Tools;
using JLHHJSvr.BLL;
using JLHHJSvr.Com;
using JLHHJSvr.Com.Model;
using JLHHJSvr.Helper;
using JLHHJSvr.LJException;
using JLHHJSvr.LJFramework.Tools;
using JLHHJSvr.Tools;
using LJLib.DAL.SQL;
using LJLib.Net.SPI.Server;
using LJLib.SQLEX;
using Newtonsoft.Json.Linq;

namespace JLHHJSvr.Excutor
{
    internal sealed class DelMtrlPfExcutor : ExcutorBase<CreatMtrldefRequest, CreatMtrldefResponse>
    {
        Dictionary<string, object> replacements = new Dictionary<string, object>();

        protected override void ExcuteInternal(CreatMtrldefRequest request, object state, CreatMtrldefResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (request.list.Count <= 0)
            {
                rslt.ErrMsg = "床垫id参数为空!";
                return;
            }

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


                var power91 = UserHelper.CheckFuncPower(cmd, tokendata.empid, 91);
                if (!power91)
                {
                    throw new LJCommonException("你没有删除清单权限");
                }

                foreach (var mattressid in request.list)
                {
                    var mattress = new u_mattress();
                    if (DbSqlHelper.SelectOne(cmd, "u_mattress", "mattressid = @mattressid", new Dictionary<string, object>() { { "mattressid", mattressid } }, mattress, "erp_mtrlid, creatmtrlqd_flag") != 1)
                    {
                        rslt.ErrMsg = "床垫报价单匹配失败";
                        return;
                    }
                    if (mattress.erp_mtrlid <= 0)
                    {
                        rslt.ErrMsg = "床垫清单还没匹配L1成品";
                        return;
                    }
                    if (mattress.creatmtrlqd_flag == 0)
                    {
                        rslt.ErrMsg = "床垫未生成erp清单，不能删除erp清单！";
                        return;
                    }

                    var l1Helper = HelperBase.GetHelper<ERPHelper>(cmd);
                    l1Helper.context = new HelperBase.Context() { tokendata = tokendata };

                    l1Helper.CheckLogin();
                    var l1Req = new JObject()
                    {
                        ["token"] = GlobalVar.ERP_TOKEN,
                        ["mtrlid"] = mattress.erp_mtrlid,
                    };

                    var l1Rslt = l1Helper.DoExecute("DelPrdPf", l1Req);
                    rslt.ErrMsg = $"{l1Rslt.GetValue("ErrMsg")}";
                }
            }
        }
    }
}
