using ICSSoft.Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ICSSoft.Entity;
using UFSoft.UBF.Util.Context;
using System.ServiceModel;
using www.ufida.org.EntityData;
using UFSoft.UBF.Exceptions1;
using UFSoft.UBF.Service;
using ICS.WCF.Base;

namespace ICSSoft.APIApproveMiscRcv
{
    public class ApproveMiscRcv
    {
        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"];
        /// <summary>
        /// 审核杂收单（外部通过API调用）
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public Result Approve(List<ICSOtherInDoc> infos)
        {
            var res = new Result();
            var datalist = new List<ICSOtherInDoc>();

            foreach (var info in infos)
            {
                try
                {
                    string sql = "select COUNT(*) Qty from InvDoc_MiscRcvTransL where MiscRcvTrans ='" + 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("明细行数与单据行数不一致");
                    }


                    UFIDAU9ISVMiscRcvISVICommonApproveMiscRcvClient client = new UFIDAU9ISVMiscRcvISVICommonApproveMiscRcvClient();
                    //返回异常信息，目前还没有使用此属性
                    MessageBase[] returnMsg;
                    //上下文信息
                    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, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("传入组织编码错误!");
                    }

                    var UserID = "";
                    var UserCode = "";

                    sql = "select ID,Code from Base_User where Code ='" + info.User + "'";
                    dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count == 0)
                    {
                        sql = "select ID,Code from Base_User where Code ='" + Appconfig.GetDefaultUser() + "'";
                        dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                        if (dt.Rows.Count == 0)
                        {
                            throw new Exception("用户编码不存在!");
                        }
                    }

                    UserID = dt.Rows[0]["ID"].ToString();
                    UserCode = dt.Rows[0]["Code"].ToString();


                    UFIDAU9ISVMiscRcvISVIC_MiscRcvDTOData[] returnItems;

                    //给上下文信息赋值
                    context = CreateContextObj(OrgID, UserID, UserCode);

                    //服务调用
                    (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                    (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;

                    UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] queryArr = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] { };
                    List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData> queryList = new List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();
                    UFIDAU9CBOPubControllerCommonArchiveDataDTOData q = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();

                    string DocNo = "";
                    sql = @"SELECT DocNO FROM InvDoc_MiscRcvTrans a WHERE a.ID='" + info.ID + "'";
                    dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count > 0)
                    {
                        DocNo = dt.Rows[0][0].ToString();
                    }
                    else
                    {
                        throw new Exception("传入单据ID有误，请确认！");
                    }
                    q = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    q.m_iD = long.Parse(info.ID);
                    q.m_code = DocNo;
                    queryList.Add(q);

                    queryArr = queryList.ToArray();

                    returnItems = client.Do(out returnMsg, context, queryArr);


                    #region 审核后修改单据审核人
                    string usersql = @"select Name from Base_User
                                   where Code='{0}'";
                    usersql = string.Format(usersql, info.User);
                    DataTable userdt = DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                    if (userdt.Rows.Count != 0)
                    {
                        usersql = @"update InvDoc_MiscRcvTrans set ApprovedBy='{0}',ModifiedBy='{0}'
                                where ID='{1}'
                                update InvDoc_MiscRcvTransL set ModifiedBy='{0}'
                                where MiscRcvTrans='{1}'";
                        usersql = string.Format(usersql, userdt.Rows[0]["Name"].ToString(), infos[0].ID);
                        DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                    }
                    else
                    {
                        usersql = @"select Name from Base_User
                                   where Code='{0}'";
                        usersql = string.Format(usersql, Appconfig.GetDefaultUser());
                        userdt = DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                        if (userdt.Rows.Count != 0)
                        {
                            usersql = @"update InvDoc_MiscRcvTrans set ApprovedBy='{0}',ModifiedBy='{0}'
                                where ID='{1}'
                                update InvDoc_MiscRcvTransL set ModifiedBy='{0}'
                                where MiscRcvTrans='{1}'";
                            usersql = string.Format(usersql, userdt.Rows[0]["Name"].ToString(), infos[0].ID);
                            DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                        }
                    }


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

                    datalist.Add(new ICSOtherInDoc
                    {
                        ID = info.ID,
                        IsSuccess = true,
                        Message = "成功",
                        details = linelist
                    });

                    #endregion

                }
                catch (Exception ex)
                {
                    var linelist = new List<ICSOtherInLineDoc>();
                    foreach (var item in info.details)
                    {
                        linelist.Add(new ICSOtherInLineDoc
                        {
                            DetailID = item.DetailID,
                            IsSuccess = false,
                            Message = "异常：" + GetExceptionMessage(ex),
                            LogIds = item.LogIds
                        });
                    }

                    datalist.Add(new ICSOtherInDoc
                    {
                        ID = info.ID,
                        IsSuccess = false,
                        Message = "异常：" + GetExceptionMessage(ex),
                        details = linelist
                    });
                }
            }

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


            return res;
        }

        /// <summary>
        /// 审核杂收单（接口内部调用，如：创建退料单后调用审核单据）
        /// </summary>
        /// <param name="DocNOList"></param>
        /// <param name="OrgCode"></param>
        /// <returns></returns>
        public bool Approve(List<string> DocIDList, string OrgCode)
        {
            bool ResultFlag = false;
            UFIDAU9ISVMiscRcvISVICommonApproveMiscRcvClient client = new UFIDAU9ISVMiscRcvISVICommonApproveMiscRcvClient();
            //返回异常信息，目前还没有使用此属性
            MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            try
            {
                if (DocIDList == null || DocIDList.Count == 0)
                {
                    throw new Exception("传入数据不能为空!");
                }
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                          where Code='{0}'";
                orgsql = string.Format(orgsql, OrgCode);
                DataTable orgdt = DBhlper.Query(orgsql, connString);
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码错误!");
                }
                UFIDAU9ISVMiscRcvISVIC_MiscRcvDTOData[] returnItems;

                //给上下文信息赋值
                context = CreateContextObj(OrgID,"","");
                //给传入参数赋值


                //服务调用
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;

                UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] queryArr = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] { };
                List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData> queryList = new List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();
                UFIDAU9CBOPubControllerCommonArchiveDataDTOData q = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                foreach (string ID in DocIDList)
                {
                    string DocNo = "";
                    string sql = @"SELECT DocNO FROM InvDoc_MiscRcvTrans a WHERE a.ID='" + ID + "' AND Org='" + OrgID + "'";
                    DataTable dt = DBhlper.Query(sql, connString);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        string a = dt.Rows[0][0].ToString();
                        if (string.IsNullOrWhiteSpace(a))
                        {
                            throw new Exception("传入单据ID有误，请确认！");
                        }
                        else
                        {
                            DocNo = a;
                        }
                    }
                    else
                    {
                        throw new Exception("传入单据ID有误，请确认！");
                    }
                    q.m_iD = long.Parse(ID);
                    q.m_code = DocNo;
                    queryList.Add(q);
                }
                queryArr = queryList.ToArray();

                returnItems = client.Do(out returnMsg, context, queryArr);
                ResultFlag = true;

            }
            catch (Exception ex)
            {
                log.Error(GetExceptionMessage(ex));
                throw new Exception(GetExceptionMessage(ex));
            }
            return ResultFlag;
        }

        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private static ThreadContext CreateContextObj(string OrgID, string UserID, string UserCode)
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();


            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", OrgID);
            ns.Add("UserID", UserID);
            ns.Add("UserCode", UserCode);
            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
    }
}
