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 CreatePoMain
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ConnStr"];
        private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];
        /// <summary>
        /// 查找采购订单
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public List<ICSPOMain> GET(List<ICSPOMain> infos)
        {
            List<ICSPOMain> szJson = new List<ICSPOMain>();
            DataTable dt = null;
            string json = "";
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空!");
            }
            string res = string.Empty;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
            conn.Open();
            SqlTransaction sqlTran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = conn;
            try
            {
                string sql = string.Empty;
                foreach (ICSPOMain info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @" SELECT A.CPOID,A.CVENCODE,A.CDEPCODE,A.CAPPCODE,C.CDEPNAME,D.CVENNAME,A.CMAKER,A.CMAKETIME,A.CVERIFIER,A.CAUDITTIME,
                             B.IROWNO,B.CINVCODE ,B.IQUANTITY ,B.INUM,B.IRECEIVEDQTY,B.DARRIVEDATE,A.CEXCH_NAME,B.ITAXPRICE,B.INATUNITPRICE,B.IUNITPRICE
                             FROM [{1}].DBO.PO_POMAIN A
                             INNER JOIN [{1}].DBO.PO_PODETAILS B ON A.POID=B.POID
                             INNER JOIN [{1}].DBO.DEPARTMENT C ON A.CDEPCODE=C.CDEPCODE
                             INNER JOIN [{1}].DBO.VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1";
                    if (!string.IsNullOrWhiteSpace(info.POCode))
                    {
                        sql += " and a.CPOID='{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.POCode, ERPDB,info.MTime,info.User);
                    dt = DBHelper.SQlReturnData(sql, cmd);
                    json = JsonConvert.SerializeObject(dt);
                }
                cmd.Transaction.Commit();
                return szJson;
            }
            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();
            }
        }
        /// <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 sql = "";
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空!");
            }
            string res = string.Empty;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
            conn.Open();
            SqlTransaction sqlTran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = conn;
            try
            {
                foreach (AppVouch info in infos)
                {
                    string sqlID = @"SELECT * FROM UFSystem..UA_Identity where cVouchType='PU_AppVouch'";
                    dt = DBHelper.SQlReturnData(sqlID, null);
                    string ID = dt.Rows[0]["iFatherId"].ToString();
                    string DID = dt.Rows[0]["iChildId"].ToString();
                    sql += @"Insert Into [{1}].DBO.PO_POMAIN
                                    (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", info.User);
                    //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)
                    {
                        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.Amount);
                        //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();

                }
                return szJson;
            }
            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();
            }
        }
        /// <summary>
        /// 审核采购订单
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public string Approve(List<AppVouch> infos)
        {
            List<AppVouch> szJson = new List<AppVouch>();
            DataTable dt = null;
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空!");
            }
            string res = string.Empty;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
            conn.Open();
            SqlTransaction sqlTran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = conn;
            try
            {
                string sql = string.Empty;
                foreach (AppVouch info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @"UPDATE [{0}].dbo.PO_POMAIN SET cVerifier ='" + info.User + @"' ,
                            cAuditTime=CONVERT(VARCHAR(50),GETDATE(),112),cAuditDate=GETDATE() WHERE POID='" + info.ID + "'";
                    sql = string.Format(sql, ERPDB);
                    DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据!");
                }
                cmd.Transaction.Commit();
                return res;
            }
            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();
            }
        }
        /// <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;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
            conn.Open();
            SqlTransaction sqlTran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = conn;
            try
            {
                string sql = string.Empty;
                foreach (AppVouch info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @" DELETE [{1}].dbo.PO_POMAIN WHERE POID='{0}'";
                    sql = string.Format(sql, info.ID, ERPDB);
                    DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据!");
                }
                cmd.Transaction.Commit();
                return res;
                ;
            }
            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();
            }
        }
    }
}