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.Exceptions1;
using UFSoft.UBF.PL.Engine;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace UFIDA.ISV.ApproveMiscShip
{
    public class CustApproveMiscShip
    {
        /// <summary>
        /// 审核杂发单  0032019050037
        /// </summary>
        /// <returns></returns>
        //public OperationResult_ApproveMisShip CustApproveMis(string docNo, string OrgCode)
        //{
        //    OperationResult_ApproveMisShip result = new OperationResult_ApproveMisShip();

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

        //    UFIDAU9ISVMiscShipISVICommonApproveMiscShipSVClient client = new UFIDAU9ISVMiscShipISVICommonApproveMiscShipSVClient();
        //    //返回异常信息，目前还没有使用此属性
        //    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);
        //        #region 审核成功后修改单据的修改人和审核人为WMS
        //        string usersql = @"select ID,Name from Base_User
        //                           where Code='WMS'";
        //        string docsql = @"select ID from InvDoc_TransferOut
        //                          WHERE DocNo='{0}' AND Org='{1}'";
        //        docsql = string.Format(docsql, docNo, OrgID);
        //        DataTable userdt = DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
        //        DataTable docdt = DBhlper.Query(docsql, Appconfig.GetU9ConnStr());
        //        if (userdt.Rows.Count != 0 && docdt.Rows.Count != 0)
        //        {
        //            string updatesql = @"UPDATE InvDoc_MiscShip set ModifiedBy='{0}',ApprovedBy='{0}'
        //                                 where ID='{1}'";
        //            updatesql = string.Format(updatesql, userdt.Rows[0]["Name"].ToString(), docdt.Rows[0]["ID"].ToString());
        //            DBhlper.EXecute(updatesql, Appconfig.GetU9ConnStr());
        //        }
        //        #endregion
        //        //if (returnItems != null && returnItems.Length > 0)
        //        //{
        //        //    //获取返回信息得到创建的收货单信息

        //        //}
        //        //else
        //        //{
        //        //    //OperationResult_ApproveMisShip model = new OperationResult_ApproveMisShip();
        //        //    result.IsSuccess = false;
        //        //    result.Message = "审核杂发单成功";
        //        //    result.DocNo = "";
        //        //    //result.Add(model);
        //        //}

        //        result.IsSuccess = true;
        //        result.Message = "审核杂发单成功";
        //        result.DocNo = 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_ApproveMisShip CustApproveMis(string docNo, string OrgCode, string UserID, string UserCode)
        {
            OperationResult_ApproveMisShip result = new OperationResult_ApproveMisShip();

            #region 服务调用框架结构

            UFIDAU9ISVMiscShipISVICommonApproveMiscShipSVClient client = new UFIDAU9ISVMiscShipISVICommonApproveMiscShipSVClient();
            //返回异常信息，目前还没有使用此属性
            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<string> strList = new List<string>();
                UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] queryArr = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] { };
                List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData> queryList = new List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();
                UFIDAU9ISVMiscShipISVIC_MiscShipmentDTOData[] returnItems;
                //给上下文信息赋值
                context = CreateContextObj(OrgID, UserID, UserCode);
                //给传入参数赋值

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



                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);

                queryArr = queryList.ToArray();

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

                result.IsSuccess = true;
                result.Message = "审核杂发单成功";
                result.DocNo = docNo;
            }
            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_ApproveMisShip
        {
            //public string DocNo { get; set; }
            public string DocNo { get; set; }

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