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 System.Threading.Tasks;
using UFSoft.UBF.Exceptions;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace UFIDA.ISV.SubmitLendTrans
{
    public class CustCallSubmitLendTrans
    {
        public static OperationResult CustSubmitLendTrans(long LendID, string LendTransCode)
        {
            OperationResult result = new OperationResult();
            try
            {
                UFIDAU9ISVLendTransISVICommonCommitLendTransClient client = new UFIDAU9ISVLendTransISVICommonCommitLendTransClient();

                UFIDAU9ISVLendTransISVIC_LendTransDTOData[] resultList = new UFIDAU9ISVLendTransISVIC_LendTransDTOData[] { };
                List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData> modelList = new List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();
                UFIDAU9CBOPubControllerCommonArchiveDataDTOData model = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();

                MessageBase[] messageBase = null;
                object _context;
                _context = GetLLStateContext();
                bool isNotNewTransaction = true;

                model.m_code = LendTransCode;
                model.m_iD = LendID;
                modelList.Add(model);

                resultList = client.Do(out messageBase, _context, modelList.ToArray());

                if (resultList != null && resultList.Count() > 0)
                {
                    result.Message = "提交成功";
                    result.IsSuccess = true;
                }
                else
                {
                    throw new Exception("提交失败");
                }
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = GetExceptionMessage(ex);
            }
            return result;
        }


        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private static ThreadContext GetLLStateContext()
        {
            // 实例化应用上下文对象
            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>
        /// <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



    }

    public class OperationResult
    {

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