using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using DirectService.Tools;
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;
using NPOI.SS.Formula;

namespace JLHHJSvr.Excutor
{
    internal sealed class SaveErpMtrlPriceListExcutor : ExcutorBase<SaveErpMtrlPriceListRequest, SaveErpMtrlPriceListResponse>
    {
        protected override void ExcuteInternal(SaveErpMtrlPriceListRequest request, object state, SaveErpMtrlPriceListResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            using (var con = GlobalVar.ConnectionString.NewSqlConnection())
            using (var cmd = con.CreateCommand())
            {
                con.Open();

                var mtrlids = request.mtrldefList.Where(t => t.mtrlid > 0).Select(t => t.mtrlid).ToList();
                var existids = new List<int>();

                if (mtrlids.Count > 0) 
                {
                    cmd.CommandText = $@"SELECT mtrlid FROM u_mtrldef WHERE mtrlid IN {ListEx.getString(mtrlids)}";
                    cmd.Parameters.Clear();
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            existids.Add(Convert.ToInt32(reader["mtrlid"]));
                        }
                    }

                    if(existids.Count > 0 && existids.Count != mtrlids.Count)
                    {
                        var missingIds = mtrlids.Except(existids).ToList();
                        throw new LJCommonException($"以下物料不存在,请检查!{ListEx.getString(missingIds)}");
                    }
                }


                var baseHelper = HelperBase.GetHelper<BasicInfoHelper>(cmd,new HelperBase.Context() { tokendata = tokendata});
                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        foreach(var mtrl in request.mtrldefList)
                        {
                            baseHelper.SaveErpMtrlPrice(mtrl);
                        }
                        cmd.Transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        rslt.ErrMsg = e.Message;
                        cmd.Transaction?.Rollback();
                    }
                }
            }
        }
    }
}
