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.Business.BusinessEntity;
using UFSoft.UBF.Exceptions1;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;

namespace UFIDA.ISV.AppRovedAPBill
{
    public class CustApprovedAPBill
    {
        public ApproveAPRtnModel CustApprovedAP(ApproveAPModel model)
        {

            ApproveAPRtnModel result = new ApproveAPRtnModel();
            try
            {
                UFIDAU9APAPBillIAPBillApproveSVClient client = new UFIDAU9APAPBillIAPBillApproveSVClient();
                //返回异常信息，目前还没有使用此属性
                MessageBase[] returnMsg;


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


                string orgID = orgdt.Rows[0]["ID"].ToString();


                //上下文信息
                object _context = CreateContextObj(orgID);

                EntityKey entity = new EntityKey();

                string sql = "select ID from AP_APBillHead where DocNo ='" + model.DocNo + "' and Org ='" + orgID + "'";
                DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                if (dt.Rows.Count == 0)
                    throw new Exception("单号不存在！");

                long DocID = long.Parse(dt.Rows[0]["ID"].ToString());

                entity.ID = DocID;

                client.Do(out returnMsg, _context, entity);

                result.IsSuccess = true;
                result.Message = "审核成功！";

                //int returnRes = client.Do(out returnMsg, _context, entity);
                //if (returnRes == 2)
                //{
                //    result.IsSuccess = true;
                //    result.MESSAGE = "审核应付单成功";
                //    result.Code = Code;
                //}
                //else
                //{
                //    result.IsSuccess = false;
                //    result.MESSAGE = "审核应付单失败";
                //    result.Code = Code;
                //}
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = GetExceptionMessage(ex);
            }
            return result;
        }

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

            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


        #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 ApproveAPRtnModel
    {
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
    }

    public class ApproveAPModel
    {
        public string DocNo { get; set; }

        public string OrgCode { get; set; }
    }
}
