using ICSSoft.Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ICSSoft.Common;
namespace ICSSoft.DataProject
{
    public class CreateAppVouch
    {
        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"];
        public string GET(List<AppVouch> infos)
        {
            List<AppVouch> szJson = new List<AppVouch>();
            DataTable dt = null;
            DataTable dtNew = null;
            string connS = "";
            string json = "";
            if (infos == null)
            {
                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 (AppVouch 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 a.cCode,a.cDepCode,a.cMaker,a.cMakeTime,a.cVerifier,cAuditTime,b.irowno,b.cUnitID,b.fQuantity,b.cInvCode,b.dRequirDate,b.dArriveDate,b.cexch_name,b.iOriCost 
                            from dbo.PU_AppVouch a left join  dbo.PU_AppVouchs b on a.ID=b.ID  where 1=1";
                        if (!string.IsNullOrWhiteSpace(info.PRCode))
                        {
                            sql += " and a.cCode='{0}'";
                        }
                        if (!string.IsNullOrWhiteSpace(info.MTime.ToString()))
                        {
                            sql += " and ISNULL(b.cbCloseTime,ISNULL(a.cChangAuditTime,ISNULL(a.cAuditTime, ISNULL(a.cModifyTime, a.cmaketime))))>='{2}'";
                        }
                        if (!string.IsNullOrWhiteSpace(info.User))
                        {
                            sql += "and a.CMAKER='{3}'";
                        }
                        sql = string.Format(sql, info.PRCode, ERPDB, userInfo.UserName);
                        dt = DBHelper.SQlReturnData(sql, cmd);
                        if (dtNew == null)
                            dtNew = dt;
                        else
                            dtNew.Merge(dt);
                        //List<AppVouch> szJson = JsonConvert.DeserializeObject<List<AppVouch>>(json);
                        //szJson = JsonConvert.DeserializeObject<List<AppVouch>>(json);

                    }
                    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;

        }
        /// <summary>
        /// 创建请购单
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public List<AppVouch> Create(List<AppVouch> infos)
        {

            List<AppVouch> szJson = new List<AppVouch>();
            DataTable dt = null;

            string connS = "";
            string sql = "";
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            string res = string.Empty;
            SqlConnection conn = new SqlConnection();

            SqlCommand cmd = new SqlCommand();

            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 (AppVouch info in infos)
                    {
                        if (WorkPoint != info.WorkPoint)
                        {
                            continue;
                        }
                        ICSUserInfo userInfo = new ICSUserInfo();
                        userInfo = DBHelper.GetPersonInfo(info.User, cmd);
                        string[] ss = info.WorkPoint.Split('_');
                        ERPDB = ss[1];
                        string sqlID = @"SELECT * FROM UFSystem..UA_Identity where cVouchType='PU_AppVouch' and cacc_id='" + ERPDB + @"'";
                        dt = DBHelper.SQlReturnData(sqlID, null);
                        string ID = dt.Rows[0]["iFatherId"].ToString();
                        string DID = dt.Rows[0]["iChildId"].ToString();
                        sql += @"Insert Into PU_AppVouch
                                    (ivtid,id,ccode,ddate,cdepcode,
                                    cpersoncode,cptcode,cbustype,cmaker,cverifier,
                                    iverifystateex,ireturncount,iswfcontrolled,cAuditDate,iPrintCount,
                                    cMakeTime,cAuditTime,cDefine10,cDefine1,cDefine2
                                    ) 
                                    Values 
                                    ('8171','@ID',Substring(Convert( varchar(100),GetDate(),112),1,6)+REPLICATE('0',4-len(@Num" + ID + @"))+CAST(@Num" + ID + @" AS nvarchar(10)),CONVERT(VARCHAR(10),GETDATE(),23),'@cdepcode',
                                    null,'99','普通采购','@cmaker','@cverifier',
                                    '2','0','0','@cAuditDate','0',
                                    GETDATE(),GETDATE(),'job','@cDefine1','@cDefine2'
                                    )" + Environment.NewLine;
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@ID", ID);
                        cmd.Parameters.Add("@cdepcode", info.DepCode);
                        //sql = sql.Replace("@cpersoncode", cMaker);
                        cmd.Parameters.Add("@cmaker", userInfo.UserName);
                        //sql = sql.Replace("@cverifier", cCurrentAuditor);
                        cmd.Parameters.Add("@cAuditDate", info.MTime.ToString());
                        cmd.Parameters.Add("@cDefine1", info.PRCode);
                        //sql = sql.Replace("@cDefine2", SourceCode);
                        cmd.CommandText = sql;
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            log.Error("表头失败！");
                            throw new Exception("程序异常，请联系开发人员！");
                        }
                        foreach (var detail in info.details)
                        {
                            //                        string SortSeq = ch["SortSeq"].ToString();
                            //                        string cInvCode = ch["cInvCode"].ToString();
                            //                        string cInvName = ch["cInvName"].ToString();
                            //                        string cInvStd = ch["cInvStd"].ToString();
                            //                        string cComUnitName = ch["cComUnitName"].ToString();
                            //                        string fQuantity = ch["fQuantity"].ToString();
                            //                        string dRequirDate = ch["dRequirDate"].ToString();
                            //                        string cVenName = ch["cVenName"].ToString();
                            //                        #region 判断存货编码是否存在
                            //                        sql += @"IF NOT EXISTS(
                            //	                                SELECT cInvCode 
                            //	                                FROM Inventory
                            //	                                WHERE cInvCode='@cInvCode'
                            //                                )
                            //                                BEGIN
                            //	                                RAISERROR('存货编码：@cInvCode 不存在！',16,0)
                            //                                END" + Environment.NewLine;
                            //                        #endregion
                            //                        #region PU_AppVouchs
                            //                        #region 获取ID
                            //                        string appskey = cCompanyCode + i + SortSeq;
                            //                        sql += ICSHelper.GetIDSql(cCompanyCode, "PuApp", appskey, GetID.CHILD) + Environment.NewLine;
                            //                        #endregion
                            sql += @"Insert Into PU_AppVouchs
                                                            (id,autoid,cvencode,cinvcode,fquantity,
                                                            funitprice,ipertaxrate,ftaxprice,fmoney,drequirdate,
                                                            darrivedate,iReceivedQTY,cdefine22,cdefine23,btaxcost,
                                                            iReceivedNum,cpersoncodeexec,cdepcodeexec,cexch_name,iexchrate,
                                                            ioricost,ioritaxcost,iorimoney,ioritaxprice,iorisum,
                                                            imoney,itaxprice,ivouchrowno) 
                                                            VALUES 
                                                            ('@ID', '@DID',NULL,'@cInvCode','@fQuantity',
                                                            NULL,17,NULL,NULL,'@drequirdate',
                                                            '@darrivedate','0',NULL,NULL,1,
                                                            0,NULL,NULL,N'人民币',1,
                                                            NULL,NULL,NULL,NULL,NULL,
                                                            NULL,NULL,'@ivouchrowno')" + Environment.NewLine;

                            //sql = sql.Replace("@cInvCode", cInvCode);
                            //sql = sql.Replace("@fQuantity", fQuantity);
                            //sql = sql.Replace("@drequirdate", dRequirDate);
                            //sql = sql.Replace("@darrivedate", dRequirDate);
                            //sql = sql.Replace("@ivouchrowno", SortSeq);
                            cmd.Parameters.Clear();
                            cmd.Parameters.Add("@cInvCode", detail.InvCode);
                            cmd.Parameters.Add("@fQuantity", detail.Quantity);
                            //sql = sql.Replace("@cpersoncode", cMaker);
                            cmd.Parameters.Add("@darrivedate", detail.ArriveDate);
                            //sql = sql.Replace("@cverifier", cCurrentAuditor);
                            cmd.Parameters.Add("@drequirdate", info.MTime);
                            cmd.Parameters.Add("@ivouchrowno", detail.Sequence);
                            try
                            {
                                cmd.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                log.Error("表体失败！");
                                throw new Exception("程序异常，请联系开发人员！");
                            }
                            //sql = sql.Replace("@cDefine2", SourceCode);
                        }
                        //                    #endregion
                        //                    sqls.Add(cCompanyCode + "~" + PRCode, sql);

                        //                    if (i == parent.Rows.Count - 1)//循环到最后保存到公司
                        //                    {
                        //                        Dictionary<string, string> result = ICSHelper.InsertDate(dictionary[cCompanyCode], sqls);
                        //                        foreach (var res in result)
                        //                        {
                        //                            errors.Add(res.Key, res.Value);
                        //                        }
                        //                    }
                        //                }


                    }
                    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();
                }
            }
            return szJson;

        }
        /// <summary>
        /// 审核请购单
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public string Approve(List<AppVouch> infos)
        {
            List<AppVouch> szJson = new List<AppVouch>();
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            string connS = "";
            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 (AppVouch 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 = @"UPDATE dbo.PU_AppVouch SET cVerifier ='" + userInfo.UserName + @"' ,
                            cAuditTime=CONVERT(VARCHAR(50),GETDATE(),112),cAuditDate=GETDATE() WHERE ID='" + info.ID + "'";
                        sql = string.Format(sql, ERPDB);
                        DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据！");

                    }
                    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();
                }
            }
            return res;

        }
        /// <summary>
        /// 删除请购单
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public string Delete(List<AppVouch> infos)
        {
            List<AppVouch> szJson = new List<AppVouch>();
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            string res = string.Empty;
            string connS = "";
            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 (AppVouch info in infos)
                    {
                        if (WorkPoint != info.WorkPoint)
                        {
                            continue;
                        }
                        if (info.MTime < new DateTime(2000, 01, 01))
                            throw new Exception("请输入正确的操作时间：" + info.MTime);
                        sql = @" DELETE dbo.PU_AppVouch WHERE ID={0}";
                        sql = string.Format(sql, info.ID, ERPDB);
                        DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据！");

                    }
                    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();
                }
            }
            return res;


        }
    }
}
