using ICSSoft.Common;
using ICSSoft.Entity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ICSSoft.DataProject
{
    /// <summary>
    /// 采购退库
    /// </summary>
    public class PurchaseReturnBack
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
        private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];
        private static string Type = System.Configuration.ConfigurationManager.AppSettings["Type"];
        public string Get(List<ICSPurchaseReturnBack> infos)
        {

            List<ICSPurchaseReturnBack> szJson = new List<ICSPurchaseReturnBack>();
            DataTable dt = null;
            DataTable dtNew = null;
            string connS = "";
            string json = "";
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            string res = string.Empty;
            SqlConnection conn = new SqlConnection();
            SqlCommand cmd = new SqlCommand();
            string sql = string.Empty;

               List<string> result = infos.Select(t => t.WorkPoint).Distinct().ToList();


               foreach (string WorkPoint in result)
               {
                   try
                   {
                       connS = string.Format(connString, WorkPoint);
                       conn = new System.Data.SqlClient.SqlConnection(connS);
                       conn.Open();
                       SqlTransaction sqlTran = conn.BeginTransaction();
                       cmd = new SqlCommand();
                       cmd.Transaction = sqlTran;
                       cmd.Connection = conn;
                       foreach (ICSPurchaseReturnBack info in infos)
                       {
                           if (WorkPoint != info.WorkPoint)
                               continue;

                           ICSUserInfo userInfo = new ICSUserInfo();
                           userInfo = DBHelper.GetPersonInfo(info.User, cmd);
                           if (info.MTime < new DateTime(2000, 01, 01))
                               throw new Exception("请输入正确的操作时间：" + info.MTime);
                           sql = @" 	 SELECT iBillType,A.ID,A.cCode,A.cVenCode,D.cVenName,C.CDEPNAME,A.cDepCode,C.cDepName,A.cpocode,A.cMaker,A.cMakeTime,A.cverifier,A.caudittime,
                             B.Autoid,B.irowno ,B.cInvCode ,B.INUM,B.iQuantity,B.fValidInQuan,B.iPOsID
                             FROM  PU_ArrivalVouch A
                             INNER JOIN PU_ArrivalVouchs B ON A.ID=B.ID
                             INNER JOIN DEPARTMENT C ON A.CDEPCODE=C.CDEPCODE
                             INNER JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1 and  iQuantity<0 and A.cBusType='普通采购'";
                           if (!string.IsNullOrWhiteSpace(info.DNRTCode))
                           {
                               sql += " and a.cCode='{0}'";
                           }
                           if (!string.IsNullOrWhiteSpace(info.MTime.ToString()))
                           {
                               sql += " and ISNULL(a.cModifyTime,ISNULL(a.cAuditTime, ISNULL(a.cModifyTime, a.cmaketime)))>='{1}'";
                           }
                           if (!string.IsNullOrWhiteSpace(info.User))
                           {
                               sql += "and a.CMAKER='{2}'";
                           }
                           sql = string.Format(sql, info.DNRTCode, info.MTime, userInfo.UserName);
                           dt = DBHelper.SQlReturnData(sql, cmd);
                           if (dt.Rows.Count <= 0 || dt == null)
                               throw new Exception("采购退货单：" + info.DNRTCode + "，无信息！");
                           if (dtNew == null)
                               dtNew = dt;
                           else
                               dtNew.Merge(dt);

                       }
                       cmd.Transaction.Commit();

                   }
                   catch (Exception ex)
                   {
                       cmd.Transaction.Rollback();
                       log.Error(ex.Message);
                       throw new Exception(ex.Message);
                   }
                   finally
                   {
                       if (conn.State == ConnectionState.Open)
                       {
                           conn.Close();
                       }
                       conn.Dispose();
                   }
               }
            json = JsonConvert.SerializeObject(dtNew);
            return json;

        }
    }
}
