using ICS.WCF.Base;
using ICSSoft.Entity;
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 UFIDA.ISV.SubmitLendTrans;
using UFSoft.UBF.Exceptions1;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace UFIDA.ISV.ApproveLendTrans
{
    public class CustCallApproveLendTrans
    {
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
        public Result CustApproveLendTrans(List<ICSBrrowOutDocApprove> Infos)
        {
            Result res = new Result();
            var datalist = new List<ICSBrrowOutDocApprove>();
            foreach (var info in Infos)
            {
                try
                {
                    string sql = "select COUNT(*) Qty from InvDoc_LendLine where LendTrans ='" + 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("明细行数与单据行数不一致");
                    }



                    UFIDAU9ISVLendTransISVICommonApproveLendTransClient client = new UFIDAU9ISVLendTransISVICommonApproveLendTransClient();

                    UFIDAU9ISVLendTransISVIC_LendTransDTOData[] resultList = new UFIDAU9ISVLendTransISVIC_LendTransDTOData[] { };
                    List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData> modelList = new List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();
                    UFIDAU9CBOPubControllerCommonArchiveDataDTOData model = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();

                    MessageBase[] messageBase = null;
                    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, connString);
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("传入组织编码错误!");
                    }

                    _context = GetLLStateContext(OrgID);

                    string usersql = @"select ID,Name from Base_User
                                    where Code='{0}'";
                    usersql = string.Format(usersql, info.User);
                    DataTable userdt = DBhlper.Query(usersql, connString);
                    if (userdt.Rows.Count == 0)
                    {
                        throw new Exception("审核人员在U9不存在!");
                    }

                    #region 查询借出单ID及单据状态
                    long LendID = 0;
                    sql = @"select ID,Status from InvDoc_LendTrans
                                   where DocNo='{0}' AND Org='{1}'";
                    sql = string.Format(sql, info.DocNO, OrgID);
                    dt = DBhlper.Query(sql, connString);
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("需要审核的借出单号不存在！");
                    }

                    LendID = long.Parse(dt.Rows[0]["ID"].ToString());

                    #region 调用接口前验证料品是否有足够的库存进行审核
                    string chksql = @"select ItemInfo_ItemID,Wh,CostUOMQty,OwnerOrg,ISNULL(B.BinInfo_Bin,0) as BinInfo_Bin
                                      ,ISNULL(A.LotInfo_LotMaster,0) AS LotInfo_LotMaster from InvDoc_LendLine A
                                      LEFT JOIN InvDoc_LendBin B ON B.LendLine=A.ID
                                      where LendTrans='{0}'";
                    chksql = string.Format(chksql, LendID);
                    DataTable chkdt = DBhlper.Query(chksql, connString);
                    if (chkdt.Rows.Count != 0)
                    {
                        long chkBinID = long.Parse(chkdt.Rows[0]["BinInfo_Bin"].ToString());
                        long chkItemID = long.Parse(chkdt.Rows[0]["ItemInfo_ItemID"].ToString());
                        long chkWhID = long.Parse(chkdt.Rows[0]["Wh"].ToString());
                        long chkOrgID = long.Parse(chkdt.Rows[0]["OwnerOrg"].ToString());
                        long chkLotID = long.Parse(chkdt.Rows[0]["LotInfo_LotMaster"].ToString());
                        chksql = @"select StoreQty from InvTrans_WhQoh
                                   where ItemInfo_ItemID='{0}' AND ItemOwnOrg='{1}'
                                   AND Wh='{2}' AND ISNULL(LotInfo_LotMaster_EntityID,0)={3}
                                   AND ISNULL(BinInfo_Bin,0)={4}";
                        chksql = string.Format(chksql, chkItemID, chkOrgID, chkWhID, chkLotID, chkBinID);
                        chkdt = DBhlper.Query(chksql, connString);
                        if (chkdt.Rows.Count == 0)
                        {
                            throw new Exception("借出单:" + info.DocNO + "对应料品可用库存不足，不能进行审核操作！");
                        }
                        else
                        {
                            if (Convert.ToDecimal(chkdt.Rows[0]["StoreQty"].ToString()) == 0)
                            {
                                throw new Exception("借出单:" + info.DocNO + "对应料品可用库存不足，不能进行审核操作！");
                            }
                        }
                    }
                    #endregion
                    if (dt.Rows[0]["Status"].ToString() == "0")
                    {
                        SubmitLendTrans.OperationResult submitresult = new SubmitLendTrans.OperationResult();
                        #region 开立状态的单据需要先进行提交处理
                        submitresult = CustCallSubmitLendTrans.CustSubmitLendTrans(LendID, info.DocNO);
                        if (submitresult.IsSuccess == false)
                        {
                            throw new Exception("提交失败：" + submitresult.Message);
                        }
                        #endregion
                    }

                    #endregion
                    model.m_code = info.DocNO;
                    model.m_iD = LendID;
                    modelList.Add(model);

                    resultList = client.Do(out messageBase, _context, modelList.ToArray());


                    #region 审核成功后修改单据的修改人和审核人为WMS

                    #endregion

                    string updatesql = @"UPDATE InvDoc_LendTrans set ModifiedBy='{0}',ApprovedBy='{0}',ApprovedOn=GETDATE()
                                             where DocNo = '{1}' AND Org='{2}'";
                    updatesql = string.Format(updatesql, userdt.Rows[0]["Name"].ToString(), info.DocNO, OrgID);
                    DBhlper.EXecute(updatesql, connString);

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

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

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

                    datalist.Add(new ICSBrrowOutDocApprove
                    {
                        DocNO = info.DocNO,
                        IsSuccess = false,
                        Message = "失败：" + GetExceptionMessage(ex),
                        details = linelist
                    });
                }
            }

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

        }


        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private static ThreadContext GetLLStateContext(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 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 OperationResult
    {

        public string DocNo { get; set; }
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
    }
}
