using NFine.Code;
using NFine.Domain.Entity.SystemManage;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using NFine.Repository;
using System.Text;
using System;
using System.Configuration;
using NFine.Data;
using System.IO;

namespace NFine.Application.WMS
{
    public class WatchPanelApp : RepositoryFactory<ModuleEntity>
    {
        string workpoint = ConfigurationManager.ConnectionStrings["WorkPointCode"].ConnectionString;
        private static string U9IP = ConfigurationManager.ConnectionStrings["U9connstr"].ConnectionString;
        private static string StratTimecfg = ConfigurationManager.ConnectionStrings["StratTime"].ConnectionString;
        private static string EndTimecfg = ConfigurationManager.ConnectionStrings["EndTime"].ConnectionString;
        private static string advDays = ConfigurationManager.ConnectionStrings["advDays"].ConnectionString;
        private static string workPoint = ConfigurationManager.ConnectionStrings["WorkPoint"].ConnectionString;

        string StratTime = DateTime.Parse(DateTime.Now.AddDays(-1).ToString()).ToString("yyyy-MM-dd") + ' ' + StratTimecfg;
        string EndTime = DateTime.Parse(DateTime.Now.ToString()).ToString("yyyy-MM-dd") + ' ' + EndTimecfg;

        //private string ERPName = U9IP.Substring(U9IP.IndexOf("Server=") + 7, 9) + "." + U9IP.Substring(U9IP.IndexOf("Catalog=") + 8, 7);
        //string dsaq = ConfigurationManager.ConnectionStrings["advDays"].ConnectionString;

        private static string conbegin = "Data Source=";
        private static int end = U9IP.IndexOf(";Uid=");
        private static string ERPName = "[" + U9IP.Substring(conbegin.Length, end - conbegin.Length).Replace(";Database=", "].");
        private static string ERPName1 = ERPName.Split('.')[ERPName.Split('.').Length - 1];

        string EndTime2 = "";

        //到货明细
        public DataTable GetList1(string queryJson, ref Pagination jqgridparam)
        {
            var queryParam = queryJson.ToJObject();
            OperatorModel oo = NFine.Code.OperatorProvider.Provider.GetCurrent();
            List<DbParameter> parameter = new List<DbParameter>();
            string SqlText = @"
select * from (
                SELECT *,
                  收货数量 -已检数量   待检数量,
	                CASE WHEN 收货数量 -已检数量> 0 THEN '待检验' WHEN 已检待入> 0 THEN '待入库' ELSE '完成' END 状态
	                FROM (
		                SELECT  dd.orderno 订单号,dd.itemcode 料号,dd.planqty 收货数量,inv.invname 物料名称,
		                isnull((
				                SELECT SUM (lotqty) 
				                FROM icsitemlot lot 
				                WHERE lot.TransNO=dd.ReceiptNO AND lot.TransLine=dd.ReceiptLine 
				                AND isnull(IQCStatus,'') !='' AND cc.workpoint=lot.workpoint),0) 已检数量,
		                isnull((
				                SELECT SUM (lotqty) 
				                FROM icsitemlot lot 
				                WHERE lot.TransNO=dd.ReceiptNO AND lot.TransLine=dd.ReceiptLine 
				                AND isnull(IQCStatus,'') !='' AND cc.workpoint=lot.workpoint 
				                AND NOT EXISTS (
					                SELECT 1 FROM ICSWareHouseLotInfo info 
					                WHERE info.lotno=lot.lotno AND info.workpoint=lot.workpoint)),0) 已检待入 
		                FROM ICSINVReceipt cc 
		                LEFT JOIN ICSINVReceiptDetail dd ON cc.ReceiptNO=dd.ReceiptNO AND dd.workpoint=cc.workpoint 
		                LEFT JOIN ICSINVENTORY inv ON inv.invcode=dd.itemcode AND dd.workpoint=inv.workpoint 
		                WHERE cc.mtime >=DATEADD(week, -1,getdate())
                        and cc.workpoint='" + workpoint + @"'
                ) ff  ) gg
 
                 ";

            DataTable dt = Repository().FindTablePageBySql_Other(SqlText, "WMSconnstr", parameter.ToArray(), ref jqgridparam);


            return dt;

        }

        //来料不合格明细
        public DataTable GetList2(string queryJson, ref Pagination jqgridparam)
        {
            var queryParam = queryJson.ToJObject();
            OperatorModel oo = NFine.Code.OperatorProvider.Provider.GetCurrent();
            List<DbParameter> parameter = new List<DbParameter>();
            string SqlText = @"
select  * from (
      SELECT cc.receiptNo 到货单,dd.orderno 采购订单号,dd.itemcode 料号, inv.invname 物料名称,
		  sum(lot.lotqty) 不合格数量 ,kk.CKITEMDESC 不良原因 
	 
		FROM ICSINVReceipt cc 
		LEFT JOIN ICSINVReceiptDetail dd ON cc.ReceiptNO=dd.ReceiptNO AND dd.workpoint=cc.workpoint 
		LEFT JOIN ICSINVENTORY inv ON inv.invcode=dd.itemcode AND dd.workpoint=inv.workpoint 
		left join icsitemlot lot  on lot.TransNO=dd.ReceiptNO AND lot.TransLine=dd.ReceiptLine 
				AND cc.workpoint=lot.workpoint 
		left join (select * from (select ROW_NUMBER()over(partition by LOTNO order by mtime desc,id ) rowId,lotno ,errdata ,CKITEMDESC
                          from ICSIQCErrList ck  where workpoint='" + workpoint + @"' ) as AuctionRecords 
                           where rowId=1) kk on kk.lotno=lot.lotno
		WHERE 1=1
         and cc.mtime >=DATEADD(MONTH, -1,getdate())
		and kk.errdata='不合格' 
		and cc.workpoint='" + workpoint + @"' 
group by cc.receiptNo  ,dd.orderno  ,dd.itemcode  , inv.invname ,kk.CKITEMDESC ) jj
		  ";

            DataTable dt = Repository().FindTablePageBySql_Other(SqlText, "WMSconnstr", parameter.ToArray(), ref jqgridparam);


            return dt;

        }

        public DataTable GetWIPDATA()
        {
            List<DbParameter> parameter = new List<DbParameter>();
            string SqlText = @" 
           select  distinct mo.mocode 生产订单号,mo.moseq 行号,mo.itemcode 物料编码,inv.invname 物料名称,
                mo.moplanqty 数量,sim.MUSERName 加工人员,sim.opcode 加工工序
                ,row_number() over (partition by mo.mocode  ,mo.moseq  ,  sim.MUSERName  ,sim.opcode order by sim.mtime desc,sim.id desc) rn                 
                from  icsmo mo
                left join ICSITEMLot lot on lot.transno =mo.mocode and  lot.TransLine=mo.moseq and lot.workpoint =mo.workpoint 
                left join  ICSLOTSIMULATION sim on mo.WorkPoint=sim.WorkPoint and sim.lotno=lot.lotno   
                left join ICSINVENTORY inv on inv.invcode=mo.itemcode and inv.workpoint=mo.workpoint 
                where sim.mtime>CAST(CAST(GETDATE() as date) as varchar(10)) + ' 00:00:00'
                and mo.WorkPoint='" + workpoint + @"'
             
                            ";

            DataTable dt = Repository().GetDataTableBySql_Other(SqlText, "WMSconnstr", null);
            //测试
            for (int i = 0; i < 20; i++)
            {
                DataRow newRow;
                newRow = dt.NewRow();
                newRow["生产订单号"] = "MO-0001"+i.ToString();
                newRow["行号"] = "22";
                dt.Rows.Add(newRow);

            }
            return dt;
        }

        
        //车间人员信息
        public DataTable GetWIPUser()
        {
            List<DbParameter> parameter = new List<DbParameter>();
            string SqlText = @" 
           select  distinct mo.mocode 生产订单号,mo.moseq 行号,mo.itemcode 物料编码,inv.invname 物料名称,
                mo.moplanqty 数量,sim.MUSERName 加工人员,sim.opcode 加工工序
                ,row_number() over (partition by mo.mocode  ,mo.moseq  ,  sim.MUSERName  ,sim.opcode order by sim.mtime desc,sim.id desc) rn                 
                from  icsmo mo
                left join ICSITEMLot lot on lot.transno =mo.mocode and  lot.TransLine=mo.moseq and lot.workpoint =mo.workpoint 
                left join  ICSLOTSIMULATION sim on mo.WorkPoint=sim.WorkPoint and sim.lotno=lot.lotno   
                left join ICSINVENTORY inv on inv.invcode=mo.itemcode and inv.workpoint=mo.workpoint 
                where sim.mtime>CAST(CAST(GETDATE() as date) as varchar(10)) + ' 00:00:00'
                and mo.WorkPoint='" + workpoint + @"'
             
                            ";

            DataTable dt = Repository().GetDataTableBySql_Other(SqlText, "WMSconnstr", null);
            //测试
            for (int i = 0; i < 20; i++)
            {
                DataRow newRow;
                newRow = dt.NewRow();
                newRow["生产订单号"] = "MO-0001" + i.ToString();
                newRow["行号"] = "22";
                dt.Rows.Add(newRow);

            }
            return dt;
        }
        //收料信息
        public DataTable GetWIPRCV()
        {
            List<DbParameter> parameter = new List<DbParameter>();
            string SqlText = @" 
            select B.CreatedOn 到货时间,A.DescFlexField_PrivateDescSeg1 送货单号,A.DocNO 收货单号,B.DocLineNo 收货单行号
			,ISNULL(B.QCBillNo,'') AS 质检单号,CASE WHEN A.Status='0' THEN '开立' WHEN A.Status='2' THEN '检验完成' WHEN A.Status='3' THEN '核准中' ELSE '业务关闭' END AS 状态
            ,A.Supplier_ShortName 供应商名称,A.DescFlexField_PubDescSeg13 紧急程度,B.ItemInfo_ItemCode 料号
			,B.ItemInfo_ItemName 品名,C.INVSTD 规格型号,C.INVUOM 单位,B.ArriveQtyTU 到货数量,B.QualifiedQtyTU 合格数量
			,case when B.Status='5' then B.QualifiedQtyTU When B.Status='5' AND ISNULL(B.QCBillNo,'')='' then B.QualifiedQtyTU ELSE 0 end as U9已上架数量
			,ISNULL(F.QTY,0) AS WMS已上架数量,B.ArriveQtyTU-ISNULL(F.QTY,0) AS WMS未上架数量,E.Name 库管员 
			from 
			{0}.DBO.PM_Receivement A
			LEFT JOIN (SELECT a.ID,b.CreatedOn,b.DocLineNo,b.QCBillNo,b.ItemInfo_ItemCode,b.ItemInfo_ItemName,b.ItemInfo_ItemID,b.WhMan
			,sum(b.ArriveQtyTU) ArriveQtyTU,SUM(b.QualifiedQtyTU) QualifiedQtyTU,b.Status
			from {0}.DBO.PM_Receivement a LEFT JOIN {0}.DBO.PM_RcvLine b on b.Receivement=a.ID 
			where (SplitFlag=0 OR SplitFlag=2)
			GROUP BY a.ID,b.CreatedOn,b.DocLineNo,b.QCBillNo,b.ItemInfo_ItemCode,b.ItemInfo_ItemName,b.ItemInfo_ItemID,b.WhMan,b.Status ) B
			ON B.ID=A.ID
			LEFT JOIN ICSINVENTORY C on C.ID=B.ItemInfo_ItemID
            LEFT JOIN {0}.DBO.CBO_Operators_trl E on E.ID=B.WhMan
			LEFT JOIN (SELECT ASN.STNO,ASN.ITEMCODE,SUM(ISNULL(WHLOT.LotQty,0)) AS QTY FROM ICSASNDETAIL ASN
			LEFT JOIN ICSITEMLot LOT ON LOT.LotNO=ASN.LOTNO AND LOT.WorkPoint=ASN.WorkPoint
			LEFT JOIN ICSWareHouseLotInfo WHLOT ON WHLOT.LotNO=LOT.LotNO AND WHLOT.WorkPoint=LOT.WorkPoint
			GROUP BY ASN.STNO,ASN.ITEMCODE) F ON F.STNO=A.DescFlexField_PrivateDescSeg1 AND F.ITEMCODE=B.ItemInfo_ItemCode
			where 1=1 and B.CreatedOn>CAST(CAST(GETDATE()  as date) as varchar(10)) + ' 00:00:00'
			order by B.CreatedOn";

            SqlText = string.Format(SqlText, ERPName, workpoint);
            DataTable dt = Repository().GetDataTableBySql_Other(SqlText, "WMSconnstr", null);
            return dt;
        }
        //收料图表
        public DataTable GetWIPRCVChart()
        {
            List<DbParameter> parameter = new List<DbParameter>();
            string SqlText = @" 
           SELECT top 1 (SELECT COUNT(ID) FROM {0}.DBO.PM_RcvLine 
where (SplitFlag=0 OR SplitFlag=2) 
and CreatedOn>CAST(CAST(GETDATE()  as date) as varchar(10)) + ' 00:00:00' and status<>'5') as U9dk,
            (SELECT COUNT(ID) FROM {0}.DBO.PM_RcvLine 
where (SplitFlag=0 OR SplitFlag=2) 
and CreatedOn>CAST(CAST(GETDATE()  as date) as varchar(10)) + ' 00:00:00' and status='5') as U9gb
            from {0}.DBO.PM_RcvLine";

            SqlText = string.Format(SqlText, ERPName, workpoint);
            DataTable dt = Repository().GetDataTableBySql_Other(SqlText, "WMSconnstr", null);
            return dt;
        }

        //发料信息
        public DataTable GetMaterialPick() 
        {
            List<DbParameter> parameter = new List<DbParameter>();
            string SqlText = $@"  SELECT
	                                   a.ApplyCode,
	                                   A.Sequence,
	                                   --a.SAPSequence,
	                                   a.InvCode,
	                                   c.LotNo,
	                                   c.Quantity,
	                                   e.StartLocation,
	                                   e.EndLocation
-- 	                                   e.TaskCode 
                                   FROM
	                                   ICSMOApply a
-- 	                                   INNER JOIN ICSContainerReceiptsNumber b ON a.ApplyCode= b.TransCode 
	                                   INNER JOIN ICSWareHouseLotInfoLog c ON a.ApplyCode= c.TransCode  
                                       AND
	                                   c.TransType= '15' 
	                                   AND a.Sequence= c.TransSequence 
	                                   INNER JOIN ( SELECT DISTINCT e.StartLocation,e.EndLocation FROM                                     
                                       ICSForkLiftTaskLog e WHERE e.EndLocation is not null AND e.EndLocation!=''AND (e.EATTRIBUTE1 IS NULL OR e.EATTRIBUTE1!='己回库') ) e ON  c.FromLocationCode= e.StartLocation
	                                  
                                   WHERE
                                       a.WorkPoint in({workPoint})";

            //if (!string.IsNullOrWhiteSpace(StratTime))
            //{
            //    SqlText += " and a.CreatedOn>'" + StratTime + "'";
            //}
            //if (!string.IsNullOrWhiteSpace(EndTime))
            //{
            //    SqlText += " and a.CreatedOn<'" + EndTime + "'";
            //}
            //if (!string.IsNullOrWhiteSpace(advDays))
            //{
            //    SqlText += @" and a.MTIME>CAST(CAST(DATEADD(day, -" + advDays + @", GETDATE())  as date) as varchar(10)) + ' 00:00:00'
            //                  and a.MTIME<=CAST(CAST(GETDATE()  as date) as varchar(10)) + ' 23:59:59'";
            //}
            //if (string.IsNullOrWhiteSpace(StratTime) && string.IsNullOrWhiteSpace(EndTime) && string.IsNullOrWhiteSpace(advDays))
            //{
            //    SqlText += @" and a.MTIME>CAST(CAST(GETDATE()  as date) as varchar(10)) + ' 00:00:00'
            //                  and a.MTIME<=CAST(CAST(GETDATE()  as date) as varchar(10)) + ' 23:59:59'";
            //}
            SqlText += @"order by a.MTIME ";

            //SqlText = string.Format(SqlText, ERPName, workpoint);
            DataTable dt = Repository().GetDataTableBySql_Other(SqlText, "WMSconnstr", null);
            return dt;
        }
        //发料图表
        public DataTable GetMaterialPickChart()
        {
            List<DbParameter> parameter = new List<DbParameter>();
            string SqlText = @"  SELECT top 1 
            (SELECT COUNT(*) from {0}.DBO.MO_MO a
            where  a.CreatedOn>CAST(CAST(DATEADD(day, -{2}, GETDATE())  as date) as varchar(10)) + ' 00:00:00')-
            (SELECT COUNT(*) from {0}.DBO.MO_MO a
            LEFT JOIN (SELECT DISTINCT COUNT(VouchRow) 子件项数,MOCode from ICSMaterialPick GROUP BY MOCode) b on a.DocNo=b.MOCode
            LEFT JOIN (SELECT DISTINCT COUNT(VouchRow) 完成项数,MOCode from ICSMaterialPick where Quantity<=HasQuantity GROUP BY MOCode) c on a.DocNo=c.MOCode
            where  a.CreatedOn>CAST(CAST(DATEADD(day, -{2}, GETDATE())  as date) as varchar(10)) + ' 00:00:00' and b.子件项数=c.完成项数)
            as 未完成工单,
        
            (SELECT COUNT(*) from {0}.DBO.MO_MO a
            LEFT JOIN (SELECT DISTINCT COUNT(VouchRow) 子件项数,MOCode from ICSMaterialPick GROUP BY MOCode) b on a.DocNo=b.MOCode
            LEFT JOIN (SELECT DISTINCT COUNT(VouchRow) 完成项数,MOCode from ICSMaterialPick where Quantity<=HasQuantity GROUP BY MOCode) c on a.DocNo=c.MOCode
            where  a.CreatedOn>CAST(CAST(DATEADD(day, -{2}, GETDATE())  as date) as varchar(10)) + ' 00:00:00' and b.子件项数=c.完成项数) as 领料完成工单 
            from {0}.DBO.MO_MO";

            SqlText = string.Format(SqlText, ERPName, workpoint, advDays);
            DataTable dt = Repository().GetDataTableBySql_Other(SqlText, "WMSconnstr", null);
            return dt;
        }

        //发货信息
        public DataTable GetSo()
        {
            List<DbParameter> parameter = new List<DbParameter>();
            string SqlText = @" 
            SELECT DISTINCT a1.CreatedOn ,A1.BusinessDate 日期,A1.DocNo 销售出库单,A2.DocLineNo 行号,A5.Code 物料编码,A6.NameCombineName 存货名称,
			A5.SPECS 规格型号,A10.Name 单位,ISNULL(A2.ShipQtyInvAmount, 0) 应发数量,ISNULL(so.HasQuantity, 0) 已发数量,ISNULL(A2.ShipQtyInvAmount,0)-isnull(so.HasQuantity, 0) WMS未发数量
            from {0}.DBO.SM_Ship A1
            LEFT JOIN {0}.dbo.SM_ShipLine A2 ON A2.Ship=A1.ID
            LEFT JOIN {0}.dbo.SM_ShipLine_Trl A3 ON A2.ID=A3.ID AND A3.SysMLFlag='zh-CN'
            LEFT JOIN {0}.dbo.CBO_ItemMaster A5 ON A2.ItemInfo_ItemID=A5.ID
            LEFT JOIN {0}.dbo.CBO_ItemMaster_Trl A6 ON A6.ID = A5.ID AND A6.SysMLFlag='zh-CN'
            LEFT JOIN {0}.dbo.CBO_Wh A7 ON A2.WH=A7.ID
            LEFT JOIN {0}.dbo.CBO_Wh_Trl A8 ON A8.ID = A7.ID AND A8.SysMLFlag='zh-CN'
            LEFT JOIN {0}.dbo.Base_UOM A9 ON A2.PriceUOM=A9.ID
            LEFT JOIN {0}.dbo.Base_UOM_Trl A10 ON A10.ID = A9.ID AND A10.SysMLFlag='zh-CN'
            LEFT JOIN ICSSODispatch so on A1.DocNo=so.DispatchCode AND A2.DocLineNo=so.DispatchRow
            where 1=1 AND ISNULL(A2.WH,'')!=''";

            if (!string.IsNullOrWhiteSpace(StratTime))
            {
                SqlText += " and a1.CreatedOn>'" + StratTime + "'";
            }
            if (!string.IsNullOrWhiteSpace(EndTime))
            {
                SqlText += " and a1.CreatedOn<'" + EndTime + "'";
            }
            if (string.IsNullOrWhiteSpace(StratTime) && string.IsNullOrWhiteSpace(EndTime) && !string.IsNullOrWhiteSpace(advDays))
            {
                SqlText += " and a1.CreatedOn>CAST(CAST(DATEADD(day, -" + advDays + ", GETDATE())  as date) as varchar(10)) + ' 00:00:00'";
            }
            if (string.IsNullOrWhiteSpace(StratTime) && string.IsNullOrWhiteSpace(EndTime) && string.IsNullOrWhiteSpace(advDays))
            {
                SqlText += " and a1.CreatedOn>CAST(CAST(GETDATE()  as date) as varchar(10)) + ' 00:00:00'";
            }
            SqlText += @"order by a1.CreatedOn ";

            SqlText = string.Format(SqlText, ERPName, workpoint);
            DataTable dt = Repository().GetDataTableBySql_Other(SqlText, "WMSconnstr", null);
            return dt;
        }

        //工单欠料信息
        public DataTable GetOwe()
        {
            List<DbParameter> parameter = new List<DbParameter>();
            string SqlText = @"  SELECT a.DocNo U9工单,a.startDate 开工日期,BItem.Code 母件料号,BItem.Name 母件名称,BItem.SPECS 母件规格,A.ProductQty 工单数量,
            UOM.Name 母件单位,cBItem.Code 子件料号,cBItem.Name 子件名称,cBItem.SPECS 子件规格,--b.id,c.id,d.MO,
            b.ActualReqQty,c.IssuedQty,d.qty,
            ISNULL(b.ActualReqQty, 0)-ISNULL(c.IssuedQty, 0)+ISNULL(d.qty, 0) as 子件欠料数量
            from {0}.DBO.MO_MO a
            LEFT JOIN {0}.DBO.CBO_ItemMaster BItem on BItem.ID=a.ItemMaster
            LEFT JOIN {0}.DBO.Base_UOM_Trl UOM ON  UOM.ID = BItem.InventoryUOM
            LEFT JOIN {0}.DBO.MO_MoPickList b on a.ID=B.MO
            LEFT JOIN {0}.DBO.CBO_ItemMaster cBItem on b.ItemMaster=cBItem.ID
            LEFT JOIN {0}.DBO.MO_IssueDocLine c on a.ID=c.MO and b.ItemMaster=c.Item
            LEFT JOIN (SELECT b.MO,b.IssuedQty as qty,b.Item from {0}.DBO.mo_IssueDoc a 
            INNER JOIN {0}.DBO.MO_IssueDocLine b on a.ID=b.IssueDoc 
            INNER JOIN {0}.DBO.MO_IssueDocLine c on b.SourceIssueDocLine=c.ID 
            where a.IssueType='1' ) d on a.ID=d.MO and b.ItemMaster=d.Item
			where a.DocState<>3 ";

            //if (!string.IsNullOrWhiteSpace(StratTime))
            //{
            //    SqlText += " and a.CreatedOn>'" + StratTime + "'";
            //}
            //if (!string.IsNullOrWhiteSpace(EndTime))
            //{
            //    SqlText += " and a.CreatedOn<'" + EndTime + "'";
            //}
            if (!string.IsNullOrWhiteSpace(advDays))
            {
                SqlText += @" and a.startDate>CAST(CAST(DATEADD(day, -" + advDays + @", GETDATE())  as date) as varchar(10)) + ' 00:00:00'
                              and a.startDate<=CAST(CAST(GETDATE()  as date) as varchar(10)) + ' 23:59:59'";
            }
            if (string.IsNullOrWhiteSpace(StratTime) && string.IsNullOrWhiteSpace(EndTime) && string.IsNullOrWhiteSpace(advDays))
            {
                SqlText += @" and a.startDate>CAST(CAST(GETDATE()  as date) as varchar(10)) + ' 00:00:00'
                              and a.startDate<=CAST(CAST(GETDATE()  as date) as varchar(10)) + ' 23:59:59'";
            }
            SqlText += @"order by a.startDate ";

            SqlText = string.Format(SqlText, ERPName, workpoint);
            DataTable dt = Repository().GetDataTableBySql_Other(SqlText, "WMSconnstr", null);
            return dt;
        }
        
        public static void WriteLogFile(string input, string txtName)
        {
            try
            {
                string logAdress = "C:\\看板日志" + "\\";
                if (!System.IO.Directory.Exists(logAdress))
                {
                    System.IO.Directory.CreateDirectory(logAdress);//不存在就创建目录   
                }

                string adress = logAdress + txtName;
                if (!System.IO.Directory.Exists(adress))
                {
                    System.IO.Directory.CreateDirectory(adress);//不存在就创建目录   
                }

                // string logAdress = ConfigurationManager.AppSettings["logAdress"].ToString();
                /**/
                ///指定日志文件的目录
                string fname = adress + "\\" + "log" + DateTime.Now.ToString("yy-MM-dd") + ".txt";
                /**/
                ///定义文件信息对象

                FileInfo finfo = new FileInfo(fname);

                if (!finfo.Exists)
                {
                    FileStream fs;
                    fs = File.Create(fname);
                    fs.Close();
                    finfo = new FileInfo(fname);
                }

                /**/
                ///判断文件是否存在以及是否大于2K
                if (finfo.Length > 1024 * 1024 * 10)
                {
                    /**/
                    ///文件超过10MB则重命名
                    File.Move(logAdress + "\\Log\\" + txtName + ".txt", Directory.GetCurrentDirectory() + DateTime.Now.TimeOfDay + "\\Log\\" + txtName + ".txt");
                    /**/
                    ///删除该文件
                    //finfo.Delete();
                }
                //finfo.AppendText();
                /**/
                ///创建只写文件流

                using (FileStream fs = finfo.OpenWrite())
                {
                    /**/
                    ///根据上面创建的文件流创建写数据流
                    StreamWriter w = new StreamWriter(fs);

                    /**/
                    ///设置写数据流的起始位置为文件流的末尾

                    ///设置写数据流的起始位置为文件流的末尾
                    w.BaseStream.Seek(0, SeekOrigin.End);

                    w.WriteLine("*****************Start*****************");
                    w.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    /**/
                    ///写入当前系统时间并换行

                    /**/
                    ///写入日志内容并换行
                    w.WriteLine(input);

                    /**/
                    ///写入------------------------------------“并换行
                    w.WriteLine("------------------END------------------------");

                    /**/
                    ///清空缓冲区内容,并把缓冲区内容写入基础流
                    w.Flush();

                    /**/
                    ///关闭写数据流
                    w.Close();
                }
            }
            catch (Exception ex)
            { }

        }
    }
}