using ICS.WCF.Base;
using ICSSoft.DataProject;
using ICSSoft.Entity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
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.Exceptions1;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;
using UFSoft.UBF.Exceptions1;
using ICS.CreateLotMaster;

namespace ICSSoft.APIModifyRMAToRCV
{
    public class ModifyRMAToRCV
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
        private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];
        private static string LogName = "修改并审核销售退回收货";
        /// <summary>
        /// 修改并审核销售退回收货
        /// </summary>
        /// <returns></returns>
        /// 
        public string ActionModifyRMAToRCV(List<ICSRcvUpdateHead> infos)
        {
            ThreadContext context;
            DataSet ds = new DataSet();
            try
            {
                string DocNo = "";
                string DocLine = "";
                string _MOCode = string.Empty;
                UFIDAU9CustDocIModifyAndApproveISMRcvModifyAndApproveServiceClient client = new UFIDAU9CustDocIModifyAndApproveISMRcvModifyAndApproveServiceClient();
                MessageBase[] message = null;
                UFIDAU9CustDocIModifyAndApproveSMRCVModifyInputHeadData InputInfo = new UFIDAU9CustDocIModifyAndApproveSMRCVModifyInputHeadData();
                List<UFIDAU9CustDocIModifyAndApproveSMRcvModifyInputLineData> LineInfoList = new List<UFIDAU9CustDocIModifyAndApproveSMRcvModifyInputLineData>();
                UFIDAU9CustDocIModifyAndApproveSMRcvModifyInputLineData InputLineInfo = new UFIDAU9CustDocIModifyAndApproveSMRcvModifyInputLineData();
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, infos[0].WorkPoint);
                DataTable orgdt = DBhlper.Query(orgsql, connString);
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码错误!");
                }

                InputInfo.m_rcvDocNo = infos[0].DocNo;
                InputInfo.m_org = new UFIDAU9BaseOrganizationOrganizationData();
                InputInfo.m_org.m_iD = long.Parse(OrgID);
                InputInfo.m_org.m_code = infos[0].WorkPoint;
                foreach (ICSRcvUpdateBody lineInfo in infos[0].details)
                {
                    InputLineInfo = new UFIDAU9CustDocIModifyAndApproveSMRcvModifyInputLineData();
                    if (DocNo == "")
                    {
                        DocNo = infos[0].DocNo;
                        DocLine = lineInfo.Sequence;
                    }
                    else
                    {
                        if (DocNo == infos[0].DocNo && DocLine == lineInfo.Sequence)
                        {
                            InputLineInfo.m_isNeedSplit = true;
                        }
                        else
                        {
                            InputLineInfo.m_isNeedSplit = false;
                            DocNo = infos[0].DocNo;
                            DocLine = lineInfo.Sequence;
                        }
                    }
                    InputLineInfo.m_rcvLineNo = int.Parse(lineInfo.Sequence);
                    InputLineInfo.m_rcvInvCode = lineInfo.InvCode;
                    InputLineInfo.m_rcvQty = lineInfo.Quantity;
                    if (lineInfo.BatchCode != "")
                    {
                        #region 创建批号接口调用
                        string LotID = "";
                        CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                        string lotWHCode = lineInfo.WHCode;
                        string lotItemCode = lineInfo.InvCode;
                        string LotCode = lineInfo.BatchCode;
                        #region 查询批号是否已经存在，如果不存在，则需要创建批号
                        string lotsql = @"  select A.ID,A.LotCode from Lot_LotMaster A
                                            LEFT JOIN CBO_ItemMaster B ON B.ID=A.Item AND B.Org=A.ItemOwnerOrg
                                            WHERE A.LotCode='{0}' AND B.Code='{1}'";
                        lotsql = string.Format(lotsql, LotCode, lotItemCode, OrgID);
                        DataTable sqldt = DBhlper.Query(lotsql, connString);
                        if (sqldt.Rows.Count != 0)
                        {
                            InputLineInfo.m_batchID = long.Parse(sqldt.Rows[0]["ID"].ToString());
                            InputLineInfo.m_batchCode = lineInfo.BatchCode;
                        }
                        else
                        {
                            LotMasterCreate.CustCreateRCVLotMasterPN(lotWHCode, lotItemCode, LotCode, OrgID, ref LotID);
                            if (LotID != "")
                            {
                                InputLineInfo.m_batchID = long.Parse(LotID);
                                InputLineInfo.m_batchCode = lineInfo.BatchCode;
                            }
                        }
                        #endregion
                        #endregion
                    }
                    else
                    {
                        InputLineInfo.m_batchID = 0;
                        InputLineInfo.m_batchCode = "";
                    }
                    LineInfoList.Add(InputLineInfo);
                }
                InputInfo.m_rcvLineInfo = LineInfoList.ToArray();
                context = CreateContextObj(OrgID);
                //服务返回结果
                UFIDAU9CustDocIModifyAndApproveSMRcvModifyReturnModelData result;
                //返回异常信息，目前还没有使用此属性
                MessageBase[] returnMsg;
                result = client.Do(context, InputInfo, out returnMsg);
                if (result.m_isSuccess == true)
                {
                    #region 查询
                    string sql = "";
                    sql = @" select DISTINCT a.ID as ID,a.ID as IDs,'' as SourceCode ,
                            a.DocNo as IssueCode,'' AS cDepCode,'' as cDepName,'' WHCode,'' WHName,
                            a.SrcDocType as SourceType,a.CreatedBy as CreateUser,a.CreatedOn as CreateDateTime,
                            a.ApprovedBy as Checker,a.ApprovedOn as CheckDateTime
                            from PM_Receivement a
                            WHERE a.DocNo='{0}' and a.Org='{1}'";
                    sql = string.Format(sql, result.m_docNo, OrgID);
                    DataTable dt = DBhlper.Query(sql, connString);
                    ds.Tables.Add(dt);

                    sql = @"select DISTINCT a.ID as IDs,b.ID as DetailID,b.DocLineNo as Sequence,c.Code as InvCode 
                                ,b.RcvQtyCU as Quantity,b.SrcDoc_SrcDocLine_EntityID as SourceDetailID,0 as Amount
                                ,d.Code as cDepCode,dd.Name as cDepName,e.Code as WHCode,ee.Name as WHName
                                ,isnull(f.Code,'') ProjectCode,isnull(g.LotCode,'') cBatch,'' version ,'' brand,
                                '' as cFree1,
                                '' as cFree2,
                                '' as cFree3,
                                '' as cFree4,
                                '' as cFree5,
                                '' as cFree6,
                                '' as cFree7,
                                '' as cFree8,
                                '' as cFree9,
                                '' as cFree10,
                                '' as LogId
                                from PM_Receivement a
                                left join PM_RcvLine b on b.Receivement=a.ID
                                left join CBO_ItemMaster c on c.ID=b.ItemInfo_ItemID
                                left join CBO_Department d on d.ID=b.RcvDept
                                left join CBO_Department_Trl dd on dd.ID=d.ID
                                left join CBO_Wh e on e.ID=b.Wh
                                left join CBO_Wh_Trl ee on ee.ID=e.ID
                                left join CBO_Project f on f.ID=b.Project
                                left join Lot_LotMaster g on g.ID=b.RcvLot
                                WHERE a.DocNo='{0}' and a.Org='{1}'";
                    sql = string.Format(sql, result.m_docNo, OrgID);
                    dt = DBhlper.Query(sql, connString);
                    ds.Tables.Add(dt);
                    #endregion
                }
                else
                {
                    throw new Exception(result.m_message);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            string szJson = JSON.DataSetToJson(ds, "details", "IDs");
            return szJson;
        }

        /// <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());
            ns.Add("acttype", ConfigurationManager.AppSettings["acttype"].ToString());
            thContext.nameValueHas = ns;

            return thContext;

            return thContext;
        }

        public class rtnMaterialDeliveryInfo
        {
            public string DocNo { get; set; }
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
            public object Data { get; set; }
        }

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

    }


}
