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

namespace ICS.ApproveShip
{
    public class ApproveShip
    {
        private static string ERPConStr = Appconfig.GetU9ConnStr();
        private static string MessageLogName = "出货单审核";


        public AppShipReturnModel Approve(string ID, string OrgCode,string UserCode)
        {
            AppShipReturnModel res1 = new AppShipReturnModel();
            try
            {
                StringBuilder strHead = new StringBuilder();
                strHead.AppendLine("接口传入参数：" + ID);
                Appconfig.WriteLogFile(strHead.ToString(), MessageLogName);



                //组织
                string ORGID = "";
                if (!string.IsNullOrEmpty(OrgCode))
                {
                    ORGID = IsExistsCode(OrgCode, "Base_Organization");
                    if (string.IsNullOrEmpty(ORGID))
                    {
                        res1.IsSuccess = false;
                        res1.Message = "组织编码：" + OrgCode + "不存在";

                        StringBuilder str4 = new StringBuilder();
                        str4.AppendLine("***************接口传出参数：");
                        str4.AppendLine("ID:" + ID + "MESSAGE:" + res1.Message);
                        str4.AppendLine("***************接口传出参数End");
                        Appconfig.WriteLogFile(str4.ToString(), MessageLogName);

                        return res1;
                    }
                }
                else
                {
                    ORGID = Appconfig.IsExistsCode(OrgCode, "Base_Organization");
                }
                string status = "";
                //   long SysVersion = -1;
                string DocNO = "";
                DataTable dt = GetDocNO(ID, ORGID);//3：已核准；   2：核准中； 1:开立； 0:草稿
                bool IsSubmit = false;
                bool isSubmitAndApprove = false;
                bool isUnApprove = false;

                if (dt != null && dt.Rows.Count > 0)
                {
                    status = dt.Rows[0]["status"].ToString();
                    DocNO = dt.Rows[0]["docno"].ToString();
                }
                else//不存在 报错
                {
                    res1.IsSuccess = false;
                    res1.Message = "单据ID：" + ID + "不存在";

                    StringBuilder str4 = new StringBuilder();
                    str4.AppendLine("***************接口传出参数：");
                    str4.AppendLine("ID:" + ID + "MESSAGE:" + res1.Message);
                    str4.AppendLine("***************接口传出参数End");
                    Appconfig.WriteLogFile(str4.ToString(), MessageLogName);

                    return res1;
                }
                if (status == "0")//开立:报错
                {
                    //res1.IsSuccess = false;
                    //res1.Message = DocNo + "单据：草稿状态";
                    //return res1;
                    IsSubmit = false;
                    isSubmitAndApprove = true;
                }
                if (status == "1")//开立:报错
                {
                    //res1.IsSuccess = false;
                    //res1.Message = DocNo + "单据：开立状态";
                    //return res1;
                    IsSubmit = false;
                    isSubmitAndApprove = true;
                }
                if (status == "2")//审核中:报错
                {
                    IsSubmit = true;
                    isSubmitAndApprove = true;
                }

                if (status == "3")//已核准:不报错
                {
                    res1.IsSuccess = true;
                    res1.Message = DocNO + "单据：已审核状态";

                    StringBuilder str4 = new StringBuilder();
                    str4.AppendLine("***************接口传出参数：");
                    str4.AppendLine("Code:" + DocNO + "MESSAGE:" + res1.Message);
                    str4.AppendLine("***************接口传出参数End");
                    Appconfig.WriteLogFile(str4.ToString(), MessageLogName);

                    return res1;
                }

                //核准中:1 
                UFIDAU9ISVSMIAuditShipSVClient client = new UFIDAU9ISVSMIAuditShipSVClient();
                object con = CreateContextObj(ORGID);
                List<UFIDAU9ISVSMDocKeyDTOData> List = new List<UFIDAU9ISVSMDocKeyDTOData>();
                UFIDAU9ISVSMDocKeyDTOData data = new UFIDAU9ISVSMDocKeyDTOData();
                data.m_docID = long.Parse(ID);
                data.m_docNO = DocNO;
                data.m_itemBarCodeUseDTOs = new UFIDAU9BCCalcDataCreateBarCodeUsedInDTOData[0];
                List.Add(data);

                List<UFIDAU9BCCalcDataCreateBarCodeUsedInDTOData> List22 = new List<UFIDAU9BCCalcDataCreateBarCodeUsedInDTOData>();
                UFSoft.UBF.Exceptions1.MessageBase[] rrList = client.Do(con, List.ToArray(), IsSubmit, isSubmitAndApprove, isUnApprove, List22.ToArray());
                if (rrList != null && rrList.Count() > 0)
                {
                    string Message = "";
                    foreach (UFSoft.UBF.Exceptions1.MessageBase rr in rrList)
                    {
                        if (!string.IsNullOrEmpty(rr.localMessage))
                        {
                            Message += rr.localMessage + ";";
                        }
                    }
                    Message = Message.TrimEnd(';');
                    res1.IsSuccess = false;
                    res1.Message = DocNO + "审核失败：" + Message;
                }
                else
                {

                    res1.IsSuccess = true;
                    res1.Message = DocNO + "审核成功";
                    #region 审核后修改单据审核人
                    string usersql = @"select Name from Base_User
                                               where Code='{0}'";
                    usersql = string.Format(usersql, UserCode);
                    DataTable userdt = DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                    if (userdt.Rows.Count != 0)
                    {
                        usersql = @"update SM_Ship set ApproveMan='{0}',ModifiedBy='{0}'
                                where ID='{1}'
                                update SM_ShipLine set ModifiedBy='{0}'
                                where Ship='{1}'";
                        usersql = string.Format(usersql, userdt.Rows[0]["Name"].ToString(), ID);
                        DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                    }
                    #endregion
                }

                StringBuilder strHead3 = new StringBuilder();
                strHead3.AppendLine("***************接口传出参数：");
                strHead3.AppendLine("DocNo:" + DocNO + ",IsSuccess：" + res1.IsSuccess.ToString() + "MESSAGE:" + res1.Message);
                strHead3.AppendLine("***************接口传出参数End");
                Appconfig.WriteLogFile(strHead3.ToString(), MessageLogName);

                return res1;


            }
            catch (Exception ex)
            {
                res1.IsSuccess = false;
                res1.Message = GetExceptionMessage(ex);
            }


            StringBuilder strHead2 = new StringBuilder();
            strHead2.AppendLine("***************接口传出参数：");
            strHead2.AppendLine("IsSuccess：" + res1.IsSuccess.ToString() + "MESSAGE:" + res1.Message);
            strHead2.AppendLine("***************接口传出参数End");
            Appconfig.WriteLogFile(strHead2.ToString(), MessageLogName);
            return res1;

        }


        #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


        private string IsExistsCode(string Code, string TableName)
        {
            string sql = @"    select  id from  " + TableName + @"  where code='" + Code + @"' ";
            DataTable dt = DBhlper.Query(sql, ERPConStr);
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows[0][0].ToString();
            }
            return "";
        }

        public static DataTable GetDocID(string DocNo, string OrgID)
        {
            string sql = @"
                     select a.ApproveMan,a.status ,a.docno, a.id  ID ,a.SysVersion 
                    from SM_Ship a 
                    where   a.DocNo='{0}' and a.org='{1}' ";
            sql = string.Format(sql, DocNo, OrgID);
            DataTable dt = DBhlper.Query(sql, ERPConStr);
            return dt;
        }

        public static DataTable GetDocNO(string ID, string OrgID)
        {
            string sql = @"
                     select a.ApproveMan,a.status ,a.docno, a.id  ID ,a.SysVersion 
                    from SM_Ship a 
                    where   a.ID='{0}' and a.org='{1}' ";
            sql = string.Format(sql, ID, OrgID);
            DataTable dt = DBhlper.Query(sql, ERPConStr);
            return dt;
        }

    }
}
