using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.ServiceModel;
using System.Text;
using ICS.WCF.Base;
using UFSoft.UBF.Exceptions1;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using UFSoft.UBF.Exceptions;
using System.Configuration;
using ICSSoft.Entity;

namespace UFIDA.ISV.BFRCVApprove
{
    public class CustBFRCVApprove
    {

        public static ReturnValue1 CustApproveRec(string DocCode, string OrgCode, string Status)
        {
            long DocID = 0;
            string EntityType = "";
            #region 服务调用框架结构
            //实例化代理类 
            UFIDAU9PMRcvIRcvApprovedSVClient client = new UFIDAU9PMRcvIRcvApprovedSVClient();
            //服务返回结果
            //UFIDAU9PMPOPurchaseOrderData[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            //UFIDAU9PMDTOsOBAPurchaseOrderDTOData[] pOList;
            UFSoft.UBF.Business.BusinessEntity.EntityKey docHead = new UFSoft.UBF.Business.BusinessEntity.EntityKey();
            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("未获取到组织!");
                }
                DataTable dt = GetData(DocCode, OrgID);
                string state = string.Empty;
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()) && !string.IsNullOrEmpty(dt.Rows[0][1].ToString()))
                    {
                        DocID = long.Parse(dt.Rows[0][0].ToString());
                        EntityType = dt.Rows[0][1].ToString();
                        state = dt.Rows[0][2].ToString();
                    }
                    else
                    {
                        throw new Exception("输入的单据号不正确!");
                    }
                }
                else
                {
                    throw new Exception("输入的单据号不正确!");
                }

                int acttype = int.Parse(ConfigurationManager.AppSettings["acttype"].ToString());
                //给上下文信息赋值
                context = CreateContextObj(OrgID);
                //给传入参数赋值
                docHead.EntityType = EntityType;
                docHead.ID = DocID;

                //pOList = SetPoDtos(U9Info, poInfoList);
                //服务调用
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                //if (Status == "审核")
                if (Status == "审核")
                {
                    if (state == "0")
                    {
                        returnMsg = client.Do(context, 7, docHead);
                        if (returnMsg != null)
                        {
                            ReturnValue1 value = new ReturnValue1();
                            if (!string.IsNullOrWhiteSpace(returnMsg[0].localMessage))
                            {
                                value.IsSuccess = false;
                                value.Mes = returnMsg[0].localMessage;
                                return value;
                            }
                        }
                    }
                    returnMsg = client.Do(context, acttype, docHead);
                }
                else
                {
                    returnMsg = client.Do(context, 9, docHead);
                }
                if (returnMsg != null)
                {
                    ReturnValue1 value = new ReturnValue1();
                    if (!string.IsNullOrWhiteSpace(returnMsg[0].localMessage))
                    {
                        value.IsSuccess = false;
                        value.Mes = returnMsg[0].localMessage;
                        return value;
                    }
                    else
                    {
                        value.poheadList = returnMsg;
                        //value.Mes = returnMsg[0].localMessage;
                        value.IsSuccess = true;
                        return value;
                    }
                }
                else
                {
                    ReturnValue1 value = new ReturnValue1();
                    //异常信息捕获
                    value.poheadList = returnMsg;
                    //value.Mes = "未返回任何数据";
                    value.IsSuccess = true;

                    StringBuilder str = new StringBuilder();
                    str.AppendLine("审核入库单");
                    str.AppendLine("单号:" + DocCode);
                    str.AppendLine("结果:" + "True");
                    Appconfig.WriteLogFile(str.ToString(), "审核入库单");

                    return value;
                }
            }
            catch (Exception ex)
            {
                StringBuilder str = new StringBuilder();
                str.AppendLine("审核入库单");
                str.AppendLine("单号:" + DocCode);
                str.AppendLine("错误:" + GetExceptionMessage(ex));
                str.AppendLine("结果:" + "False");
                Appconfig.WriteLogFile(str.ToString(), "审核入库单");
                ReturnValue1 value = new ReturnValue1();
                //异常信息捕获
                value.Mes = "入库单号:" + DocCode + "," + GetExceptionMessage(ex);
                value.IsSuccess = false;
                return value;
            }
            #endregion
        }

        public bool Approve(List<ICSPurchaseReceiveDoc> InfoList)
        {
            long DocID = 0;
            string EntityType = "";
            #region 服务调用框架结构
            //实例化代理类 
            UFIDAU9PMRcvIRcvApprovedSVClient client = new UFIDAU9PMRcvIRcvApprovedSVClient();
            //服务返回结果
            //UFIDAU9PMPOPurchaseOrderData[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            //UFIDAU9PMDTOsOBAPurchaseOrderDTOData[] pOList;
            UFSoft.UBF.Business.BusinessEntity.EntityKey docHead = new UFSoft.UBF.Business.BusinessEntity.EntityKey();
            try
            {
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, InfoList[0].WorkPoint);
                DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("未获取到组织!");
                }
                DataTable dt = GetDataByID(InfoList[0].ID);
                string state = string.Empty;
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()) && !string.IsNullOrEmpty(dt.Rows[0][1].ToString()))
                    {
                        DocID = long.Parse(dt.Rows[0][0].ToString());
                        EntityType = dt.Rows[0][1].ToString();
                        state = dt.Rows[0][2].ToString();
                    }
                    else
                    {
                        throw new Exception("传入的单据ID查询到的数据不正确!");
                    }
                }
                else
                {
                    throw new Exception("传入的单据ID无法查询到对应数据!");
                }

                int acttype = int.Parse(ConfigurationManager.AppSettings["acttype"].ToString());
                //给上下文信息赋值
                context = CreateContextObj(OrgID);
                //给传入参数赋值
                docHead.EntityType = EntityType;
                docHead.ID = DocID;

                //pOList = SetPoDtos(U9Info, poInfoList);
                //服务调用
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                if (state == "0")
                {
                    returnMsg = client.Do(context, 7, docHead);
                    if (returnMsg != null)
                    {
                        ReturnValue1 value = new ReturnValue1();
                        if (!string.IsNullOrWhiteSpace(returnMsg[0].localMessage))
                        {
                            return false;
                        }
                    }
                }
                returnMsg = client.Do(context, acttype, docHead);
                if (returnMsg != null)
                {
                    ReturnValue1 value = new ReturnValue1();
                    if (!string.IsNullOrWhiteSpace(returnMsg[0].localMessage))
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    ReturnValue1 value = new ReturnValue1();
                    //异常信息捕获
                    value.poheadList = returnMsg;
                    //value.Mes = "未返回任何数据";
                    value.IsSuccess = true;

                    StringBuilder str = new StringBuilder();
                    str.AppendLine("审核委外退货单");
                    str.AppendLine("单据ID:" + InfoList[0].ID);
                    str.AppendLine("结果:" + "True");
                    Appconfig.WriteLogFile(str.ToString(), "审核委外退货单");

                    return true;
                }
            }
            catch (Exception ex)
            {
                StringBuilder str = new StringBuilder();
                str.AppendLine("审核委外退货单");
                str.AppendLine("单据ID:" + InfoList[0].ID);
                str.AppendLine("错误:" + GetExceptionMessage(ex));
                str.AppendLine("结果:" + "False");
                Appconfig.WriteLogFile(str.ToString(), "审核委外退货单");
                ReturnValue1 value = new ReturnValue1();
                //异常信息捕获
                return false;
            }
            #endregion
        }

        public UpdateDescReturn UpdatePOLineDesc(List<UPDATECDEFIND> InfoList)
        {
            string UpdateSql = "";
            bool NeedUpdate = false;
            UpdateDescReturn Result = new UpdateDescReturn();
            try
            {
                foreach (UPDATECDEFIND Info in InfoList)
                {
                    string OrgID = "";
                    string PoLineID = "";
                    string orgsql = @"select ID from Base_Organization
                                      where Code='{0}'";
                    orgsql = string.Format(orgsql, Info.WorkPoint);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("传入组织编码:" + Info.WorkPoint + "错误!");
                    }
                    string linesql = @" select B.ID from PM_PurchaseOrder A
                                        LEFT JOIN PM_POLine B ON B.PurchaseOrder=A.ID
                                        where DocNo='{0}' AND B.DocLineNo='{1}' AND A.Org='{2}'";
                    linesql = string.Format(linesql, Info.Code, Info.Sequence, OrgID);
                    DataTable linedt = DBhlper.Query(linesql, Appconfig.GetU9ConnStr());
                    if (linedt.Rows.Count != 0)
                    {
                        PoLineID = linedt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("传入采购订单:" + Info.Code + ",行:" + Info.Sequence + "未查询到对应采购订单行!");
                    }
                    UpdateSql += @" Update PM_POLine set ";
                    string chksql = @" IF EXISTS (
                                            SELECT 1 
                                            FROM INFORMATION_SCHEMA.COLUMNS 
                                            WHERE TABLE_NAME = 'PM_POLine' AND COLUMN_NAME = '{0}'
                                        )
                                        BEGIN
                                            select '1' AS ColumnsChk
                                        END
                                        ELSE
                                        BEGIN
                                            select '0' AS ColumnsChk
                                        END";
                    chksql = string.Format(chksql, Info.Delivery1Name);
                    DataTable chkdt = DBhlper.Query(chksql, Appconfig.GetU9ConnStr());
                    if (chkdt.Rows[0]["ColumnsChk"].ToString() == "1")
                    {
                        NeedUpdate = true;
                        UpdateSql += " " + Info.Delivery1Name + " = '" + Info.Delivery1Value + "',";
                    }
                    chksql = @" IF EXISTS (
                                            SELECT 1 
                                            FROM INFORMATION_SCHEMA.COLUMNS 
                                            WHERE TABLE_NAME = 'PM_POLine' AND COLUMN_NAME = '{0}'
                                        )
                                        BEGIN
                                            select '1' AS ColumnsChk
                                        END
                                        ELSE
                                        BEGIN
                                            select '0' AS ColumnsChk
                                        END";
                    chksql = string.Format(chksql, Info.Delivery2Name);
                    chkdt = DBhlper.Query(chksql, Appconfig.GetU9ConnStr());
                    if (chkdt.Rows[0]["ColumnsChk"].ToString() == "1")
                    {
                        NeedUpdate = true;
                        UpdateSql += " " + Info.Delivery2Name + " = '" + Info.Delivery2Value + "',";
                    }
                    UpdateSql = UpdateSql.TrimEnd(',');
                    UpdateSql += " where ID='{0}'";
                    UpdateSql = string.Format(UpdateSql, PoLineID);
                }
                #region 执行更新语句
                if (NeedUpdate == true)
                {
                    DBhlper.EXecute(UpdateSql, Appconfig.GetU9ConnStr());
                    Result.Success = true;
                    Result.Message = "";
                }
                else
                {
                    throw new Exception("传入字段无法在U9找到对应的字段名，未更新任何数据!");
                }
                #endregion
                return Result;
            }
            catch (Exception ex)
            {
                Result.Success = false;
                Result.Message = ex.Message;
                return Result;
            }
        }

        private static DataTable GetData(string DocCode, string OrgID)
        {
            string sql = @"select  A.ID,A1.[Code] as [Receivement_RcvDocType_Code],A.Status
from  PM_Receivement as A  
left join [PM_RcvDocType] as A1 on (A.[RcvDocType] = A1.[ID])  
left join [PM_RcvDocType_Trl] as A2 on (A2.SysMlFlag = 'zh-CN') and (A1.[ID] = A2.[ID])
where A.DocNo='" + DocCode + "' AND A.Org='" + OrgID + "'";
            return DBhlper.Query(sql, Appconfig.GetU9ConnStr());
        }

        private static DataTable GetDataByID(string ID)
        {
            string sql = @"select  A.ID,A1.[Code] as [Receivement_RcvDocType_Code],A.Status
                            from  PM_Receivement as A  
                            left join [PM_RcvDocType] as A1 on (A.[RcvDocType] = A1.[ID])  
                            left join [PM_RcvDocType_Trl] as A2 on (A2.SysMlFlag = 'zh-CN') and (A1.[ID] = A2.[ID])
                            where A.ID='" + ID + "'";
            return DBhlper.Query(sql, Appconfig.GetU9ConnStr());
        }

        #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

        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private static ThreadContext CreateContextObj(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
        public class ReturnValue1//List<rtnPoinfo>
        {
            public bool IsSuccess;
            public string Mes;
            public MessageBase[] poheadList;
        }

        public class ApproveReturnValue//List<rtnPoinfo>
        {
            public bool Success;
            public string Message;
        }

        public class UPDATECDEFIND
        {
            public string WorkPoint;
            public string Code;
            public string Sequence;
            public string Delivery1Name;
            public string Delivery1Value;
            public string Delivery2Name;
            public string Delivery2Value;
        }

        public class UpdateDescReturn
        {
            public bool Success;
            public string Message;
        }
    }
}
