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

namespace UFIDA.ISV.TransferInBatchApproveSRV
{
    public class CustTransferInBatchApproveSRV
    {
        /// <summary>
        /// 调拨单审核--调入单
        /// </summary>
        /// <param name="DocNoList"></param>
        /// <returns></returns>
        public OperationResult CustApproveTransferIn(InPut input)
        {
            //List<OperationResult> resultList = new List<OperationResult>();
            OperationResult model = new OperationResult();
            //UFSoft.UBF.Exceptions1.MessageBase[] Do
            //(object context, www.ufida.org.EntityData.UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] docList, 
            //string approvedBy, System.DateTime approvedOn)
            #region 服务调用框架结构

            UFIDAU9ISVTransferInISVITransferInBatchApproveSRVClient client = new UFIDAU9ISVTransferInISVITransferInBatchApproveSRVClient();
            MessageBase[] returnMsg;
            //上下文信息
            object context;

            string docNo_ = string.Empty;
            try
            {
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, input.OrgCode);
                DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    model.IsSuccess = false;
                    model.Message = "传入的组织编码有误";
                    model.DocNo = "";
                    return model;
                }
                //input.DocNo = "Tra2019090004";
                //input.approvedBy = "管理员";
                if (string.IsNullOrWhiteSpace(input.approvedBy))
                {
                    model.IsSuccess = false;
                    model.Message = "传入调拨单审核人不能为空";
                    model.DocNo = "";
                    return model;
                }
                if (!string.IsNullOrWhiteSpace(input.DocNo))
                {
                    UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] TraIDData = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] { };

                    List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData> TraIDList = new List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();

                    docNo_ = string.Empty;
                    UFIDAU9CBOPubControllerCommonArchiveDataDTOData _model = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    _model.m_code = input.DocNo;
                    docNo_ = input.DocNo;
                    TraIDList.Add(_model);

                    //string docNo = "Tra2019090002";
                    //DocNoList.Add(docNo);
                    TraIDData = TraIDList.ToArray();

                    if (TraIDList != null && TraIDList.Count > 0)
                    {
                        //给上下文信息赋值
                        context = CreateContextObj(OrgID);

                        //服务调用
                        (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                        (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                        #region 获取业务员名称
                        string approvedBy = string.Empty;
                        string usersql = @"select B.Name from CBO_Operators A
                                           LEFT JOIN CBO_Operators_Trl B
                                           ON B.ID=A.ID
                                           where A.Code='{0}' and A.Org='{1}'";
                        usersql = string.Format(usersql, input.approvedBy, OrgID);
                        DataTable userdt = DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                        #endregion
                        if (userdt.Rows.Count != 0)
                        {
                            approvedBy = userdt.Rows[0]["Name"].ToString();
                        }
                        else
                        {
                            
                        }
                        System.DateTime approvedOn = DateTime.Now;

                        returnMsg = client.Do(context, TraIDData, approvedBy, approvedOn);

                        if (returnMsg != null && returnMsg.Length > 0)
                        {
                            foreach (var item in returnMsg)
                            {
                                string sql = @"SELECT DocNo  FROM  InvDoc_TransferIn WHERE ID='{0}'  ";
                                sql = string.Format(sql, item.entityID);

                                DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                                if (dt.Rows.Count > 0)
                                {
                                    foreach (DataRow dr in dt.Rows)
                                    {
                                        //OperationResult model = new OperationResult();
                                        model.IsSuccess = false;
                                        model.Message = "审核失败;" + item.localMessage;
                                        model.DocNo = dr["DocNo"].ToString();
                                        //resultList.Add(model);
                                        return model;
                                    }
                                }
                            }
                        }
                        else
                        {
                            //#region 审核成功后修改单据的修改人和审核人为WMS
                            //Appconfig.UpdateDocApproveMan(docNo_, OrgID, "WMS", "InvDoc_TransferIn", "InvDoc_TransInLine");
                            //#endregion
                            #region 审核成功后修改单据的修改人和审核人为WMS
                            usersql = @"select ID,Name from Base_User
                                   where Code='WMS'";
                            string docsql = @"select ID from InvDoc_TransferOut
                                  WHERE DocNo='{0}' AND Org='{1}'";
                            docsql = string.Format(docsql, docNo_, OrgID);
                            userdt = DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                            DataTable docdt = DBhlper.Query(docsql, Appconfig.GetU9ConnStr());
                            if (userdt.Rows.Count != 0 && docdt.Rows.Count != 0)
                            {
                                string updatesql = @"UPDATE InvDoc_TransferIn set ModifiedBy='{0}',ApprovedBy='{0}'
                                                     where ID='{1}'";
                                updatesql = string.Format(updatesql, userdt.Rows[0]["Name"].ToString(), docdt.Rows[0]["ID"].ToString());
                                DBhlper.EXecute(updatesql, Appconfig.GetU9ConnStr());
                            }
                            #endregion
                            //OperationResult model = new OperationResult();
                            model.IsSuccess = true;
                            model.Message = "审核成功";
                            model.DocNo = docNo_;
                            //resultList.Add(model);
                            return model;
                        }
                    }
                }
                else
                {
                    //OperationResult model = new OperationResult();
                    model.IsSuccess = false;
                    model.Message = "传入调拨单单号不能为空";
                    model.DocNo = "";
                    //resultList.Add(model);
                    return model;
                }
                //return resultList;
            }
            catch (Exception ex)
            {
                //异常信息捕获
                //OperationResult model = new OperationResult();
                model.IsSuccess = false;
                model.Message = GetExceptionMessage(ex);
                model.DocNo = docNo_;
                //resultList.Add(model);
                return model;
                //return resultList;

            }
            #endregion

            //行10，子行10存储地点 零件仓进行库位管理，库位不能为空，请录入。
            //行10，子行10存储地点 零件仓进行库位管理，库位不能为空，请录入。
            return model;
        }

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

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


    public class InPut
    {
        /// <summary>
        /// 调拨单单号
        /// </summary>
        public string DocNo { get; set; }

        /// <summary>
        /// 审核人
        /// </summary>
        public string approvedBy { get; set; }
        /// <summary>
        /// 组织编码
        /// </summary>
        public string OrgCode { get; set; }

    }

}
