using ICS.WCF.Base;
using ICSSoft.Entity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UFIDA.U9.Cust.CreateRcvByPoBatchForApi
{
    public class CreateRcvByPoBatchForApiSrv
    {
        public Result Action(List<CreateRcvByPoBatchForApiModel> list)
        {
            var datalist = new List<CreateRcvByPoBatchForApiModel>();
            var res = new Result();

            foreach (var info in list)
            {
                try
                {
                    var 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)
                    {
                        throw new Exception("组织编码不存在!");
                    }

                    orgID = orgdt.Rows[0]["ID"].ToString();

                    var UserCode = "";

                    string sql = "Select ID from base_user where code ='" + info.User + "'";
                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count == 0)
                    {
                        sql = "Select ID from base_user where code ='" + Appconfig.GetDefaultUser() + "'";
                        dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                        if (dt.Rows.Count == 0)
                        {
                            throw new Exception("用户不存在!");
                        }
                        UserCode = Appconfig.GetDefaultUser();
                    }
                    else
                    {
                        UserCode = info.User;
                    }

                    res = PostToOpenAPI(SetData(info, orgID), info.WorkPoint, UserCode, datalist);
                    if (!res.Success)
                    {
                        throw new Exception(res.Message);
                    }

                }
                catch (Exception ex)
                {
                    var details = new List<CreateRcvByPoBatchForApiLineModel>();
                    foreach (var item in info.details)
                    {
                        details.Add(new CreateRcvByPoBatchForApiLineModel
                        {
                            DetailID = item.PODetailID,
                            LogIds = item.LogIds
                        });
                    }

                    datalist.Add(new CreateRcvByPoBatchForApiModel
                    {
                        IsSuccess = false,
                        Message = "创建失败：" + ex.Message,
                        details = details
                    });
                }
            }

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

        private string SetData(CreateRcvByPoBatchForApiModel info, string OrgID)
        {
            var HeadList = new List<CreateRcvByPoBatchForApiPostModel>();
            var Head = new CreateRcvByPoBatchForApiPostModel();
            var LineList = new List<CreateRcvByPoBatchForApiPostLineModel>();
            Head.IsApproved = true;
            //Head.DocStatus = 2;
            foreach (var line in info.details)
            {
                var detail = new CreateRcvByPoBatchForApiPostLineModel();
                string sqlAll = @"select 
                        (ceiling(c.SupplierConfirmQtyTU+c.SupplierConfirmQtyTU * isnull(d.PerOfOvertop,0))-c.TotalRecievedQtyTU) Qty,a.DocNo,b.DocLineNo,c.SubLineNo
                        from PM_POLine b
                        join PM_POShipLine c on c.POLine = b.ID
						join PM_PurchaseOrder a on b.PurchaseOrder = a.ID
                        left join CBO_ReceiptRule d ON b.rcvby=d.id and b.CurrentOrg=d.org
                        where c.ID ='{0}'  and c.Status =2 ";
                sqlAll = string.Format(sqlAll, line.PODetailID);
                DataTable dtAll = DBhlper.Query(sqlAll, Appconfig.GetU9ConnStr());
                if (dtAll.Rows.Count == 0)
                {
                    throw new Exception("采购订单子行不存在或状态不是已审核");
                }

                var qty = decimal.Parse(dtAll.Rows[0]["Qty"].ToString());
                if (qty == 0)
                {
                    throw new Exception("采购订单子行已全部收货，无法重复收货");
                }

                string sql = "select ID from CBO_Wh where Code ='" + line.WHCode + "' and Org ='" + OrgID + "'";
                DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                if (dt.Rows.Count == 0)
                {
                    throw new Exception("存储地点不存在，编码：" + line.WHCode);
                }

                if (!string.IsNullOrEmpty(line.BatchCode))
                {
                    sql = "select ID from Lot_LotMaster where LotCode ='" + line.BatchCode + "' and ItemCode ='" + line.InvCode + "'";
                    dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("料品批号不存在");
                    }
                }

                if (line.RtnDeductQtyTU + line.RtnFillQtyTU > line.Quantity)
                {
                    throw new Exception("传入退补加退扣大于收货数量");
                }



                var DocNo = dtAll.Rows[0]["DocNo"].ToString();
                var DocLineNo = dtAll.Rows[0]["DocLineNo"].ToString();
                var SubLineNo = dtAll.Rows[0]["SubLineNo"].ToString();

                detail.PONo = DocNo;
                detail.POLineNo = int.Parse(DocLineNo);
                detail.POShipLineNo = int.Parse(SubLineNo);

                detail.Amount1 = line.Quantity - line.RtnDeductQtyTU - line.RtnFillQtyTU;
                detail.Amount2 = 0;
                detail.ArrivedTime = DateTime.Now.ToString();
                detail.BusinessDate = DateTime.Now.ToString();
                detail.ConfirmDate = DateTime.Now.ToString();

                detail.RcvQtyPU = line.Quantity - line.RtnDeductQtyTU - line.RtnFillQtyTU;

                detail.rlInfo = new rlInfo
                {
                    Wh = new Wh { m_code = line.WHCode },
                    StorageType = 4,//可用
                    ConfirmDate = DateTime.Now.ToString(),
                    InvLotCode = line.BatchCode,
                    RtnDeductQtyTU = line.RtnDeductQtyTU,
                    RtnFillQtyTU = line.RtnFillQtyTU,
                    RejectQtyTU = line.RtnDeductQtyTU + line.RtnFillQtyTU,
                    RcvProcedure =1
                };

                detail.DescFlexField = new DescFlexField();
                detail.DescFlexField.PrivateDescSeg30 = line.LogIds;

                LineList.Add(detail);
            }

            Head.potorcvDTOS = LineList;
            HeadList.Add(Head);
            return JsonConvert.SerializeObject(HeadList);

        }


        private Result PostToOpenAPI(string JsonPost, string OrgCode, string UserCode, List<CreateRcvByPoBatchForApiModel> datalist)
        {
            var res = new Result();
            try
            {
                //获取授权
                string url = "http://{2}/u9c/webapi/OAuth2/GetAuthorizeCode?clientid={0}&clientsecret={1}";
                url = string.Format(url, ConfigurationManager.AppSettings["clientid"].ToString(), ConfigurationManager.AppSettings["clientsecret"].ToString(), ConfigurationManager.AppSettings["U9IP"].ToString());
                string resultuu = PostData.GetInfo("", url);

                JObject objuu = JObject.Parse(resultuu);

                if (objuu["Success"].ToString().ToUpper() == "TRUE" && !string.IsNullOrEmpty(objuu["Data"].ToString()))
                {
                    string keyCode = objuu["Data"].ToString();
                    //获取Token
                    string ToeknUrl = "http://{4}/u9c/webapi/OAuth2/Login?userCode={0}&entcode={1}&orgcode={2}&code={3}";
                    ToeknUrl = string.Format(ToeknUrl, UserCode, ConfigurationManager.AppSettings["enterpriseID"].ToString(), OrgCode, keyCode, ConfigurationManager.AppSettings["U9IP"].ToString());
                    string resultToken = PostData.GetInfo("", ToeknUrl);

                    objuu = JObject.Parse(resultToken);

                    if (objuu["Success"].ToString().ToUpper() == "TRUE" && !string.IsNullOrEmpty(objuu["Data"].ToString()))
                    {
                        string TokenCode = objuu["Data"].ToString();
                        //创建单据
                        string Url = "http://{0}/u9c/webapi/Receivement/CreateRcvBySrcPO";
                        Url = string.Format(Url, ConfigurationManager.AppSettings["U9IP"].ToString());

                        string File = PostData.APT(Url, JsonPost, TokenCode);


                        objuu = JObject.Parse(File);

                        if (objuu["Success"].ToString().ToUpper() != "TRUE" || string.IsNullOrEmpty(objuu["Data"].ToString()))
                        {
                            throw new Exception("调用OpenAPI创建单据失败：" + objuu["ResMsg"].ToString());
                        }
                        else
                        {
                            foreach (JObject item in objuu["Data"])
                            {
                                if (item["IsSucess"].ToString().ToUpper() == "TRUE")
                                {
                                    string sql = @"select b.DocLineNo,b.DescFlexSegments_PrivateDescSeg30,b.ID,a.Supplier_Code,d.Name,
												b.ItemInfo_ItemCode,b.RcvQtyPU,b.ArriveQtyPU,b.SrcDoc_SrcDocLine_EntityID,a.DocNo
												from PM_Receivement a
                                                    left join PM_RcvLine b on a.ID = b.Receivement
													left join CBO_Supplier c on a.Supplier_Supplier = c.ID
													left join CBO_Supplier_Trl d on a.Supplier_Supplier = d.ID
                                                    where a.ID ='" + item["ID"].ToString() + "'";
                                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                                    if (dt.Rows.Count == 0)
                                    {
                                        throw new Exception("Api返回的的单据ID未查询到指定的单据信息");
                                    }

                                    var details = new List<CreateRcvByPoBatchForApiLineModel>();
                                    foreach (DataRow dr in dt.Rows)
                                    {
                                        details.Add(new CreateRcvByPoBatchForApiLineModel
                                        {
                                            DetailID = dr["ID"].ToString(),
                                            Sequence = int.Parse(dr["DocLineNo"].ToString()),
                                            InvCode = dr["ItemInfo_ItemCode"].ToString(),
                                            Quantity = decimal.Parse(dr["ArriveQtyPU"].ToString()),
                                            LogIds = dr["DescFlexSegments_PrivateDescSeg30"].ToString(),
                                            PODetailID = dr["SrcDoc_SrcDocLine_EntityID"].ToString()
                                        });
                                    }

                                    datalist.Add(new CreateRcvByPoBatchForApiModel
                                    {
                                        ID = item["ID"].ToString(),
                                        RCVTCode = dt.Rows[0]["DocNo"].ToString(),
                                        DNCode = dt.Rows[0]["DocNo"].ToString(),
                                        IsSuccess = true,
                                        Message = "成功",
                                        details = details
                                    });

                                    res.Success = true;
                                    res.Message = "创建已审核的单据成功";
                                    res.Data = datalist;
                                }
                                else
                                {
                                    throw new Exception("创建单据推送数据到U9API失败：" + item["ErrorMsg"].ToString());
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("获取Token失败：" + objuu["ResMsg"].ToString());
                    }
                }
                else
                {
                    throw new Exception("获取授权失败：" + objuu["ResMsg"].ToString());
                }
            }
            catch (Exception ex)
            {
                res.Success = false;
                res.Message = ex.Message;
            }

            return res;
        }
    }

    public class CreateRcvByPoBatchForApiModel
    {
        public string ID;//表头ID
        public string RCVTCode;//入库单号
        public string User;//操作人
        public DateTime MTime;//操作时间
        public string VenCode;//供应商编号
        public bool UpdateStock;
        public string WHCode;//仓库编号
        public string DNCode;//到货单编号
        public string POCode;//采购订单号
        public string WorkPoint;//站点 
        public string DNRTCode;
        public string RCVNEGCode { get; set; }
        public bool Enable;
        public bool IsLineApprove { get; set; }//是否行审

        public bool IsSuccess { get; set; }

        public string Message { get; set; }

        public List<CreateRcvByPoBatchForApiLineModel> details { get; set; }
    }

    public class CreateRcvByPoBatchForApiLineModel
    {
        public int Sequence;//行号
        public string DNSequence;
        public string InvCode;
        public string WHCode;//仓库编号
        public decimal Quantity;
        public decimal Amount;
        public string Currency;
        public decimal UnitPrice;
        public string DNDetailID;
        public string DNRTDetailID;
        public string PODetailID;

        public string ProjectCode;//项目号
        public string Version;//版本
        public string Brand;//厂牌
        public string BatchCode;//批次号
        public string cFree1;//自由项1
        public string cFree2;//自由项2
        public string cFree3;//自由项3
        public string cFree4;//自由项4
        public string cFree5;//自由项5
        public string cFree6;//自由项6
        public string cFree7;//自由项7
        public string cFree8;//自由项8
        public string cFree9;//自由项9
        public string cFree10;//自由项10

        public bool IsSuccess { get; set; }

        public string Message { get; set; }

        public string LogIds { get; set; }

        public string DetailID { get; set; }

        public decimal RtnFillQtyTU { get; set; }//退补数量

        public decimal RtnDeductQtyTU { get; set; }//退扣数量

        public List<CreateRcvByPoBatchForApiDetailModel> detailss { get; set; }
    }

    public class CreateRcvByPoBatchForApiDetailModel
    {
        public string ID { get; set; }
        public string DetailID { get; set; }
        public string SourceDetailID { get; set; }
        public string SourceCode { get; set; }
        public string SourceSequence { get; set; }
        public string TransCode { get; set; }
        public string TransSequence { get; set; }
        public string InvCode { get; set; }
        public decimal Quantity { get; set; }
        public decimal Amount { get; set; }
        public string Currency { get; set; }
        public decimal UnitPrice { get; set; }
        public string ODNDetailID { get; set; }
        public string OOID { get; set; }
        public string OODetailID { get; set; }
        public string PickID { get; set; }
        public string WHCode { get; set; }
        public string ProjectCode = string.Empty;//项目号
        public string Version = string.Empty;//版本
        public string Brand = string.Empty;//厂牌
        public string BatchCode = string.Empty;//批次号
        public string cFree1 = string.Empty;//自由项1
        public string cFree2 = string.Empty;//自由项2
        public string cFree3 = string.Empty;//自由项3
        public string cFree4 = string.Empty;//自由项4
        public string cFree5 = string.Empty;//自由项5
        public string cFree6 = string.Empty;//自由项6
        public string cFree7 = string.Empty;//自由项7
        public string cFree8 = string.Empty;//自由项8
        public string cFree9 = string.Empty;//自由项9
        public string cFree10 = string.Empty;//自由项10
    }

    public class CreateRcvByPoBatchForApiPostModel
    {
        public int DocStatus { get; set; }

        public bool IsApproved { get; set; }

        public List<CreateRcvByPoBatchForApiPostLineModel> potorcvDTOS { get; set; }
    }

    public class CreateRcvByPoBatchForApiPostLineModel
    {
        public string BusinessDate { get; set; }

        public decimal Amount1 { get; set; }

        public decimal Amount2 { get; set; }

        public string PONo { get; set; }

        public int POLineNo { get; set; }

        public int POShipLineNo { get; set; }

        public string ArrivedTime { get; set; }

        public string ConfirmDate { get; set; }

        public decimal RcvQtySU { get; set; }//库存数量

        public rlInfo rlInfo { get; set; }

        public decimal RcvQtyPU { get; set; }

        public decimal RcvQtyCU { get; set; }


        public DescFlexField DescFlexField { get; set; }
    }

    public class rlInfo
    {
        public Wh Wh { get; set; }

        public string InvLotCode { get; set; }

        public int StorageType { get; set; }

        public int RcvProcedure { get; set; }

        public string ConfirmDate { get; set; }

        public decimal RtnFillQtyTU { get; set; }//退补数量

        public decimal RtnDeductQtyTU { get; set; }//退扣数量

        public decimal RejectQtyTU { get; set; }//拒收数量

        public string ItemVersion { get; set; }
    }

    public class Wh
    {
        public string m_code { get; set; }
    }

    public class DescFlexField
    {
        public string PrivateDescSeg30 { get; set; }
    }
}
