using ICS.DeleteMiscShip;
using ICS.WCF.Base;
using ICSSoft.Entity;
using Newtonsoft.Json;
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 UFIDA.ISV.ApproveMiscShip;
using UFIDA.ISV.CommitMiscShip;
using UFIDA.U9.ISV.INV;
using UFSoft.UBF.Service;

namespace ICS.CreateMiscShipByItemRequest
{
    public class CreateMiscShipByItemRequestSrv
    {
        public Result Create(List<CreateMiscHeadModel> ModelList)
        {
            var result = new Result();
            var datalist = new List<CreateMiscHeadModel>();

            foreach (var info in ModelList)
            {
                try
                {
                    string sql = "select ID from Base_Organization where Code ='" + info.WorkPoint + "'";
                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("组织编码不存在，编码：" + info.WorkPoint);
                    }

                    string OrgID = dt.Rows[0]["ID"].ToString();

                    sql = "select ID from Base_User where Code ='" + info.User + "'";
                    dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("用户编码不存在，编码：" + info.WorkPoint);
                    }

                    var userid = dt.Rows[0]["ID"].ToString();

                    ItemRequestToMiscShipForRestSVClient client = new ItemRequestToMiscShipForRestSVClient();
                    ItemRequestToMiscShipResultDTOData[] Rtndata;
                    ItemRequestToMiscShipInputDTOData[] data = SetData(info, OrgID);


                    ISVContext context = CreateContextObj(OrgID, info.WorkPoint, info.User);


                    Rtndata = client.Do(context, data, 0);
                    if (Rtndata.Length > 0)
                    {
                        try
                        {
                            CustCommonitMisShip commit = new CustCommonitMisShip();
                            CustCommonitMisShip.OperationResult_CommitMisShip res = commit.CustCommitMisShip(Rtndata[0].ErpDocNo, info.WorkPoint, userid, info.User);
                            if (res.IsSuccess)
                            {
                                //审核单据
                                CustApproveMiscShip approve = new CustApproveMiscShip();
                                CustApproveMiscShip.OperationResult_ApproveMisShip appres = approve.CustApproveMis(Rtndata[0].ErpDocNo, info.WorkPoint, userid, info.User);
                                if (!appres.IsSuccess)
                                {
                                    throw new Exception("审核失败：" + appres.Message);
                                }

                                string sqlupt = "";
                                //更新logids
                                foreach (var item in info.details)
                                {
                                    sqlupt += @"  update b set b.DescFlexSegments_PrivateDescSeg30 ='{0}'
                                        from InvDoc_MiscShip a
                                        join InvDoc_MiscShipL b on a.ID = b.MiscShip
                                        where a.DocNo ='" + Rtndata[0].ErpDocNo + "' and b.SrcDoc_SrcDocLine_EntityID ='" + item.DemandDetailID + "';";
                                    sqlupt = string.Format(sqlupt, item.LogIds);
                                }
                                DBhlper.EXecute(sqlupt, Appconfig.GetU9ConnStr());


                                sql = @"select a.DocNo,a.ID,b.ID LineID,b.DocLineNo,b.ItemInfo_ItemCode,b.StoreUOMQty,
                                        b.SrcDoc_SrcDocLine_EntityID,b.DescFlexSegments_PrivateDescSeg30 
                                            from InvDoc_MiscShip a
                                        left join InvDoc_MiscShipL b on a.ID = b.MiscShip
                                        where a.DocNo ='" + Rtndata[0].ErpDocNo + "' and a.Org ='" + OrgID + "'";
                                dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                                if (dt.Rows.Count > 0)
                                {
                                    var linelist = new List<CreateMiscLineModel>();
                                    foreach (DataRow item in dt.Rows)
                                    {
                                        linelist.Add(new CreateMiscLineModel
                                        {
                                            Sequence = item["DocLineNo"].ToString(),
                                            DetailID = item["LineID"].ToString(),
                                            DemandDetailID = item["SrcDoc_SrcDocLine_EntityID"].ToString(),
                                            LogIds = item["DescFlexSegments_PrivateDescSeg30"].ToString(),
                                        });
                                    }

                                    datalist.Add(new CreateMiscHeadModel
                                    {
                                        ID = dt.Rows[0]["ID"].ToString(),
                                        Code = dt.Rows[0]["DocNo"].ToString(),
                                        IsSuccess = true,
                                        Message ="成功",
                                        details = linelist
                                    });
                                }
                            }
                            else
                            {
                                throw new Exception("提交杂发单失败：" + res.Message);
                            }
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                //删除单据
                                DeleteMiscShipCode delete = new DeleteMiscShipCode();
                                var deleteres = delete.CustDeleteMiscShip(new List<string> { Rtndata[0].ErpDocNo }, OrgID);
                                if (!deleteres.Success)
                                {
                                    throw new Exception(deleteres.Message);
                                }

                                var linelist = new List<CreateMiscLineModel>();
                                foreach (var item in info.details)
                                {
                                    linelist.Add(new CreateMiscLineModel
                                    {
                                        DemandDetailID = item.DemandDetailID,
                                        LogIds = item.LogIds
                                    });
                                }

                                datalist.Add(new CreateMiscHeadModel
                                {
                                    IsSuccess = false,
                                    Message = "提交审核失败：" + ex.Message + "，删除成功",
                                    details = linelist
                                });
                            }
                            catch (Exception deleteex)
                            {
                                throw new Exception("提交审核失败：" + ex.Message + "，删除失败：" + deleteex.Message);
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("U9标准服务返回信息为空");
                    }
                }
                catch (Exception ex)
                {
                    var linelist = new List<CreateMiscLineModel>();
                    foreach (var item in info.details)
                    {
                        linelist.Add(new CreateMiscLineModel
                        {
                            DemandDetailID = item.DemandDetailID,
                            LogIds = item.LogIds
                        });
                    }

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

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

        private ItemRequestToMiscShipInputDTOData[] SetData(CreateMiscHeadModel Model, string OrgID)
        {
            List<ItemRequestToMiscShipInputDTOData> DataList = new List<ItemRequestToMiscShipInputDTOData>();

            foreach (var line in Model.details)
            {
                ItemRequestToMiscShipInputDTOData data = new ItemRequestToMiscShipInputDTOData();

                string sql = @"select a.ID,b.ID LineID,a.ItemRequestDocType from InvDoc_ItemRequest a
                                left join InvDoc_ItemRequestL b on a.id = b.ItemRequest
                                where b.ID ='" + line.DemandDetailID + "' and a.Status =2";
                DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                if (dt.Rows.Count == 0)
                {
                    throw new Exception("料品需求单不存在或者不是已审核状态");
                }
                long SrcLineID = long.Parse(dt.Rows[0]["LineID"].ToString());
                long SrcID = long.Parse(dt.Rows[0]["ID"].ToString());
                var ItemRequestDocType = dt.Rows[0]["ItemRequestDocType"].ToString();

                data.SrcID = SrcID.ToString();
                data.SrcLineID = SrcLineID;

                data.ShipDate = DateTime.Now.ToString();
                data.ShipQty = line.Quantity;

                sql = "select TargetDocTypeCode from Base_PushToDocTypeRuleLine where EntityFieldValue1 ='" + ItemRequestDocType + "'";
                dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                if (dt.Rows.Count == 0)
                {
                    throw new Exception("未查到料品需求单对应的杂发的推式配置单据类型");
                }

                var TargetDocTypeCode = dt.Rows[0]["TargetDocTypeCode"].ToString();

                data.MiscShipDocType = TargetDocTypeCode;

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

                data.Wh = long.Parse(dt.Rows[0]["ID"].ToString());
                data.RandomSrcID = SrcLineID.ToString();


                //data.Uom = "PCS";
                //data.PickTallyTime = DateTime.Now.ToString();
                //data.CreatedBy = "shaobin";
                //data.IsMFG = false;

                DataList.Add(data);
            }


            return DataList.ToArray();
        }

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

            isvContext.OrgID = Convert.ToInt64(orgID);
            isvContext.OrgCode = ORGCode;
            isvContext.UserCode = UserCode;
            isvContext.EntCode = ConfigurationManager.AppSettings["enterpriseID"].ToString();
            isvContext.CultureName = ConfigurationManager.AppSettings["cultureName"].ToString();
            return isvContext;
        }
        #endregion


    }

    public class CreateMiscHeadModel
    {
        /// <summary>
        /// 组织编码
        /// </summary>
        public string WorkPoint { get; set; }

        public string User { get; set; }

        public bool IsSuccess { get; set; }

        public string Message { get; set; }

        public string ID { get; set; }

        public string Code { get; set; }

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


    public class CreateMiscLineModel
    {
        public string DetailID { get; set; }

        public string Sequence { get; set; }
        /// <summary>
        /// 料品需求单行ID
        /// </summary>
        public string DemandDetailID { get; set; }


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

        /// <summary>
        /// 存储地点
        /// </summary>
        public string WHCode { get; set; }

        public string LogIds { get; set; }
    }

    public class CreateMiscRtnModel
    {
        public bool IsSuccess { get; set; }

        public string Message { get; set; }

        public string DocNo { get; set; }
    }

}
