using System; 
using System.Data;
using System.Data.Common;
using System.Collections.Generic;
using System.Text;
using DSWeb.Areas.Account.Models.Chfee_Invoiceapplication;
using DSWeb.Areas.Account.Models.Chfee_do_detail;
using DSWeb.Areas.Account.Models.MsOpBill;
using DSWeb.Areas.Account.Models.BillChfeeDetail;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DSWeb.Areas.Account.Models.Chfee_Exrate;
using DSWeb.Areas.Account.Models.Chfee_do_Sum;
using DSWeb.Areas.CommMng.Models;
using DSWeb.EntityDA;
using HcUtility.Comm;
using DSWeb.Areas.CommMng.DAL;
using DSWeb.Areas.Account.Models.Chfee_Invoice;
using DSWeb.Areas.Account.Models.Chfee_Invoice_HangXin;
using DSWeb.Areas.Account.Models.ChfeeDetail;
using System.IO;
using DSWeb.MvcShipping.DAL.MsCodeGoodInv;
using DSWeb.MvcShipping.DAL.MsSysParamSet;

namespace DSWeb.Areas.Account.DAL.Chfee_Invoice_HangXin
{
    public partial class ChinvoiceDAL
    {

        #region 支票册列表

        static public List<ChInvoiceBook_HangXin> GetBookDataList(string strCondition, string COMPANYID, string sort = null)
        {

            var strSql = new StringBuilder();
            strSql.Append(" SELECT [GID],[NAME],[DESCRIPTION],[CREATEUSER],[CREATETIME],[MODIFIEDUSER],[MODIFIEDTIME]");
            strSql.Append(" ,[INVOICECODE],[INVOICENUMSTART],[INVOICENUMEND],[INVOICETOTAL],[DELETEUSER]");
            strSql.Append(" ,[DELETETIME],[COMPANYID],[TYPE],DEFUSER");
            strSql.Append(",(select ShowName from [user] where GID=ch_fee_invoicebooks.CREATEUSER) as CREATEUSERREF");
            strSql.Append(",(select ShowName from [user] where GID=ch_fee_invoicebooks.DELETEUSER) as DELETEUSERREF");
            strSql.Append(",(select ShowName from [user] where GID=ch_fee_invoicebooks.DEFUSER) as DEFUSERREF");
            strSql.Append(",CASE ISLOCK WHEN 1 THEN '是' ELSE '' END as ISLOCK");
            strSql.Append(",CASE ISDELETE WHEN 1 THEN '是' ELSE '' END as ISDELETE");
            strSql.Append(" FROM ch_fee_invoicebooks where COMPANYID='" + COMPANYID + "' ");

            if (!string.IsNullOrEmpty(strCondition))
            {
                strSql.Append(" and " + strCondition);
            }

            var sortstring = DatasetSort.Getsortstring(sort);
            if (!string.IsNullOrEmpty(sortstring))
            {
                strSql.Append(" order by " + sortstring);
            }
            else
            {
                strSql.Append(" order by CREATETIME DESC");

            }

            return SetBookData(strSql);
        }

        static public ChInvoiceBook_HangXin GetBookData(string condition, string companyid)
        {
            var list = GetBookDataList(condition, companyid);
            if (list.Count > 0)
                return list[0];

            return new ChInvoiceBook_HangXin();
        }

        private static List<ChInvoiceBook_HangXin> SetBookData(StringBuilder strSql)
        {
            var headList = new List<ChInvoiceBook_HangXin>();
            Database db = DatabaseFactory.CreateDatabase();
            using (IDataReader reader = db.ExecuteReader(CommandType.Text, strSql.ToString()))
            {
                while (reader.Read())
                {
                    ChInvoiceBook_HangXin data = new ChInvoiceBook_HangXin();
                    #region Set DB data to Object
                    data.GID = Convert.ToString(reader["GID"]);
                    data.NAME = Convert.ToString(reader["NAME"]);
                    data.DESCRIPTION = Convert.ToString(reader["DESCRIPTION"]);
                    data.CREATEUSER = Convert.ToString(reader["CREATEUSER"]);
                    data.CREATEUSERREF = Convert.ToString(reader["CREATEUSERREF"]);
                    if (reader["CREATETIME"] != DBNull.Value)
                        data.CREATETIME = Convert.ToString(reader["CREATETIME"]);
                    data.INVOICECODE = Convert.ToString(reader["INVOICECODE"]);
                    data.INVOICENUMSTART = Convert.ToString(reader["INVOICENUMSTART"]);
                    data.INVOICENUMEND = Convert.ToString(reader["INVOICENUMEND"]);
                    if (reader["INVOICETOTAL"] != DBNull.Value)
                        data.INVOICETOTAL = Convert.ToInt32(reader["INVOICETOTAL"]);
                    data.ISLOCK = Convert.ToString(reader["ISLOCK"]);

                    data.COMPANYID = Convert.ToString(reader["COMPANYID"]);
                    data.TYPE = Convert.ToString(reader["TYPE"]);
                    data.DELETEUSER = Convert.ToString(reader["DELETEUSER"]);
                    data.DELETEUSERREF = Convert.ToString(reader["DELETEUSERREF"]);
                    if (reader["ISDELETE"] != DBNull.Value)
                        data.ISDELETE = Convert.ToString(reader["ISDELETE"]);
                    if (reader["DELETETIME"] != DBNull.Value)
                        data.DELETETIME = Convert.ToString(reader["DELETETIME"]);
                    data.COMPANYID = Convert.ToString(reader["COMPANYID"]);
                    data.DEFUSER = Convert.ToString(reader["DEFUSER"]);
                    data.DEFUSERREF = Convert.ToString(reader["DEFUSERREF"]);


                    #endregion
                    headList.Add(data);
                }
                reader.Close();
            }
            return headList;
        }


        static public List<ChInvoiceBookdetail_HangXin> GetBookitemsDataList(string strCondition, string sort = null)
        {

            var strSql = new StringBuilder();
            strSql.Append(" SELECT [GID],[BOOKID],[INVOICENUM],[CREATEUSER],[CREATETIME]");
            strSql.Append(" ,[DELETEUSER],[DELETETIME],[MAKEOUTTIME],[MAKEOUTUSER]");
            strSql.Append(",(select ShowName from [user] where GID=ch_fee_invoiceitems.CREATEUSER) as CREATEUSERREF");
            strSql.Append(",CASE ISLOCK WHEN 1 THEN '是' ELSE '' END as ISLOCK");
            strSql.Append(",CASE ISDELETE WHEN 1 THEN '是' ELSE '' END as ISDELETE");
            strSql.Append(",CASE ISMAKEOUT WHEN 1 THEN '是' ELSE '' END as ISMAKEOUT");
            strSql.Append(" FROM ch_fee_invoiceitems where 1=1 ");

            if (!string.IsNullOrEmpty(strCondition))
            {
                strSql.Append(" and " + strCondition);
            }

            var sortstring = DatasetSort.Getsortstring(sort);
            if (!string.IsNullOrEmpty(sortstring))
            {
                strSql.Append(" order by " + sortstring);
            }
            else
            {
                strSql.Append(" order by INVOICENUM ");

            }

            return SetBookitemsData(strSql);
        }



        private static List<ChInvoiceBookdetail_HangXin> SetBookitemsData(StringBuilder strSql)
        {
            var headList = new List<ChInvoiceBookdetail_HangXin>();
            Database db = DatabaseFactory.CreateDatabase();
            using (IDataReader reader = db.ExecuteReader(CommandType.Text, strSql.ToString()))
            {
                while (reader.Read())
                {
                    ChInvoiceBookdetail_HangXin data = new ChInvoiceBookdetail_HangXin();
                    #region Set DB data to Object
                    data.GID = Convert.ToString(reader["GID"]);
                    data.BOOKID = Convert.ToString(reader["BOOKID"]);
                    data.INVOICENUM = Convert.ToString(reader["INVOICENUM"]);
                    data.CREATEUSER = Convert.ToString(reader["CREATEUSER"]);
                    data.CREATEUSERREF = Convert.ToString(reader["CREATEUSERREF"]);
                    if (reader["CREATETIME"] != DBNull.Value)
                        data.CREATETIME = Convert.ToString(reader["CREATETIME"]);
                    data.ISLOCK = Convert.ToString(reader["ISLOCK"]);
                    data.ISDELETE = Convert.ToString(reader["ISDELETE"]);
                    data.DELETEUSER = Convert.ToString(reader["DELETEUSER"]);
                    if (reader["DELETETIME"] != DBNull.Value)
                        data.DELETETIME = Convert.ToString(reader["DELETETIME"]);
                    data.ISMAKEOUT = Convert.ToString(reader["ISMAKEOUT"]);
                    if (reader["MAKEOUTTIME"] != DBNull.Value)
                        data.MAKEOUTTIME = Convert.ToString(reader["MAKEOUTTIME"]);
                    data.MAKEOUTUSER = Convert.ToString(reader["MAKEOUTUSER"]);

                    #endregion
                    headList.Add(data);
                }
                reader.Close();
            }
            return headList;
        }

        public static DBResult CreateBookitems(ChInvoiceBook_HangXin CheBook, string userid)
        {
            var result = new DBResult();

            Database db = DatabaseFactory.CreateDatabase();
            using (var conn = db.CreateConnection())
            {
                conn.Open();
                var tran = conn.BeginTransaction();

                try
                {


                    if (Convert.ToInt32(CheBook.INVOICENUMSTART) != 0 && Convert.ToInt32(CheBook.INVOICENUMEND) != 0)
                    {

                        var numlength = CheBook.INVOICENUMSTART.Length;
                        var cheno = Convert.ToInt32(CheBook.INVOICENUMSTART);
                        var maxcheno = Convert.ToInt32(CheBook.INVOICENUMEND);


                        var cmdInsert =
                            db.GetSqlStringCommand(
                                   @"insert into ch_fee_invoiceitems (GID,BOOKID,INVOICENUM,CREATEUSER,CREATETIME,ISLOCK
                                  ,ISDELETE,ISMAKEOUT) 
                                   values (@GID,@BOOKID,@INVOICENUM,@CREATEUSER,@CREATETIME,@ISLOCK
                                  ,@ISDELETE,@ISMAKEOUT) ");


                        for (int i = cheno; i <= maxcheno; i++)
                        {
                            cmdInsert.Parameters.Clear();
                            db.AddInParameter(cmdInsert, "@GID", DbType.String, Guid.NewGuid().ToString());
                            db.AddInParameter(cmdInsert, "@BOOKID", DbType.String, CheBook.GID);
                            var invoicenum=Convert.ToString(i);
                            if (invoicenum.Length<numlength) {
                              var betweenlength=numlength-invoicenum.Length;
                                for (int j=0;j<betweenlength;j++){
                                    invoicenum ="0"+invoicenum;
                                
                                }
                            
                            }
                            db.AddInParameter(cmdInsert, "@INVOICENUM", DbType.String, invoicenum);
                            db.AddInParameter(cmdInsert, "@CREATEUSER", DbType.String, userid);
                            db.AddInParameter(cmdInsert, "@CREATETIME", DbType.String, DateTime.Now);
                            db.AddInParameter(cmdInsert, "@ISLOCK", DbType.Boolean, false);
                            db.AddInParameter(cmdInsert, "@ISDELETE", DbType.Boolean, false);
                            db.AddInParameter(cmdInsert, "@ISMAKEOUT", DbType.Boolean, false);
                            db.ExecuteNonQuery(cmdInsert, tran);
                        }


                    }

                    result = new DBResult();
                    result.Success = true;
                    result.Message = "成功";

                    tran.Commit();
                }
                catch (Exception)
                {
                    tran.Rollback();

                    result.Success = false;
                    result.Message = "生成过程出现错误,请重试或联系系统管理员";

                    return result;
                }
            }

            result.Success = true;
            result.Message = "生成成功";

            return result;
        }

        public static DBResult LockBookitems(List<ChInvoiceBookdetail_HangXin> boday)
        {
            var result = new DBResult();

            Database db = DatabaseFactory.CreateDatabase();
            using (var conn = db.CreateConnection())
            {
                conn.Open();
                var tran = conn.BeginTransaction();

                try
                {
                    if (boday != null)
                    {

                        var cmdupdate = db.GetSqlStringCommand("update ch_fee_invoiceitems set ISLOCK=1 where GID=@GID");

                        foreach (var enumValue in boday)
                        {
                            cmdupdate.Parameters.Clear();
                            db.AddInParameter(cmdupdate, "@GID", DbType.String, enumValue.GID);
                            db.ExecuteNonQuery(cmdupdate, tran);
                        }
                    }

                    result = new DBResult();
                    result.Success = true;
                    result.Message = "成功";

                    tran.Commit();
                }
                catch (Exception)
                {
                    tran.Rollback();

                    result.Success = false;
                    result.Message = "锁定出现错误,请重试或联系系统管理员";

                    return result;
                }
            }

            result.Success = true;
            result.Message = "锁定成功";

            return result;
        }
        public static DBResult CancelLockBookitems(List<ChInvoiceBookdetail_HangXin> boday)
        {
            var result = new DBResult();

            Database db = DatabaseFactory.CreateDatabase();
            using (var conn = db.CreateConnection())
            {
                conn.Open();
                var tran = conn.BeginTransaction();

                try
                {
                    if (boday != null)
                    {

                        var cmdupdate = db.GetSqlStringCommand("update ch_fee_invoiceitems set ISLOCK=0 where GID=@GID");

                        foreach (var enumValue in boday)
                        {
                            cmdupdate.Parameters.Clear();
                            db.AddInParameter(cmdupdate, "@GID", DbType.String, enumValue.GID);
                            db.ExecuteNonQuery(cmdupdate, tran);
                        }
                    }

                    result = new DBResult();
                    result.Success = true;
                    result.Message = "成功";

                    tran.Commit();
                }
                catch (Exception)
                {
                    tran.Rollback();

                    result.Success = false;
                    result.Message = "锁定出现错误,请重试或联系系统管理员";

                    return result;
                }
            }

            result.Success = true;
            result.Message = "锁定成功";

            return result;
        }
        #region 判断是否已使用
        public static bool GetMakeOutCount(string BSNO)
        {
            var isfee = false;
            var strSql = new StringBuilder();
            strSql.Append("Select count(*) as count ");
            strSql.Append(" from ch_fee_invoiceitems ");
            strSql.Append(" where ISMAKEOUT=1 and BOOKID='" + BSNO + "'");
            Database db = DatabaseFactory.CreateDatabase();
            using (IDataReader reader = db.ExecuteReader(CommandType.Text, strSql.ToString()))
            {
                while (reader.Read())
                {
                    var evData = Convert.ToInt32(reader["count"]);
                    if (evData > 0) { isfee = true; };
                }
                reader.Close();
            }
            return isfee;
        }
        #endregion

        public static List<ChInvoiceNo> GetInviceNo(string strCondition)
        {
            var strSql = new StringBuilder();
            strSql.Append("select i.INVOICENUM from ch_fee_invoiceitems i left join ch_fee_invoicebooks b on (i.BOOKID=b.GID)");
            strSql.Append(" where (i.ISLOCK=0 or i.ISLOCK is null) and (i.isdelete=0 or i.isdelete is null) and i.ismakeout=0 and (b.isdelete=0 or b.isdelete is null)");
            if (!string.IsNullOrEmpty(strCondition))
            {
                strSql.Append(" and " + strCondition);
            }
            strSql.Append(" order by i.INVOICENUM ");

            Database db = DatabaseFactory.CreateDatabase();
            var evList = new List<ChInvoiceNo>();
            using (IDataReader reader = db.ExecuteReader(CommandType.Text, strSql.ToString()))
            {
                while (reader.Read())
                {
                    var evData = new ChInvoiceNo();
                    evData.INVNO = Convert.ToString(reader["INVOICENUM"]);

                    evList.Add(evData);
                }
                reader.Close();
            }

            return evList;
        }

        #endregion

        public static DBResult DeleteUpBook(string billno, string userid)
        {
            var result = new DBResult();

            Database db = DatabaseFactory.CreateDatabase();
            using (var conn = db.CreateConnection())
            {
                conn.Open();
                var tran = conn.BeginTransaction();

                try
                {


                    var cmdUpdate =
                     db.GetSqlStringCommand(
                               @"UPDATE ch_fee_invoicebooks set ISDELETE=1,DELETEUSER=@DELETEUSER,DELETETIME=@DELETETIME where GID=@BILLNO");

                    cmdUpdate.Parameters.Clear();
                    db.AddInParameter(cmdUpdate, "@BILLNO", DbType.String, billno);
                    db.AddInParameter(cmdUpdate, "@DELETEUSER", DbType.String, billno);
                    db.AddInParameter(cmdUpdate, "@DELETETIME", DbType.String, DateTime.Now);
                    db.ExecuteNonQuery(cmdUpdate, tran);



                    result = new DBResult();
                    result.Success = true;
                    result.Message = "成功";

                    tran.Commit();
                }
                catch (Exception)
                {
                    tran.Rollback();

                    result.Success = false;
                    result.Message = "保存出现错误,请重试或联系系统管理员";

                    return result;
                }
            }

            result.Success = true;
            result.Message = "保存成功";

            return result;
        }


        public static DBResult UpdateInvNoDelete(string billno, string userid)
        {
            var result = new DBResult();

            Database db = DatabaseFactory.CreateDatabase();
            using (var conn = db.CreateConnection())
            {
                conn.Open();
                var tran = conn.BeginTransaction();

                try
                {


                    var cmdUpdate =
                     db.GetSqlStringCommand(
                               @"UPDATE ch_fee_invoiceitems set ISDELETE=1,DELETEUSER=@DELETEUSER,DELETETIME=@DELETETIME where INVOICENUM=@BILLNO");

                    cmdUpdate.Parameters.Clear();
                    db.AddInParameter(cmdUpdate, "@BILLNO", DbType.String, billno);
                    db.AddInParameter(cmdUpdate, "@DELETEUSER", DbType.String, billno);
                    db.AddInParameter(cmdUpdate, "@DELETETIME", DbType.String, DateTime.Now);
                    db.ExecuteNonQuery(cmdUpdate, tran);



                    result = new DBResult();
                    result.Success = true;
                    result.Message = "成功";

                    tran.Commit();
                }
                catch (Exception)
                {
                    tran.Rollback();

                    result.Success = false;
                    result.Message = "保存出现错误,请重试或联系系统管理员";

                    return result;
                }
            }

            result.Success = true;
            result.Message = "保存成功";

            return result;
        }
        public static DBResult UpdateInvNoUse(string billno, string userid)
        {
            var result = new DBResult();

            Database db = DatabaseFactory.CreateDatabase();
            using (var conn = db.CreateConnection())
            {
                conn.Open();
                var tran = conn.BeginTransaction();

                try
                {


                    var cmdUpdate =
                     db.GetSqlStringCommand(
                               @"UPDATE ch_fee_invoiceitems set ISMAKEOUT=1,MAKEOUTUSER=@DELETEUSER,MAKEOUTTIME=@DELETETIME where INVOICENUM=@BILLNO");
                    cmdUpdate.Parameters.Clear();
                    db.AddInParameter(cmdUpdate, "@BILLNO", DbType.String, billno);
                    db.AddInParameter(cmdUpdate, "@DELETEUSER", DbType.String, billno);
                    db.AddInParameter(cmdUpdate, "@DELETETIME", DbType.String, DateTime.Now);
                    db.ExecuteNonQuery(cmdUpdate, tran);



                    result = new DBResult();
                    result.Success = true;
                    result.Message = "成功";

                    tran.Commit();
                }
                catch (Exception)
                {
                    tran.Rollback();

                    result.Success = false;
                    result.Message = "保存出现错误,请重试或联系系统管理员";

                    return result;
                }
            }

            result.Success = true;
            result.Message = "保存成功";

            return result;
        }

    
//        public static DBResult UpdateInvNoCancelUse(string billno)
//        {
//            var result = new DBResult();

//            Database db = DatabaseFactory.CreateDatabase();
//            using (var conn = db.CreateConnection())
//            {
//                conn.Open();
//                var tran = conn.BeginTransaction();

//                try
//                {


//                    var cmdUpdate =
//                     db.GetSqlStringCommand(
//                               @"UPDATE ch_fee_chequeitems set ISMAKEOUT=0,MAKEOUTUSER='',MAKEOUTTIME=null where INVOICENUM=@BILLNO
//                               ");
//                    cmdUpdate.Parameters.Clear();
//                    db.AddInParameter(cmdUpdate, "@BILLNO", DbType.String, billno);
//                    db.ExecuteNonQuery(cmdUpdate, tran);



//                    result = new DBResult();
//                    result.Success = true;
//                    result.Message = "成功";

//                    tran.Commit();
//                }
//                catch (Exception)
//                {
//                    tran.Rollback();

//                    result.Success = false;
//                    result.Message = "保存出现错误,请重试或联系系统管理员";

//                    return result;
//                }
//            }

//            result.Success = true;
//            result.Message = "保存成功";

//            return result;
//        }


    }
}