using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using ICS.WCF.Base;
using UFIDA.U9.ISV.Rcv;
using UFSoft.UBF.Service;

namespace ICS.CreateCreateRcvRest
{
    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 static ReturnValue CustCreatePR(List<ITEMREQDATA> PRList)
        {
            #region 服务调用框架结构
            //实例化代理类 UFIDAU9ISVItemIBatchCreateItemByDTOSRVClient 
            CreateRcvRestSVClient client = new CreateRcvRestSVClient();
            //服务返回结果

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

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

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

                string ORGID = "";
                string OrgCode = "";




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

                    if (string.IsNullOrEmpty(ORGID))
                    {
                        throw new Exception("组织编码：" + ORGCode + "在U9中不存在。");
                    }
            

           

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



                CreateRcvRestDTOData[] itemDatas = setDataForItem(PRList, ORGID, ORGCode);


                //服务调用

                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                returnItems = client.Do(context, itemDatas.ToArray());

                foreach (CreateRcvRestDTOData data in returnItems)
                {
                    StringBuilder str = new StringBuilder();
                    str.AppendLine("创建U9退货单");
                    str.AppendLine("单号:" + data.DocNo);
                    Appconfig.WriteLogFile(str.ToString(), "创建U9退货单");
                }
                ReturnValue value = new ReturnValue();
                value.IsSuccess = true;
                value.Message = "退货单成功";
                List<RtnPRData> values = new List<RtnPRData>();
                int msgnumber = 0;
                foreach (CreateRcvRestDTOData data in returnItems)
                {
                    msgnumber++;
                    if (msgnumber != 1)
                    {
                        continue;
                    }
                    RtnPRData prvalue = new RtnPRData();
                    prvalue.DocNo = data.DocNo;
                    prvalue.msg = data.SyncErrMsg;
                    if (prvalue.msg != null)
                    {
                        value.IsSuccess = false;
                        value.Message = "退货单失败";
                    }
                    values.Add(prvalue);
                }
                value.PRList = values;
                Appconfig.WriteLogFile("成功", "创建U9退货单");
                return value;
            }
            catch (Exception ex)
            {
                //异常信息捕获
                string HeadList = string.Empty;


                StringBuilder str = new StringBuilder();
                foreach (ITEMREQDATA data in PRList)
                {
                    str.AppendLine("创建U9退货单");
                    str.AppendLine(ex.ToString());
                    HeadList += "\r\n 数量：" + data.RcvQty + "，调入仓库：" + data.Wh + "，库位：" + data.Bin + "，批号：" + data.LotNo +"，单位：" + data.Uom;
                }
                str.AppendLine(HeadList);
                str.AppendLine("结果:" + "False");


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

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



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

            isvContext.OrgID = Convert.ToInt64(ORGID);
            isvContext.OrgCode = ORGCode;
            isvContext.UserCode = UserCode;
            isvContext.EntCode = ConfigurationManager.AppSettings["enterpriseID"].ToString();

            return isvContext;
        }
        #endregion

        private static CreateRcvRestDTOData[] setDataForItem(List<ITEMREQDATA> datas, string ORGID, string OrgCode)
        {

            int number = 0;

            List<CreateRcvRestDTOData> prs = new List<CreateRcvRestDTOData>();



            List<ItemCURR> lstitem = new List<ItemCURR>();

            foreach (ITEMREQDATA data in datas)
            {
                number++;
                CreateRcvRestDTOData pr = new CreateRcvRestDTOData();

                if (Appconfig.Getusername(data.CreatedBy) != null)
                    pr.CreatedBy = data.CreatedBy;//创建人      
                else
                    throw new Exception("用户：" + data.CreatedBy + "不存在");


                if (Appconfig.GetPOID(data.DocNo, data.DocLineNo) != null)
                    pr.POLineID = Convert.ToInt64(Appconfig.GetPOID(data.DocNo, data.DocLineNo));
                else
                    throw new Exception("订单：" + data.DocNo + "，行：" + data.DocLineNo + "不存在");
               
                pr.DocTypeCode = data.DocTypeCode;
                pr.ReceivementType = 1;
                pr.SrcID = "1";
                pr.RcvQty = data.RcvQty;
                pr.PriceTC = data.PriceTC;
                pr.RtnDeductQty = data.RtnDeductQty;
                pr.RtnFillQty = data.RtnFillQty;
                pr.Memo = data.Memo;
                pr.LotNo = data.LotNo;
                pr.BusinessDate = data.BusinessDate;
                pr.ItemID = Convert.ToInt64(Appconfig.ITEMMATERID(data.Item, ORGID));//料品      
                
                pr.GroupFlag = data.GroupFlag;
                pr.OtherDesc = data.OtherDesc;

                if (Appconfig.GetMarkid(data.Mfc) != "")
                    pr.Mfc = Convert.ToInt64(Appconfig.GetMarkid(data.Mfc));
                else
                    pr.Mfc = 0;

                if (Appconfig.GetBysupid(data.Supplier, ORGID) != "")
                    pr.Supplier = Convert.ToInt64(Appconfig.GetBysupid(data.Supplier, ORGID));
                else
                    pr.Supplier = 0;

                if (Appconfig.uomid(data.Uom) != "")
                    pr.Uom = Convert.ToInt64(Appconfig.uomid(data.Uom));
                else
                    throw new Exception("计量单位：" + data.Uom + "不存在");

                if (Appconfig.GetWhCodeByBinid(data.Wh, ORGID) != "")
                    pr.Wh = Convert.ToInt64(Appconfig.GetWhCodeByBinid(data.Wh, ORGID)); //调出仓库id
                else
                    pr.Wh = 0;

                //throw new Exception("存储地点：" + data.Wh + "不存在");
                if (Appconfig.GetByBinid(data.Bin, ORGID) != "")
                    pr.Bin = Convert.ToInt64(Appconfig.GetByBinid(data.Bin, ORGID));
                else
                    pr.Bin = 0;
            
                //throw new Exception("库位：" + data.Bin + "不存在");

                    

                if (Appconfig.GetProjectid(data.Project, ORGID) != "")
                    pr.Project = Convert.ToInt64(Appconfig.GetProjectid(data.Project, ORGID));
                else
                    pr.Project = 0;
                //throw new Exception("项目：" + data.Project + "不存在");
             
            
                prs.Add(pr);
            }
            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 ITEMREQDATA
    {
        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 Wh { 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 DocNo { get; set; }//	单号 
        public string DocLineNo { get; set; }//	行号     
        public decimal RtnFillQty { get; set; }//	补货数量 
        public decimal RtnDeductQty { get; set; }//	退扣数量 
        public string ReceivementType { get; set; }//	收货单类型 
        public string OtherDesc { get; set; }//	弹性域 
        public decimal PriceTC { 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 bool IsSuccess { get; set; }//成功
        public string Message { get; set; }//信息
        public List<RtnPRData> PRList { get; set; }//请购单信息
    }

    public class RtnPRData
    {
        public string DocNo { get; set; }//单号
        public string msg { get; set; }//错误信息
        //public List<RtnPRLineData> lines { get; set; }//行
    }

    public class RtnPRLineData
    {
        public int DocLineNo { get; set; }//行号
        public string ItemCode { get; set; }//料号
        public decimal Qty { get; set; }//数量

        public DateTime RequiredDeliveryDate { get; set; }//要求交货日期
    }
    
}
