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

namespace ICS.CreateCreateRcvRestNEW
{
    public class CreateRCV
    {

        //private static string ORGCode = ConfigurationManager.AppSettings["orgCode"].ToString();
        private static string ERPConStr = Appconfig.GetU9ConnStr();
        private static string UserCode = ConfigurationManager.AppSettings["userCode"].ToString();
        public ReturnValue CustCreatePR(List<rCVhead> Data)
        {
            #region 服务调用框架结构
            //实例化代理类 UFIDAU9ISVItemIBatchCreateItemByDTOSRVClient 
            UFIDAU9ISVRCVIRcvToRtnRcvISVClient client = new UFIDAU9ISVRCVIRcvToRtnRcvISVClient();
            //服务返回结果

            //UFIDAU9ISVPRSVPRBizKeyDTOData[] returnItems;
            UFSoft.UBF.Exceptions.MessageBase[] returnItems;
            //返回异常信息，目前还没有使用此属性
            //UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数

            string[] splitBy = new string[] { };

            try
            {
                if (Data == null || Data.Count == 0)
                {
                    throw new Exception("传入数据为空");
                }

                string ORGID = "";
                string ORGCode = Data[0].WorkPoint;

                ORGID = Appconfig.IsExistsCode(ORGCode, "Base_Organization");

                if (string.IsNullOrEmpty(ORGID))
                {
                    throw new Exception("组织编码：" + ORGCode + "在U9中不存在。");
                }
                long rcvtype = 0L;
                string DocTypeCode = "";
                //private static string DocTypeCode = ConfigurationManager.AppSettings["PORtnDocType"].ToString();
                if (Data[0].DocType == "采购")
                {
                    if (!string.IsNullOrWhiteSpace(Appconfig.GetRCVDocType(ConfigurationManager.AppSettings["PORtnDocType"].ToString(), ORGID)))
                    {
                        DocTypeCode = ConfigurationManager.AppSettings["PORtnDocType"].ToString();
                        rcvtype = Convert.ToInt64(Appconfig.GetRCVDocType(ConfigurationManager.AppSettings["PORtnDocType"].ToString(), ORGID));
                    }
                    else
                    {
                        throw new Exception("单据类型不存在");
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(Appconfig.GetRCVDocType(ConfigurationManager.AppSettings["WWPORtnDocType"].ToString(), ORGID)))
                    {
                        DocTypeCode = ConfigurationManager.AppSettings["WWPORtnDocType"].ToString();
                        rcvtype = Convert.ToInt64(Appconfig.GetRCVDocType(ConfigurationManager.AppSettings["WWPORtnDocType"].ToString(), ORGID));
                    }
                    else
                    {
                        throw new Exception("单据类型不存在");
                    }
                }



                //给上下文信息赋值
                context = CreateContextObj();

                //给传入参数赋值



                UFIDAU9ISVRCVDTORtnRcvTransformDTOData[] itemDatas = setDataForItem(Data, ORGID, ORGCode);

                StringBuilder beginstrlog = new StringBuilder();
                beginstrlog.AppendLine("参数获取完毕");
                Appconfig.WriteLogFile(beginstrlog.ToString(), "创建U9退货单");

                //服务调用
                string[] splitBy1 = null;
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                UFIDAU9ISVRCVDTORcvToRtnRcvResultDTOData data = client.Do(out returnItems, context, splitBy1, itemDatas.ToArray(), rcvtype, 1, DocTypeCode);

                StringBuilder str = new StringBuilder();
                str.AppendLine("创建U9退货单");
                str.AppendLine("单号:" + data.m_rcvDocNos[0]);
                Appconfig.WriteLogFile(str.ToString(), "创建U9退货单");

                ReturnValue value = new ReturnValue();

                List<Data> values = new List<Data>();
                int msgnumber = 0;
                List<string> docno = new List<string>();

                docno.Add(data.m_rcvDocNos[0].ToString());
                if (string.IsNullOrEmpty(data.m_rcvDocNos[0].ToString()))
                {
                    value.IsSuccess = false;
                    value.Message = "退货单创建失败";
                }
                else
                {
                    value.DocNo = data.m_rcvDocNos[0].ToString();
                    value.IsSuccess = true;
                    value.Message = "退货单创建成功";
                }

                foreach (string item in docno)
                {
                    UFIDA.ISV.BFRCVApprove.CustBFRCVApprove.ReturnValue1 TJ = CustBFRCVApprove.CustApproveRec(item, ORGCode, "审核");
                    if (!TJ.IsSuccess)
                        throw new Exception("单据：" + item + "审核错误，错误提示：" + TJ.Mes + "！");
                }
                Data _data = new Data();
                List<DataLine> list = new List<DataLine>();
                string Selsql = @"SELECT a.ID,d.Code AS DeptCode,e.Name AS DeptName,a.DocNo,g.DocNo AS POCode,c.Code cWHCode,cc.Name cWHName,a.Supplier_Supplier,a.Org
						                    ,a.CreatedBy,a.CreatedOn,b.id DetailID,b.DocLineNo Sequence,b.ItemInfo_ItemCode InvCode
                                            ,b.ArriveQtyTU AS Quantity,0 AS Amount,b.ArriveQtyTU as RCVQuantity,g.ID as POLineID,
						                    b.RcvLotCode AS cBatch,
                                            '' cFree1,'' cFree2,'' cFree3,
                                            '' cFree4,'' cFree5,'' cFree6,
                                            '' cFree7,'' cFree8,'' cFree9,
                                            '' cFree10
                                              FROM PM_Receivement a
                                            LEFT JOIN PM_RcvLine b ON b.Receivement=a.ID
                                            LEFT JOIN CBO_Wh c ON b.Wh=c.ID
                                            LEFT JOIN CBO_Wh_Trl cc ON c.ID=cc.ID
						                    LEFT JOIN CBO_Department d on d.ID=b.RcvDept and d.Org=a.Org
						                    LEFT JOIN CBO_Department_Trl e on e.ID=d.ID
											LEFT JOIN PM_RcvLine h on h.ID=b.SrcDoc_SrcDocLine_EntityID
						                    LEFT JOIN PM_POLine f on f.ID=h.SrcDoc_SrcDocLine_EntityID
						                    LEFT JOIN PM_PurchaseOrder g on g.ID=f.PurchaseOrder
                                            WHERE a.DocNO='" + data.m_rcvDocNos[0].ToString() + "' AND a.Org='" + ORGID + "'";
                DataTable Seldt = DBhlper.Query(Selsql, Appconfig.GetU9ConnStr());
                if (Seldt != null && Seldt.Rows.Count > 0)
                {
                    foreach (DataRow item in Seldt.Rows)
                    {
                        string Supplier_Supplier = item["Supplier_Supplier"].ToString();
                        string Org = item["Org"].ToString();

                        DataLine _DataLine = new DataLine();
                        _data.ID = item["ID"].ToString();
                        _data.DNCode = item["DocNo"].ToString();
                        _data.cDepCode = item["DeptCode"].ToString();
                        _data.cDepName = item["DeptName"].ToString();
                        _data.POCode = item["POCode"].ToString();
                        _data.CreateUser = item["CreatedBy"].ToString();
                        _data.CreateDateTime = Convert.ToDateTime(item["CreatedOn"].ToString());
                        _DataLine.DetailID = item["DetailID"].ToString();
                        _DataLine.Sequence = Int32.Parse(item["Sequence"].ToString());
                        _DataLine.Quantity = Decimal.Parse(item["Quantity"].ToString());
                        _DataLine.InvCode = item["InvCode"].ToString();
                        _DataLine.PODetailID = item["POLineID"].ToString();
                        _DataLine.cBatch = item["cBatch"].ToString();
                        _DataLine.cFree1 = item["cFree1"].ToString();
                        _DataLine.cFree2 = item["cFree2"].ToString();
                        _DataLine.cFree3 = item["cFree3"].ToString();
                        _DataLine.cFree4 = item["cFree4"].ToString();
                        _DataLine.cFree5 = item["cFree5"].ToString();
                        _DataLine.cFree6 = item["cFree6"].ToString();
                        _DataLine.cFree7 = item["cFree7"].ToString();
                        _DataLine.cFree8 = item["cFree8"].ToString();
                        _DataLine.cFree9 = item["cFree9"].ToString();
                        _DataLine.cFree10 = item["cFree10"].ToString();
                        _DataLine.LogId = "";
                        list.Add(_DataLine);
                    }
                    _data.details = list;
                    value.Data = _data;
                }
                Appconfig.WriteLogFile("成功", "创建U9退货单");
                return value;
            }
            catch (Exception ex)
            {
                //异常信息捕获
                string HeadList = string.Empty;

                //string message=    GetExceptionMessage(ex);
                StringBuilder str = new StringBuilder();
                foreach (rCVhead data in Data)
                {
                    str.AppendLine("创建U9退货单");
                    str.AppendLine(ex.ToString());
                    HeadList += "\r\n 收货单号：" + data.POCode;
                }
                str.AppendLine(HeadList);
                str.AppendLine("结果:" + "False");


                Appconfig.WriteLogFile(str.ToString(), "创建U9退货单");

                ReturnValue value = new ReturnValue();
                value.IsSuccess = false;
                value.Message = GetExceptionMessage(ex);
                return value;
            }
            #endregion
        }

        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;
        }

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

            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", ConfigurationManager.AppSettings["orgID"].ToString());
            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 static UFIDAU9ISVRCVDTORtnRcvTransformDTOData[] setDataForItem(List<rCVhead> datas, string ORGID, string OrgCode)
        {
            List<UFIDAU9ISVRCVDTORtnRcvTransformDTOData> prs = new List<UFIDAU9ISVRCVDTORtnRcvTransformDTOData>();
            List<ItemCURR> lstitem = new List<ItemCURR>();

            StringBuilder beginstrlog = new StringBuilder();
            beginstrlog.AppendLine("创建采购退货(传入数据开始)");
            foreach (rCVhead data in datas)
            {
                foreach (rCVLine linedr in data.details)
                {
                    UFIDAU9ISVRCVDTORtnRcvTransformDTOData pr = new UFIDAU9ISVRCVDTORtnRcvTransformDTOData();
                    string sql = @" select A.ID from PM_Rtn A
                                    INNER JOIN PM_RtnLine B ON B.Rtn=A.ID
                                    WHERE B.ID='{0}'";
                    sql = string.Format(sql, linedr.cFree1, OrgCode);
                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("传入收货单号:" + data.POCode + "不存在!");
                    }
                    pr.m_srcID = dt.Rows[0]["ID"].ToString();
                    pr.m_srcRcvDocNo = data.POCode;
                    pr.m_srcRcvLine = long.Parse(linedr.cFree1);
                    pr.m_srcRcvDocLineNo = Convert.ToInt32(linedr.srcDocPOLineNo);

                    pr.m_rtnWh = Convert.ToInt64(Appconfig.GetWhCodeByBinid(linedr.WhCode, ORGID));

                    pr.m_rcvBusinessDate = Convert.ToDateTime(data.DocDate);

                    pr.m_rejectQty = new UFIDAU9CBODTOsDoubleQuantityData();
                    //pr.m_rejectQty.m_amount1 = data.RcvQty;
                    pr.m_rejectQty.m_amount1 = linedr.Quantity;


                    pr.m_rtnDeductQty = new UFIDAU9CBODTOsDoubleQuantityData();
                    pr.m_rtnDeductQty.m_amount1 = linedr.Quantity;

                    pr.m_rtnFillQty = new UFIDAU9CBODTOsDoubleQuantityData();
                    pr.m_rtnFillQty.m_amount1 = 0;


                    pr.ExtensionData = null;
                    beginstrlog.AppendLine("收货单号:" + data.POCode);
                    beginstrlog.AppendLine("收货单行号:" + linedr.srcDocPOLineNo.ToString());
                    beginstrlog.AppendLine("退货存储地点:" + linedr.WhCode);
                    beginstrlog.AppendLine("退货数量:" + linedr.Quantity.ToString());

                    prs.Add(pr);
                }
            }
            Appconfig.WriteLogFile(beginstrlog.ToString(), "创建采购退货");
            return prs.ToArray();
        }

        #region 时间戳方法
        private DateTime TimestampToDateTime(long timestamp)
        {
            DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = timestamp * 10000000;
            TimeSpan nowTimeSpan = new TimeSpan(lTime);
            DateTime resultDateTime = dateTimeStart.Add(nowTimeSpan);
            return resultDateTime;
        }
        #endregion



    }
    public class rCVhead
    {
        private rCVLine[] _lines;
        private string _srcDocPONo;

        private string _DocType;

        private DateTime _DocDate;

        private DateTime _ArrDate;

        private string _ASNNO;

        public rCVLine[] details
        {
            get { return _lines; }
            set { _lines = value; }
        }
        public string POCode
        {
            get { return _srcDocPONo; }
            set { _srcDocPONo = value; }
        }

        /// 来源采购订单
        /// </summary>
        public DateTime DocDate
        {
            get { return _DocDate; }
            set { _DocDate = value; }
        }

        /// 来源采购订单
        /// </summary>
        public DateTime ArrDate
        {
            get { return _ArrDate; }
            set { _ArrDate = value; }
        }

        public string ASNNO
        {
            get { return _ASNNO; }
            set { _ASNNO = value; }
        }

        public string DocType
        {
            get { return _DocType; }
            set { _DocType = value; }
        }
        public string WorkPoint { get; set; }

        /// <summary>
        /// 业务员ID
        /// </summary>
        public string UserID { get; set; }
        /// <summary>
        /// 业务员Code
        /// </summary>
        public string User { get; set; }


        public string HcFree1 { get; set; }
        public string HcFree2 { get; set; }
        public string HcFree3 { get; set; }
        public string HcFree4 { get; set; }
        public string HcFree5 { get; set; }
        public string HcFree6 { get; set; }
        public string HcFree7 { get; set; }
        public string HcFree8 { get; set; }
        public string HcFree9 { get; set; }
        public string HcFree10 { get; set; }



    }

    public class rCVLine
    {
        /// <summary>
        /// 数量
        /// </summary>
        public decimal Quantity { get; set; }

        public string WhCode { get; set; }

        public string BinCode { get; set; }

        /// <summary>
        /// 炉号
        /// </summary>



        /// <summary>
        /// 来源采购订单料号
        /// </summary>
        public string InvCode { get; set; }


        /// <summary>
        /// 来源采购订单行
        /// </summary>
        public int srcDocPOLineNo { get; set; }

        /// <summary>
        /// 库存批号
        /// </summary>
        public string BatchCode { get; set; }

        /// <summary>
        /// 批号创建时间
        /// </summary>
        public DateTime LotCreateTime { get; set; }

        /// 私有段1
        public string cFree1 { get; set; }
        /// 私有段2
        public string cFree2 { get; set; }
        /// 私有段3
        public string cFree3 { get; set; }
        /// 私有段4
        public string cFree4 { get; set; }
        /// 私有段5
        public string cFree5 { get; set; }
        /// 私有段6
        public string cFree6 { get; set; }
        /// 私有段7
        public string cFree7 { get; set; }
        /// 私有段8
        public string cFree8 { get; set; }
        /// 私有段9
        public string cFree9 { get; set; }
        /// 私有段10
        public string cFree10 { get; set; }

        public string LogId { get; set; }

    }
    public class ItemCURR
    {
        public string LOTNO { get; set; }//批号
        public string ORG { get; set; }//组织编码
        public string WH { get; set; }//仓库
        public string BIN { get; set; }//库位
        public string ITEM { get; set; }//物料
        public decimal QTY { get; set; }//数量
    }
    public class ItemRatio
    {
        public long ID { get; set; }//单位编码
        public string Code { get; set; }//单位编码
        public decimal Ratio { get; set; }//位数
        public int Precision { get; set; }//精度
    }

    public class ReturnValue
    {
        public string DocNo { get; set; }
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
        public rtnRcvLine[] rtnLines { get; set; }
        public Data Data { get; set; }
    }

    public class rtnRcvLine
    {
        public int LineNo { get; set; }
    }

    public class Data
    {
        public string ID { get; set; }
        public string DNCode { get; set; }
        public string cVenCode { get; set; }
        public string cVenName { get; set; }
        public string cDepCode { get; set; }
        public string cDepName { get; set; }
        public string POCode { get; set; }
        public string CreateUser { get; set; }
        public DateTime CreateDateTime { get; set; }
        public string Checker { get; set; }
        public DateTime CheckDateTime { get; set; }
        public List<DataLine> details { get; set; }
    }
    public class DataLine
    {
        public string DetailID { get; set; }
        public int Sequence { get; set; }
        public string InvCode { get; set; }
        public Decimal Quantity { get; set; }
        public Decimal RCVQuantity { get; set; }
        public string PODetailID { get; set; }
        public Decimal Amount { get; set; }
        public string cBatch { get; set; }
        public string brand { get; set; }
        public string cFree1 { get; set; }
        public string cFree2 { get; set; }
        public string cFree3 { get; set; }
        public string cFree4 { get; set; }
        public string cFree5 { get; set; }
        public string cFree6 { get; set; }
        public string cFree7 { get; set; }
        public string cFree8 { get; set; }
        public string cFree9 { get; set; }
        public string cFree10 { get; set; }

        public string LogId { get; set; }
    }

    public class ITEMREQDATA
    {
        public string DocDate { get; set; }
        public string SrcID { get; set; }//	外系统ID 
        public string POLineID { get; set; }//	采购行ID 
        public string Uom { get; set; }//	单位  
        public decimal RcvQty { get; set; }//	收货数量 
        public string BusinessDate { get; set; }//	日期 
        public string CreatedBy { get; set; }//	操作人 
        public string LotNo { get; set; }//	批号 
        public string WHCode { get; set; }//	存储地点 
        public string Bin { get; set; }//	库位 
        public string Memo { get; set; }//	备注 
        public string Mfc { get; set; }//	厂牌 
        public string Project { get; set; }//	项目 
        public string Item { get; set; }//	料品 
        public string Supplier { get; set; }//	供应商 
        public string DocTypeCode { get; set; }//	单据类型 
        public string GroupFlag { get; set; }//	分单标识       
        public string SourceCode { get; set; }//	单号 
        public string Sequence { get; set; }//	行号     
        public decimal RtnFillQty { get; set; }//	补货数量 
        public decimal Quantity { get; set; }//	退扣数量 
        public string ReceivementType { get; set; }//	收货单类型 
        public string OtherDesc { get; set; }//	弹性域 
        public decimal PriceTC { get; set; }//	价格 

        public string WorkPoint { get; set; }//	组织 


    }
}
