using ICS.WCF.Base;
using ICSSoft.Entity;
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.ApproveLendBakcTrans
{
    public class CustCallApproveLendBackTrans
    {
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
        public Result ApproveLendBackTrans(List<ICSReturnInDocApprove> Infos)
        {
            var res = new Result();
            var datalist = new List<ICSReturnInDocApprove>();

            foreach (var info in Infos)
            {
                try
                {
                    string sql = "select COUNT(*) Qty from InvDoc_LendBackLine where LendBackTrans ='" + info.ID + "'";
                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    var LineCount = int.Parse(dt.Rows[0]["Qty"].ToString());
                    if (LineCount == 0)
                    {
                        throw new Exception("还入单ID不存在");
                    }

                    if (info.details == null)
                    {
                        throw new Exception("明细行数为0");
                    }

                    if (LineCount != info.details.Count)
                    {
                        throw new Exception("明细行数与单据行数不一致");
                    }




                    UFIDAU9ISVLendBackTransISVICommonLendBackTransApproveSVClient client = new UFIDAU9ISVLendBackTransISVICommonLendBackTransApproveSVClient();
                    //服务返回结果


                    UFIDAU9ISVLendBackTransISVLendBackTransDocInfoData[] data;

                    MessageBase[] messageBase = null;
                    object _context;

                    string OrgID = "";
                    string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                    orgsql = string.Format(orgsql, info.WorkPoint);
                    DataTable orgdt = DBhlper.Query(orgsql, connString);
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("传入组织编码错误!");
                    }

                    _context = GetLLStateContext(OrgID);


                    List<UFIDAU9ISVLendBackTransISVLendBackTransDocInfoData> DataList = new List<UFIDAU9ISVLendBackTransISVLendBackTransDocInfoData>();
                    DataList.Add(new UFIDAU9ISVLendBackTransISVLendBackTransDocInfoData
                    {
                        m_docID = long.Parse(info.ID)
                    });

                    data = DataList.ToArray();


                    //服务调用
                    (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                    (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                    messageBase = client.Do(_context, data, 2);

                    var linelist = new List<ICSReturnInDocLineApprove>();
                    foreach (var item in info.details)
                    {
                        linelist.Add(new ICSReturnInDocLineApprove
                        {
                            DetailID = item.DetailID,
                            IsSuccess = true,
                            Message = "成功",
                            LogIds = item.LogIds
                        });
                    }

                    datalist.Add(new ICSReturnInDocApprove
                    {
                        DocNO = info.DocNO,
                        IsSuccess = true,
                        Message = "成功",
                        details = linelist
                    });
                }
                catch (Exception ex)
                {
                    var linelist = new List<ICSReturnInDocLineApprove>();
                    foreach (var item in info.details)
                    {
                        linelist.Add(new ICSReturnInDocLineApprove
                        {
                            DetailID = item.DetailID,
                            LogIds = item.LogIds,
                            IsSuccess = false,
                            Message = "失败：" + GetExceptionMessage(ex),
                        });
                    }

                    datalist.Add(new ICSReturnInDocApprove
                    {
                        DocNO = info.DocNO,
                        IsSuccess = false,
                        Message = "失败：" + GetExceptionMessage(ex),
                        details = linelist
                    });
                }
            }

            res.Success = true;
            res.Message = "成功";
            res.Data = datalist;
            return res;
        }


        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private static ThreadContext GetLLStateContext(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


        #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; }
    }
}
