using ICS.WCF.Base;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.ServiceModel;
using System.Text;
using UFSoft.UBF.Exceptions;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace UFIDA.ISV.CommitMiscShip
{
    public class CustCommonitMisShip
    {
        /// <summary>
        /// 提交杂发单
        /// </summary>
        /// <returns></returns>
        //public OperationResult_CommitMisShip CustCommitMisShip(string docNo, string OrgCode)
        //{
        //    OperationResult_CommitMisShip result = new OperationResult_CommitMisShip();

        //    #region 服务调用框架结构

        //    UFIDAU9ISVMiscShipISVICommonCommitMiscShipSVClient client = new UFIDAU9ISVMiscShipISVICommonCommitMiscShipSVClient();
        //    //返回异常信息，目前还没有使用此属性
        //    MessageBase[] returnMsg;
        //    //上下文信息
        //    object context;
        //    //传入 参数

        //    try
        //    {
        //        if (string.IsNullOrWhiteSpace(docNo))
        //        {
        //            result.IsSuccess = false;
        //            result.Message = "请传入单号";
        //            result.DocNo = docNo;
        //            return result;
        //        }
        //        string OrgID = "";
        //        string orgsql = @"select ID from Base_Organization
        //                          where Code='{0}'";
        //        orgsql = string.Format(orgsql, OrgCode);
        //        DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
        //        if (orgdt.Rows.Count != 0)
        //        {
        //            OrgID = orgdt.Rows[0]["ID"].ToString();
        //        }
        //        else
        //        {
        //            result.IsSuccess = false;
        //            result.Message = "传入组织编码:" + OrgCode + "不存在!";
        //            result.DocNo = docNo;
        //            return result;
        //        }
        //        long ID = 0L;
        //        string sql = @"SELECT ID FROM InvDoc_MiscShip a WHERE a.DocNo='" + docNo + "' AND Org='" + OrgID + "'";
        //        DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
        //        if (dt != null && dt.Rows.Count > 0)
        //        {
        //            string a = dt.Rows[0][0].ToString();
        //            if (string.IsNullOrWhiteSpace(a))
        //            {
        //                result.IsSuccess = false;
        //                result.Message = "请传入单号有误，请重新输入";
        //                result.DocNo = docNo;
        //                return result;
        //            }
        //            else
        //            {
        //                ID = long.Parse(a);
        //            }
        //        }
        //        else
        //        {
        //            result.IsSuccess = false;
        //            result.Message = "请传入单号有误，请重新输入";
        //            result.DocNo = docNo;
        //            return result;
        //        }

        //        UFIDAU9ISVMiscShipISVIC_MiscShipmentDTOData[] returnItems;

        //        //给上下文信息赋值
        //        context = CreateContextObj(OrgID);
        //        //给传入参数赋值


        //        //服务调用
        //        (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
        //        (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;

        //        UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] queryArr = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] { };
        //        List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData> queryList = new List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();
        //        UFIDAU9CBOPubControllerCommonArchiveDataDTOData q = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
        //        q.m_iD = ID;
        //        q.m_code = docNo;
        //        //q.sysState = ObjectState.Updated;
        //        queryList.Add(q);
        //        queryArr = queryList.ToArray();

        //        returnItems = client.Do(out returnMsg, context, queryArr);

        //        if (returnItems != null && returnItems.Length > 0)
        //        {
        //            //获取返回信息得到创建的收货单信息
        //            foreach (var item in returnItems)
        //            {
        //                result.IsSuccess = true;
        //                result.Message = "提交杂发单成功";
        //                result.DocNo = docNo;
        //            }
        //        }
        //        else
        //        {
        //            result.IsSuccess = false;
        //            result.Message = "提交杂发提交成功";
        //            result.DocNo = "";
        //        }

        //        StringBuilder str = new StringBuilder();
        //        str.AppendLine("提交杂发");
        //        str.AppendLine("单号:" + docNo);
        //        str.AppendLine("消息:" + result.Message);
        //        str.AppendLine("结果:" + result.IsSuccess);
        //        Appconfig.WriteLogFile(str.ToString(), "提交杂发单");


        //        return result;
        //    }
        //    catch (Exception ex)
        //    {
        //        //异常信息捕获
        //        //OperationResult_ApproveMisShip model = new OperationResult_ApproveMisShip();
        //        result.IsSuccess = false;
        //        result.Message = GetExceptionMessage(ex);
        //        result.DocNo = docNo;
        //        //result.Add(model);

        //        StringBuilder str = new StringBuilder();
        //        str.AppendLine("提交杂发单异常");
        //        str.AppendLine("单号:" + docNo);
        //        str.AppendLine("错误消息:" + result.Message);
        //        str.AppendLine("结果:" + "false");
        //        Appconfig.WriteLogFile(str.ToString(), "提交杂发单异常");


        //        return result;
        //    }
        //    #endregion
        //}


        public OperationResult_CommitMisShip CustCommitMisShip(string docNo, string OrgCode, string UserID, string UserCode)
        {
            OperationResult_CommitMisShip result = new OperationResult_CommitMisShip();

            #region 服务调用框架结构

            UFIDAU9ISVMiscShipISVICommonCommitMiscShipSVClient client = new UFIDAU9ISVMiscShipISVICommonCommitMiscShipSVClient();
            //返回异常信息，目前还没有使用此属性
            MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数

            try
            {

                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, OrgCode);
                DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码:" + OrgCode + "不存在!");
                }

                List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData> queryList = new List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();


                long ID = 0L;
                string sql = @"SELECT ID FROM InvDoc_MiscShip a WHERE a.DocNo='" + docNo + "' AND Org='" + OrgID + "'";
                DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                if (dt.Rows.Count > 0)
                {
                    ID = long.Parse(dt.Rows[0]["ID"].ToString());
                }
                else
                {
                    throw new Exception("单号不存在");
                }
                UFIDAU9CBOPubControllerCommonArchiveDataDTOData q = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                q.m_iD = ID;
                q.m_code = docNo;
                queryList.Add(q);


                UFIDAU9ISVMiscShipISVIC_MiscShipmentDTOData[] returnItems;

                //给上下文信息赋值
                context = CreateContextObj(OrgID,UserID,UserCode);
                //给传入参数赋值

                //服务调用
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;

                UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] queryArr = queryList.ToArray();

                returnItems = client.Do(out returnMsg, context, queryArr);

                if (returnItems.Length > 0)
                {
                    //获取返回信息得到创建的收货单信息
                    foreach (var item in returnItems)
                    {
                        result.IsSuccess = true;
                        result.Message = "提交杂发单成功";
                        result.DocNo = docNo;
                    }
                }
                else
                {
                    throw new Exception("提交杂发提交失败");
                }
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = GetExceptionMessage(ex);
                result.DocNo = docNo;
            }
            return result;
            #endregion
        }

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

            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", OrgID);
            ns.Add("UserID", UserID);
            ns.Add("UserCode", UserCode);
            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>
        /// <param name="ex"></param>
        private 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



        public class OperationResult_CommitMisShip
        {
            //public string DocNo { get; set; }
            public string DocNo { get; set; }

            public bool IsSuccess { get; set; }
            public string Message { get; set; }
        }
    }
}
