using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.ServiceModel;
using System.Text;
using ICS.WCF.Base;
using UFSoft.UBF.Exceptions1;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using UFSoft.UBF.Exceptions;

namespace UFIDA.ISV.BFTransFromDelete
{
    public class CustBFTransFormDelete
    {
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];

        public static void CustDeleteTransFrom(string DocCode)
        {
            long DocID = 0;
            string EntityType = "";
            #region 服务调用框架结构
            //实例化代理类 
            UFIDAU9ISVTransferFormISVICommonDeleteTransferFormSRVClient client = new UFIDAU9ISVTransferFormISVICommonDeleteTransferFormSRVClient();
            //服务返回结果
            //UFIDAU9PMPOPurchaseOrderData[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
            //上下文信息
            object context;
            bool IsSuccess = false;
            //传入 参数
            //UFIDAU9PMDTOsOBAPurchaseOrderDTOData[] pOList;
            www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] docArray = new www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] { };
            List<www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData> docList = new List<www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();
            try
            {
                DataTable dt = GetData(DocCode);
                if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()) || !string.IsNullOrEmpty(dt.Rows[0][1].ToString()))
                {
                    DocID = long.Parse(dt.Rows[0][0].ToString());
                    EntityType = dt.Rows[0][1].ToString();
                }
                else
                {
                    throw new Exception("需要删除的单据号不正确!");
                }

                www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData docinfo = new www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                //给传入参数赋值
                docinfo.m_iD = DocID;
                docList.Add(docinfo);
                docArray = docList.ToArray();
                //给上下文信息赋值
                context = CreateContextObj();
                //pOList = SetPoDtos(U9Info, poInfoList);
                //服务调用
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                returnMsg = client.Do(context, docArray);
            }
            catch (Exception ex)
            {
                StringBuilder str = new StringBuilder();
                str.AppendLine("删除形态转换单");
                //str.AppendLine("单号:" + DocCode);
                str.AppendLine("错误:" + GetExceptionMessage(ex));
                str.AppendLine("结果:" + "False");
                Appconfig.WriteLogFile(str.ToString(), "删除形态转换单");
            }
            #endregion
        }

        public static void CustDeleteTransFrom(string DocCode, string OrgID)
        {
            long DocID = 0;
            string EntityType = "";
            #region 服务调用框架结构
            //实例化代理类 
            UFIDAU9ISVTransferFormISVICommonDeleteTransferFormSRVClient client = new UFIDAU9ISVTransferFormISVICommonDeleteTransferFormSRVClient();
            //服务返回结果
            //UFIDAU9PMPOPurchaseOrderData[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
            //上下文信息
            object context;
            bool IsSuccess = false;
            //传入 参数
            //UFIDAU9PMDTOsOBAPurchaseOrderDTOData[] pOList;
            www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] docArray = new www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] { };
            List<www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData> docList = new List<www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();
            try
            {
                DataTable dt = GetData(DocCode, OrgID);
                if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()) || !string.IsNullOrEmpty(dt.Rows[0][1].ToString()))
                {
                    DocID = long.Parse(dt.Rows[0][0].ToString());
                    EntityType = dt.Rows[0][1].ToString();
                }
                else
                {
                    throw new Exception("需要删除的单据号不正确!");
                }

                www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData docinfo = new www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                //给传入参数赋值
                docinfo.m_iD = DocID;
                docList.Add(docinfo);
                docArray = docList.ToArray();
                //给上下文信息赋值
                context = CreateContextObj(OrgID);
                //pOList = SetPoDtos(U9Info, poInfoList);
                //服务调用
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                returnMsg = client.Do(context, docArray);
            }
            catch (Exception ex)
            {
                StringBuilder str = new StringBuilder();
                str.AppendLine("删除形态转换单");
                //str.AppendLine("单号:" + DocCode);
                str.AppendLine("错误:" + GetExceptionMessage(ex));
                str.AppendLine("结果:" + "False");
                Appconfig.WriteLogFile(str.ToString(), "删除形态转换单");
            }
            #endregion
        }

        private static DataTable GetData(string DocCode)
        {
            string sql = @"select ID,DocNO from InvDoc_TransferForm
                           where DocNO='" + DocCode + "' ";
            return DBhlper.Query(sql, connString);
        }

        private static DataTable GetData(string DocCode, string OrgID)
        {
            string sql = @"select ID,DocNO from InvDoc_TransferForm
                           where DocNO='" + DocCode + "' AND Org='" + OrgID + "' ";
            return DBhlper.Query(sql, connString);
        }

        #region 提取异常信息
        /// <summary>
        /// 提取异常信息
        /// </summary>
        /// <param name="ex"></param>
        private static string GetExceptionMessage(Exception ex)
        {
            string faultMessage = "未知错误，请查看ERP日志！";

            System.TimeoutException timeoutEx = ex as System.TimeoutException;
            if (timeoutEx != null)
            {
                faultMessage = "访问服务超时，请修改配置信息！";
            }
            else
            {
                FaultException<ServiceException> faultEx = ex as FaultException<ServiceException>;
                if (faultEx == null)
                {
                    faultMessage = ex.Message;
                }
                else
                {
                    ServiceException serviceEx = faultEx.Detail;
                    if (serviceEx != null && !string.IsNullOrEmpty(serviceEx.Message)
                        && !serviceEx.Message.Equals("fault", StringComparison.OrdinalIgnoreCase))
                    {
                        // 错误信息在faultEx.Message中，请提取，
                        // 格式为"Fault:料品不能为空，请录入\n 在....."
                        int startIndex = serviceEx.Message.IndexOf(":");
                        int endIndex = serviceEx.Message.IndexOf("\n");
                        if (endIndex == -1)
                            endIndex = serviceEx.Message.Length;
                        if (endIndex > 0 && endIndex > startIndex + 1)
                        {
                            faultMessage = serviceEx.Message.Substring(startIndex + 1, endIndex - startIndex - 1);
                        }
                        else
                        {
                            faultMessage = serviceEx.Message;
                        }
                    }
                }
            }
            return faultMessage;
        }
        #endregion

        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private static ThreadContext CreateContextObj()
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();


            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", ConfigurationManager.AppSettings["orgID"].ToString());
            ns.Add("UserID", ConfigurationManager.AppSettings["userID"].ToString());
            ns.Add("UserCode", ConfigurationManager.AppSettings["userCode"].ToString());
            ns.Add("Datetime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            ns.Add("CultureName", ConfigurationManager.AppSettings["cultureName"].ToString());
            ns.Add("EnterpriseID", ConfigurationManager.AppSettings["enterpriseID"].ToString());
            ns.Add("DefaultCultureName", ConfigurationManager.AppSettings["cultureName"].ToString());
            thContext.nameValueHas = ns;

            return thContext;
        }
        #endregion

        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private static ThreadContext CreateContextObj(string OrgID)
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();


            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", OrgID);
            ns.Add("UserID", ConfigurationManager.AppSettings["userID"].ToString());
            ns.Add("UserCode", ConfigurationManager.AppSettings["userCode"].ToString());
            ns.Add("Datetime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            ns.Add("CultureName", ConfigurationManager.AppSettings["cultureName"].ToString());
            ns.Add("EnterpriseID", ConfigurationManager.AppSettings["enterpriseID"].ToString());
            ns.Add("DefaultCultureName", ConfigurationManager.AppSettings["cultureName"].ToString());
            thContext.nameValueHas = ns;

            return thContext;
        }
        #endregion
    }
}
