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.CreateMaterialDeliveryDocByMoIssueApply
{
    public class CreateMaterialDeliveryDocByMoIssueApplySrv
    {

        string MessageLogName = "创建材料人库单（领料申请单）";
        public Result Action(List<CreateMaterialDeliveryDocByMoIssueApplyModel> list)
        {
            var datalist = new List<CreateMaterialDeliveryDocByMoIssueApplyModel>();
            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("组织编码不存在!");
                    }
                    else
                    {
                        orgID = orgdt.Rows[0]["ID"].ToString();
                    }

                    var UserCode = "";
                    string sql = "Select ID,Code from base_user where code ='" + info.User + "'";
                    DataTable 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("用户不存在!");
                        }

                    }

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

                    res = PostToOpenAPI(SetData(list, orgID), info.WorkPoint, UserCode, datalist);

                    if (!res.Success)
                    {
                        throw new Exception(res.Message);
                    }
                }
                catch (Exception ex)
                {
                    var linelist = new List<CreateMaterialDeliveryDocByMoIssueApplyLineModel>();
                    foreach (var items in info.details)
                    {
                        linelist.Add(new CreateMaterialDeliveryDocByMoIssueApplyLineModel
                        {
                            SourceDetailID = items.SourceDetailID,
                            LogIds = items.LogIds
                        });
                    }

                    datalist.Add(new CreateMaterialDeliveryDocByMoIssueApplyModel
                    {
                        IsSuccess = false,
                        Message = ex.Message,
                        details = linelist
                    });
                }
            }

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


        private string SetData(List<CreateMaterialDeliveryDocByMoIssueApplyModel> list, string OrgID)
        {
            List<CreateMaterialDeliveryDocPostModel> HeadList = new List<CreateMaterialDeliveryDocPostModel>();
            foreach (var line in list)
            {
                CreateMaterialDeliveryDocPostModel Head = new CreateMaterialDeliveryDocPostModel();
                //string sql = "select ID from Issue_MaterialDeliveryDocType where Code ='" + line.MaterialDeliveryDocType + "' and Org =" + OrgID;
                //DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                //if (dt.Rows.Count == 0)
                //{
                //    throw new Exception("材料出库单单据类型不存在");
                //}

                //long DocTypeID = long.Parse(dt.Rows[0]["ID"].ToString());
                //Head.MaterialDeliveryDocType = new MaterialDeliveryDocType 
                //{
                //    ID = DocTypeID
                //};
                Head.IssueType = 1;//入库
                List<CreateMaterialDeliveryDocLinePostModel> LineList = new List<CreateMaterialDeliveryDocLinePostModel>();
                foreach (var item in line.details)
                {
                    string sql = "select ID from CBO_Wh where code ='" + item.WhCode + "' and Org =" + OrgID;
                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("仓库编码不存在");
                    }

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


                    sql = "select MOPick from Issue_IssueApplyDocLine where ID =" + item.SourceDetailID + " and DocState =2";
                    dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("未查询到已审核的领料申请单行信息");
                    }

                    var mopickid = long.Parse(dt.Rows[0]["MOPick"].ToString());


                    //sql = @"select distinct b.MOPick,a.DocNo,b.DocLineNo,b.ItemVersion,b.LotNo from Issue_MaterialDeliveryDoc a
                    //            left join Issue_MaterialDeliveryDocLine b on a.ID = b.MaterialDeliveryDoc
                    //            where  b.SourceDoc_SrcDocLine_EntityID =" + item.SourceDetailID;
                    //dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    //if (dt.Rows.Count == 0)
                    //{
                    //    throw new Exception("领料申请单行未查询到已审核的材料出库单信息");
                    //}
                    //var 材料出单据 = dt.Rows[0]["DocNo"].ToString();
                    //var 材料出行号 = int.Parse(dt.Rows[0]["DocLineNo"].ToString());



                    LineList.Add(new CreateMaterialDeliveryDocLinePostModel
                    {
                        SourceDocType = 1,//领料申请
                        //IssueApplyDocLine = new IssueApplyDocLine
                        //{
                        //    ID = applineID
                        //},
                        MOPickList = new MOPickList
                        {
                            ID = mopickid
                        },
                        Wh = new Wh
                        {
                            ID = whid
                        },
                        IssuedQty = item.Quantity,
                        ItemVerSion = new ItemVerSion
                        {
                            Code = item.Version
                        },
                        Lot = new Lot
                        {
                            Code = item.BatchCode
                        },
                        Item = new Item
                        {
                            Code = item.InvCode
                        },
                        //MaterialDeliveryDocNo = 材料出单据,
                        //MaterialDeliveryDocLineNum = 材料出行号
                    });
                }
                Head.MaterialDeliveryDocLines = LineList;
                HeadList.Add(Head);
            }
            return JsonConvert.SerializeObject(HeadList);
        }


        private Result PostToOpenAPI(string JsonPost, string OrgCode, string UserCode, List<CreateMaterialDeliveryDocByMoIssueApplyModel> 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);

                Appconfig.WriteLogFile("授权返回Json：" + resultuu, MessageLogName);

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

                    Appconfig.WriteLogFile("Token返回Json：" + resultToken, MessageLogName);

                    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/MaterialDeliveryDoc/Create";
                        Url = string.Format(Url, ConfigurationManager.AppSettings["U9IP"].ToString());

                        Appconfig.WriteLogFile("创建单据传入Json：" + JsonPost, MessageLogName);
                        string File = PostData.APT(Url, JsonPost, TokenCode);

                        Appconfig.WriteLogFile("创建单据返回Json：" + File, MessageLogName);

                        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["m_isSucess"].ToString().ToUpper() == "TRUE")
                                {
                                    var ID = long.Parse(item["m_iD"].ToString());


                                    Url = "http://{0}/u9c/webapi/MaterialDeliveryDoc/Approve";
                                    Url = string.Format(Url, ConfigurationManager.AppSettings["U9IP"].ToString());

                                    List<ApproveMaterialDeliveryDocPostModel> applist = new List<ApproveMaterialDeliveryDocPostModel>();
                                    applist.Add(new ApproveMaterialDeliveryDocPostModel
                                    {
                                        ID = ID
                                    });

                                    var appJson = JsonConvert.SerializeObject(applist);

                                    Appconfig.WriteLogFile("审核单据传入Json：" + appJson, MessageLogName);

                                    string AppRtnJson = PostData.APT(Url, appJson, TokenCode);

                                    Appconfig.WriteLogFile("审核单据返回Json：" + AppRtnJson, MessageLogName);

                                    objuu = JObject.Parse(AppRtnJson);
                                    if (objuu["Success"].ToString().ToUpper() != "TRUE" || string.IsNullOrEmpty(objuu["Data"].ToString()))
                                    {
                                        throw new Exception("调用OpenAPI审核单据失败：" + objuu["ResMsg"].ToString());
                                    }
                                    else
                                    {
                                        foreach (JObject appitem in objuu["Data"])
                                        {
                                            if (appitem["m_isSucess"].ToString().ToUpper() == "TRUE")
                                            {
                                                string sql = @"select distinct a.ID,a.DocNo,b.ID LineID,b.LineNum,c.Code,b.IssuedQty,
                                b.DescFlexField_PrivateDescSeg30,b.SourceDoc_SrcDocLine_EntityID
                                from MO_IssueDoc a
                                left join MO_IssueDocLine b on a.ID = b.IssueDoc
                                left join CBO_ItemMaster c on b.Item = c.ID
                                where a.ID =" + appitem["m_iD"].ToString();
                                                DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                                                if (dt.Rows.Count == 0)
                                                {
                                                    throw new Exception("OpenApi返回的单据ID未查到相关单据信息");
                                                }

                                                var linelist = new List<CreateMaterialDeliveryDocByMoIssueApplyLineModel>();
                                                foreach (DataRow dr in dt.Rows)
                                                {
                                                    linelist.Add(new CreateMaterialDeliveryDocByMoIssueApplyLineModel
                                                    {
                                                        DetailID = dr["LineID"].ToString(),
                                                        Sequence = dr["LineNum"].ToString(),
                                                        InvCode = dr["Code"].ToString(),
                                                        Quantity = decimal.Parse(dr["IssuedQty"].ToString()),
                                                        LogIds = dr["DescFlexField_PrivateDescSeg30"].ToString(),
                                                        SourceDetailID = dr["SourceDoc_SrcDocLine_EntityID"].ToString()
                                                    });
                                                }
                                                datalist.Add(new CreateMaterialDeliveryDocByMoIssueApplyModel
                                                {
                                                    ID = dt.Rows[0]["ID"].ToString(),
                                                    SourceCode = dt.Rows[0]["DocNo"].ToString(),
                                                    IsSuccess = true,
                                                    Message = "创建已审核的单据成功",
                                                    details = linelist
                                                });
                                            }
                                            else
                                            {
                                                throw new Exception("审核单据推送数据到U9API失败：" + appitem["m_errorMsg"].ToString());
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    throw new Exception("创建单据推送数据到U9API失败：" + item["m_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 MaterialDeliveryDocByMoPickRtnModel
    {
        public bool Success { get; set; }

        public string Message { get; set; }
    }

    public class CreateMaterialDeliveryDocByMoIssueApplyModel
    {
        public string ID { get; set; }//组织编码


        public string SourceCode { get; set; }//组织编码

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

        public string User { get; set; }//业务员编码

        public bool IsSuccess { get; set; }

        public string Message { get; set; }

        public DateTime BusinessDate { get; set; }

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

    public class CreateMaterialDeliveryDocByMoIssueApplyLineModel
    {
        public string Sequence { get; set; }

        public string SourceDetailID { get; set; }

        public string DetailID { get; set; }

        public string WhCode { get; set; }

        public decimal Quantity { get; set; }

        public string Version { get; set; }


        public string BatchCode { get; set; }

        public string InvCode { get; set; }

        public string LogIds { get; set; }
    }

    public class CreateMaterialDeliveryDocPostModel
    {
        public MaterialDeliveryDocType MaterialDeliveryDocType { get; set; }

        public int IssueType { get; set; }

        public DateTime BusinessDate { get; set; }

        public List<CreateMaterialDeliveryDocLinePostModel> MaterialDeliveryDocLines { get; set; }
    }


    public class MaterialDeliveryDocType
    {
        public long ID { get; set; }
    }


    public class CreateMaterialDeliveryDocLinePostModel
    {
        public int SourceDocType { get; set; }

        public MOPickList MOPickList { get; set; }

        public Wh Wh { get; set; }

        public Lot Lot { get; set; }

        public ItemVerSion ItemVerSion { get; set; }

        public decimal IssuedQty { get; set; }

        public Item Item { get; set; }

        public string MaterialDeliveryDocNo { get; set; }

        public int MaterialDeliveryDocLineNum { get; set; }
    }


    public class MOPickList
    {
        public long ID { get; set; }
    }

    public class Wh
    {
        public long ID { get; set; }
    }

    public class Lot
    {
        //public long ID { get; set; }

        public string Code { get; set; }
    }

    public class Item
    {
        //public long ID { get; set; }

        public string Code { get; set; }
    }

    public class ItemVerSion
    {
        //public long ID { get; set; }
        public string Code { get; set; }
    }

    public class ApproveMaterialDeliveryDocPostModel
    {
        public long ID { get; set; }
    }
}
