using ICS.WCF.Base;
using ICSSoft.APIModifyIssue;
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.CreateMaterialDeliveryDocByMoPick
{
    public class CreateMaterialDeliveryDocByMoPickSrv
    {
        string MessageLogName = "创建材料人库单（工单子件）";
        public Result Action(List<ICS.CreateIssue.CustCreateIssue.IssueData> list)
        {
            var datalist = new List<ICS.CreateIssue.CustCreateIssue.IssueData>();
            var res = new Result();

            foreach (var item in list)
            {
                try
                {
                    var orgID = "";
                    string orgsql = @"select ID from Base_Organization
                                                      where Code='{0}' ";
                    orgsql = string.Format(orgsql, item.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 from base_user where code ='" + item.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 = item.User;
                    }

                    res = PostToOpenAPI(SetData(item, orgID), item.WorkPoint, UserCode, datalist);
                    if (!res.Success)
                    {
                        throw new Exception(res.Message);
                    }
                }
                catch (Exception ex)
                {
                    var linelist = new List<ICS.CreateIssue.CustCreateIssue.IssueLineData>();
                    foreach (var items in item.details)
                    {
                        linelist.Add(new ICS.CreateIssue.CustCreateIssue.IssueLineData
                        {
                            SourceDetailID = items.SourceDetailID,
                            LogIds = items.LogIds
                        });
                    }

                    datalist.Add(new ICS.CreateIssue.CustCreateIssue.IssueData
                    {
                        IsSuccess = false,
                        Message = ex.Message,
                        details = linelist
                    });
                }
            }

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


        private string SetData(ICS.CreateIssue.CustCreateIssue.IssueData line, string OrgID)
        {
            List<CreateMaterialDeliveryDocPostModel> HeadList = new List<CreateMaterialDeliveryDocPostModel>();

            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 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
								left join CBO_ItemMasterVersion c on b.ItemInfo = c.Item
								left join CBO_ItemMaster d on b.ItemInfo = d.ID
                                where b.MOPick ='" + item.SourceDetailID + "' and a.DocState ='2' and d.Code ='" + item.InvCode + "'";
                if (!string.IsNullOrEmpty(item.BatchCode))
                {
                    sql += "' and b.LotNo='" + item.BatchCode + "'";
                }
                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());

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

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

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

            return JsonConvert.SerializeObject(HeadList);
        }


        private Result PostToOpenAPI(string JsonPost, string OrgCode, string UserCode, List<ICS.CreateIssue.CustCreateIssue.IssueData> 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 = 0L;
                                    var DocNo = "";
                                    try
                                    {
                                         ID = long.Parse(item["m_iD"].ToString());
                                        DocNo = item["m_code"].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<ICS.CreateIssue.CustCreateIssue.IssueLineData>();
                                                    foreach (DataRow dr in dt.Rows)
                                                    {
                                                        linelist.Add(new ICS.CreateIssue.CustCreateIssue.IssueLineData
                                                        {
                                                            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 ICS.CreateIssue.CustCreateIssue.IssueData
                                                    {
                                                        ID = dt.Rows[0]["ID"].ToString(),
                                                        IssueNEGCode = dt.Rows[0]["DocNo"].ToString(),
                                                        IsSuccess = true,
                                                        Message = "创建已审核的单据成功",
                                                        details = linelist
                                                    });

                                                    res.Success = true;
                                                    res.Message = "创建已审核的单据成功";
                                                    res.Data = datalist;
                                                }
                                                else
                                                {
                                                    throw new Exception("审核单据推送数据到U9API失败：" + appitem["m_errorMsg"].ToString());
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        //删除材料出库
                                        try
                                        {
                                            List<OperateMaterialDeliveryModel> ListDoc4 = new List<OperateMaterialDeliveryModel>();
                                            OperateMaterialDeliveryModel delm = new OperateMaterialDeliveryModel();
                                            int Version = GetDocSysVersion(ID);
                                            delm.ID = ID;
                                            delm.DocNo = DocNo;
                                            delm.CurrentSysVersion = Version;
                                            delm.isAutoApp = true;
                                            ListDoc4.Add(delm);
                                            string postDelJson = JsonConvert.SerializeObject(ListDoc4);


                                            string DelUrl = "http://{0}/u9c/webapi/MaterialDeliveryDoc/Delete";
                                            DelUrl = string.Format(DelUrl, ConfigurationManager.AppSettings["U9IP"].ToString());
                                            Appconfig.WriteLogFile("删除材料出库单调用接口Json：" + postDelJson, MessageLogName);
                                            string resultDelFile = PostData.APT(DelUrl, postDelJson, TokenCode);

                                            Appconfig.WriteLogFile("删除材料出库单返回Json：" + resultDelFile, MessageLogName);

                                            CreateMaterialDeliveryWebApiReturnModel RetModel = JsonConvert.DeserializeObject<CreateMaterialDeliveryWebApiReturnModel>(resultDelFile);
                                            if (RetModel.Success == true &&
                                                RetModel.Data != null && RetModel.Data.Count > 0)
                                            {
                                                var IsTrues = RetModel.Data.Where(a => a.m_isSucess == false).ToList();
                                                if (IsTrues != null && IsTrues.Count() > 0)
                                                {
                                                    throw new Exception("单据创建成功，删除失败：" + IsTrues[0].m_errorMsg + "，单据审核异常：" + ex.Message);
                                                }

                                                throw new Exception("创建成功，审核失败，单据已删除，审核异常：" + ex.Message);
                                            }
                                            else
                                            {
                                                throw new Exception("单据创建成功，删除失败：" + RetModel.ResMsg + "，单据审核异常：" + ex.Message);
                                            }
                                        }
                                        catch (Exception exdelete)
                                        {
                                            res.Success = false;
                                            res.Message = exdelete.Message;
                                        }
                                       
                                    }
                                    
                                }
                                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  int GetDocSysVersion(long ID)
        {
            try
            {
                int version = 0;
                string sqsql = @"select SysVersion from Issue_IssueApplyDoc
                                  where ID='{0}'";
                sqsql = string.Format(sqsql, ID);
                DataTable sqdt = DBhlper.Query(sqsql, Appconfig.GetU9ConnStr());
                if (sqdt.Rows.Count != 0)
                {
                    version = int.Parse(sqdt.Rows[0]["SysVersion"].ToString());
                }
                return version;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }

    public class MaterialDeliveryDocByMoPickRtnModel
    {
        public bool Success { get; set; }

        public string Message { 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 DescFlexField DescFlexField { get; set; }
    }

    public class DescFlexField
    {
        public string PrivateDescSeg30 { 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; }
    }
}
