using ICSSoft.Common;
using ICSSoft.Entity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ICSSoft.DataProject
{
    /// <summary>
    /// 委外发料
    /// </summary>
    public class OutsourcingIssueDoc
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
        private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];
        private static string Type = System.Configuration.ConfigurationManager.AppSettings["Type"];
        public string Get(List<ICSOutsourcingIssueDoc> infos)
        {
            List<ICSOutsourcingIssueDoc> szJson = new List<ICSOutsourcingIssueDoc>();
            DataTable dt = null;
            string json = "";
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空!");
            }
            string res = string.Empty;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
            conn.Open();
            SqlTransaction sqlTran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = conn;
            try
            {
                string sql = string.Empty;
                foreach (ICSOutsourcingIssueDoc info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @"select a.ID as ID,a.ID as IDs,a.cCode as IssueCode,a.cDepCode,c.cDepName,a.cWhCode,
                            d.cWhName,a.cSource,cMPoCode,a.cMaker,dnmaketime,cHandler,dnverifytime 
                            from rdrecord11 a
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                           where a.cBusType='委外发料'

                     select a.ID as IDs,iMPoIds as SourceDetailID ,b.irowno as Sequence,iordercode,b.cInvCode,b.iQuantity,b.iNum,b.AutoID as DetailID
                            from rdrecord11 a
                            left join rdrecords11 b on a.ID=b.ID
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                            left join OM_MODetails e on b.iOMoDID=e.MoDetailsID
                           where a.cBusType='委外发料'";
                    if (!string.IsNullOrWhiteSpace(info.IssueCode))
                    {
                        sql += " and a.cCode='{0}'";
                    }
                    if (!string.IsNullOrWhiteSpace(info.MTime.ToString()))
                    {
                        sql += " and ISNULL(a.dnmodifytime,ISNULL(a.dnverifytime, ISNULL(a.dnmodifytime, a.dnmaketime)))>='{1}'";
                    }
                    if (!string.IsNullOrWhiteSpace(info.User))
                    {
                        sql += "and a.CMAKER='{2}'";
                    }
                    sql = string.Format(sql, info.IssueCode, info.MTime, info.User);
                    dt = DBHelper.SQlReturnData(sql, cmd);
                    json = JsonConvert.SerializeObject(dt);
                    if (dt.Rows.Count <= 0 || dt == null)
                        throw new Exception("委外发料单:" + info.IssueCode + ",无信息!");

                }
                cmd.Transaction.Commit();
                return json;
            }
            catch (Exception ex)
            {
                cmd.Transaction.Rollback();
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
                conn.Dispose();
            }
        }
        public string CreateOutsourcingIssueDoc(List<ICSOutsourcingIssueDoc> Bills)
        {
            bool ResultFlag = false;
            string msg = "";
            DataTable dt = null;
            string sql = string.Empty;
            int num = 0;
            string iFatherIdTwo = "";
            //取得out库单的默认显示模版
            //取得采购入库单单据 表头ID,表体DID
            VouchKey key = new VouchKey();
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
            conn.Open();
            SqlTransaction sqlTran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = conn;

            try
            {
                if (Bills.Count <= 0)
                {
                    throw new Exception("传送数据为空!");
                }
                LogInfo(Bills);
                LogInfo(Bills);
                foreach (ICSOutsourcingIssueDoc head in Bills)
                {
                    num = head.details.Count();
                    Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "rd", "" + num + "");
                    int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
                    int iChildId = Convert.ToInt32(dic["iChildId"].ToString());
                    DateTime date = DateTime.Now;
                    string iBaseCodeLen = DBHelper.GetAllRDCode("26", "" + date + "", "admin");
                   
                    if (head.details.Count <= 0)
                    {
                        throw new Exception("表体信息不存在!");
                    }
                    #region 判断委外订单是否已关闭
                    sql = @"SELECT distinct isnull(b.cbCloser,'') as CloseUser 
                            from dbo.OM_MOMaterials a
                            INNER JOIN OM_MODetails b ON a.MoDetailsID = b.MoDetailsID 
                            where a.MOMaterialsID='" + head.details[0].SourceDetailID + "'";
                    DataTable dtClose = DBHelper.SQlReturnData(sql, cmd);
                    if (dtClose != null && dtClose.Rows.Count > 0)
                    {
                        if (!string.IsNullOrEmpty(dtClose.Rows[0][0].ToString()))
                        {
                            throw new Exception("该委外订单行已关闭,无法领料!");
                        }
                    }
                    #endregion
                    #region 判断物料是否超额领取
                    foreach (ICSOutsourcingIssueDocs body in head.details)
                    {
                        sql = @"SELECT isnull(b.fOutExcess,0) as fOutExcess,isnull(a.iSendQTY,0) as IssQty,a.iQuantity  
                                FROM dbo.OM_MOMaterials a 
                                LEFT JOIN dbo.Inventory b ON a.cInvCode=b.cInvCode
                                WHERE a.MOMaterialsID='" + body.SourceDetailID + "'";
                        DataTable dtQty = DBHelper.SQlReturnData(sql, cmd);
                        //    if (dtQty != null && dtQty.Rows.Count > 0)
                        //    {
                        //        //可超领比率
                        //        decimal fOutExcess = Convert.ToDecimal(dtQty.Rows[0]["fOutExcess"]);
                        //        //已领数量
                        //        decimal IssQty = Convert.ToDecimal(dtQty.Rows[0]["IssQty"]);
                        //        //应领数量
                        //        decimal Qty = Convert.ToDecimal(dtQty.Rows[0]["iQuantity"]);
                        //        //当前可总领数量
                        //        decimal TotalQty = Qty + fOutExcess * Qty;
                        //        if (head.IsReturn != "1")
                        //        {
                        //            if (IssQty + body.Quantity > TotalQty)
                        //            {
                        //                throw new Exception("物料领取超过当前可领用最大数,AllocateId:" + body.SourceDetailID);
                        //            }
                        //        }
                        //        else
                        //        {
                        //            if (IssQty < body.Quantity)
                        //            {
                        //                throw new Exception("物料退料超过当前已领用最大数,AllocateId:" + body.SourceDetailID);
                        //            }
                        //        }
                        //    }
                        //    else
                        //    {
                        //        throw new Exception("委外订单行子件不存在!AllocateId:" + body.SourceDetailID);
                        //    }
                        //}
                    }
                    #endregion
                    #region 委外材料出库单表头

                        sql = @"
                            INSERT INTO dbo.rdrecord11
                            ( ID ,bRdFlag ,cVouchType ,cBusType ,cSource ,
                            cWhCode ,dDate ,cCode ,cRdCode ,cDepCode,
                            cPersonCode,cHandler ,bTransFlag ,cMaker ,dVeriDate ,
                            bpufirst ,biafirst ,VT_ID ,bIsSTQc ,cPsPcode ,
                            cMPoCode ,iproorderid ,bFromPreYear ,bIsLsQuery ,bIsComplement ,
                            iDiscountTaxType ,ireturncount ,iverifystate ,iswfcontrolled ,dnmaketime ,
                            dnverifytime ,bredvouch ,iPrintCount,cVenCode,iMQuantity)

                            SELECT distinct @ID,0,'11','委外发料','委外订单',
                            @cWhCode,CONVERT(NVARCHAR(15),GETDATE(),23),@cCode,'22',c.cDepCode,
                            c.cPersonCode,@cHandler,0,@cMaker,CONVERT(NVARCHAR(15),GETDATE(),23),
                            0,0,@VT_ID,0,b.cInvCode,
                            c.cCode,a.MoId,0,0,0,
                            0,0,0,0,GETDATE(),
                            GETDATE(),0,0,c.cVenCode,b.iQuantity
                            from dbo.OM_MOMaterials a
                            INNER JOIN dbo.OM_MODetails b ON a.MoDetailsID = b.MoDetailsID 
                            LEFT JOIN dbo.OM_MOMain c ON b.MOID = c.MOID               
                            WHERE a.MOMaterialsID='" + head.details[0].SourceDetailID + "'";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                        cmd.Parameters.Add(new SqlParameter("@cWhCode", head.WHCode));
                        cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
                        cmd.Parameters.Add(new SqlParameter("@cHandler", head.User));
                        cmd.Parameters.Add(new SqlParameter("@cMaker", head.User));
                        cmd.Parameters.Add(new SqlParameter("@VT_ID", iChildId));
                        cmd.CommandText = sql;
                        try
                        {
                            int count = cmd.ExecuteNonQuery();
                            if (count <= 0)
                            {
                                log.Error("生成委外发料单表头失败,受影响行数<=0;");
                                throw new Exception("生成委外发料单表头失败,受影响行数<=0;");
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Error("生成委外发料单表头失败!SQL:\r\n" + sql, ex);
                            throw new Exception("生成委外发料单表头失败!SQL:\r\n" + sql, ex);
                        }

                  
                        #endregion
                    #region 委外材料出库单表体
                
                    string iNQuantity = "";
                    foreach (ICSOutsourcingIssueDocs body in head.details)
                    {
                        //if (head.IsReturn == "1")
                        //{
                        //    body.iQuantity = -body.iQuantity;
                        //    iNQuantity = "-a.iQuantity";
                        //}
                        //else
                        //{
                        iNQuantity = "a.iQuantity";
                        //}
                        //if (head.IsReturn == "0")
                        //{
                        //    //判断物料批号与现存量表批号是否一致、数量不能超过现存量物料数量
                        //    sql = @"SELECT cBatch,iQuantity from CurrentStock WHERE cInvCode='" + body.cInvCode + "'AND cBatch='" + body.cBatch + "'and cWhCode='" + head.cWhCode + "'";
                        //    DataTable dtItem = U8Helper.SQlReturnData(sql, cmd);
                        //    if (dtItem != null && dtItem.Rows.Count > 0)
                        //    {
                        //        if (!dtItem.Rows[0]["cBatch"].ToString().Equals(body.cBatch))
                        //        {
                        //            throw new Exception("物料条码的批号与U8现存量物料批号不一致,物料:" + body.cInvCode);
                        //        }
                        //        if (Convert.ToDecimal(dtItem.Rows[0]["iQuantity"].ToString()) < body.iQuantity)
                        //        {
                        //            throw new Exception("物料条码的数量大于U8现存量物料数量,物料:" + body.cInvCode);
                        //        }
                        //    }
                        //    else
                        //    {
                        //        throw new Exception("物料:" + body.cInvCode + "在现存量表中不存在!");
                        //    }
                        //}
                        sql = @"INSERT INTO dbo.rdrecords11
                                ( AutoID,ID ,cInvCode,iQuantity ,cBatch ,
                                iFlag ,cItemCode ,cName ,iNQuantity ,iMPoIds ,
                                bLPUseFree ,iOriTrackID ,bCosting ,bVMIUsed ,cmocode ,
                                invcode ,imoseq ,iopseq ,iExpiratDateCalcu ,iorderdid ,
                                iordertype ,isotype ,ipesodid ,ipesotype ,cpesocode ,
                                ipesoseq ,irowno ,bcanreplace ,iposflag,iOMoDID,
                                iOMoMID,comcode)

                                SELECT distinct
                                @AutoID,@ID,@InvCode,@iQuantity,@cBatch,
                                0,null,null,@iQuantity,NULL,
                                0,0,1,0,NULL,
                                b.cInvCode,NULL,NULL,0,0,
                                0,0,a.MOMaterialsID,'6',c.cCode,
                                NULL, @irowno,0,NULL,b.MODetailsID,
                                a.MOMaterialsID,c.cCode
                                FROM dbo.OM_MOMaterials a
                                INNER JOIN dbo.OM_MODetails b ON a.MoDetailsID=b.MODetailsID
                                INNER JOIN dbo.OM_MOMain c ON b.MOID=c.MOID
                                WHERE a.MOMaterialsID='" + body.SourceDetailID + "'";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId));
                        cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
                        cmd.Parameters.Add(new SqlParameter("@iQuantity", body.Quantity));
                        //cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
                        cmd.Parameters.Add(new SqlParameter("@InvCode", body.InvCode));
                        cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
                        cmd.Parameters.Add(new SqlParameter("@irowno", body.Sequence));
                        cmd.Parameters.Add(new SqlParameter("@iNQuantity", iNQuantity));
                        cmd.CommandText = sql;
                        try
                        {
                            int count = cmd.ExecuteNonQuery();
                            if (count <= 0)
                            {
                                log.Error("生成委外发料单表体失败,受影响行数<=0;");
                                throw new Exception("生成委外发料单表体失败,受影响行数<=0;");
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Error("生成委外发料单表体失败" + sql, ex);
                            throw new Exception("生成委外发料单表体失败 " + sql, ex);
                        }
                        iFatherIdTwo += "'" + iFatherId + "',";
                        //更新现存量
                        key.cBustypeUN = "委外发料";
                        key.cVouchTypeUN = "11";
                        key.TableName = "IA_ST_UnAccountVouch11";
                        DBHelper.UpdateCurrentStock(cmd, body.InvCode, head.WHCode, "", -body.Quantity, key);
                        #region 回写工单子件已领数量
                        sql = "update OM_MOMaterials set iSendQTY=isnull(iSendQTY,0)+" + body.Quantity + " where MOMaterialsID='" + body.SourceDetailID + "' ";
                        DBHelper.CmdExecuteNonQuery(sql, cmd, "回写委外订单子件已领数量失败!");
                        #endregion
                        iChildId--;
                    }
                    #endregion
                }
                #region 查询
                sql = @"select a.ID as ID,a.ID as IDs,a.cCode as IssueCode,a.cDepCode,c.cDepName,a.cWhCode,
                            d.cWhName,a.cSource,cMPoCode,a.cMaker,dnmaketime,cHandler,dnverifytime 
                            from rdrecord11 a
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                           where a.cBusType='委外发料'and a.ID in ({0})

                     select a.ID as IDs,iOMoMID  as SourceDetailID ,b.irowno as Sequence,iordercode,b.cInvCode,b.iQuantity,b.iNum,b.AutoID as DetailID
                            from rdrecord11 a
                            left join rdrecords11 b on a.ID=b.ID
                            left join Department c on a.cDepCode=c.cDepCode
                            left join Warehouse d on a.cWhCode=d.cWhCode
                            left join OM_MODetails e on b.iOMoDID=e.MoDetailsID
                           where a.cBusType='委外发料'and a.ID in ({0})";
                sql = string.Format(sql, iFatherIdTwo.TrimEnd(','));
                DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd);
                string RelationName = "details";
                DataRelation dr = new DataRelation(RelationName, ds.Tables[0].Columns["IDs"], ds.Tables[1].Columns["IDs"]);
                ds.Relations.Add(dr);
//                sql = @" select a.ID as ID,iMPoIds,iordercode,b.irowno as Sequence,a.cCode as IssueCode,a.cDepCode,c.cDepName,a.cWhCode,
//                            d.cWhName,a.cSource,a.cMaker,dnmaketime,cHandler,dnverifytime,cSourceCodeLs,
//                            b.AutoID as DetailID ,b.irowno,b.cInvCode,b.iQuantity,e.MoDetailsID,b.iNum,e.csocode
//                            from rdrecord11 a
//                            left join rdrecords11 b on a.ID=b.ID
//                            left join Department c on a.cDepCode=c.cDepCode
//                            left join Warehouse d on a.cWhCode=d.cWhCode
//                            left join OM_MODetails e on b.iOMoDID=e.MoDetailsID
//                           where a.cBusType='委外发料'and a.ID in ({0})";
//                sql = string.Format(sql, iFatherIdTwo.TrimEnd(','));
//                dt = DBHelper.SQlReturnData(sql, cmd);
                #endregion
                cmd.Transaction.Commit();
                msg = DBHelper.DataSetToJson(ds, RelationName);
                return msg;
            }
            catch (Exception ex)
            {
                cmd.Transaction.Rollback();
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
                conn.Dispose();
            }
        }
        public string Approve(List<ICSOutsourcingIssueDoc> infos)
        {
            List<ICSOutsourcingIssueDoc> szJson = new List<ICSOutsourcingIssueDoc>();
            DataTable dt = null;
            string json = "";
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空!");
            }
            string res = string.Empty;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
            conn.Open();
            SqlTransaction sqlTran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = conn;
            try
            {
                string sql = string.Empty;
                foreach (ICSOutsourcingIssueDoc info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @"UPDATE  dbo.rdrecord11 SET cHandler ='" + info.User + @"' ,
                            dnmodifytime  =CONVERT(VARCHAR(50),GETDATE(),112),dModifyDate  =GETDATE() WHERE ID='{0}'";
                    sql = string.Format(sql, info.ID);
                    DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据!");
                }
                cmd.Transaction.Commit();
                return json;
            }
            catch (Exception ex)
            {
                cmd.Transaction.Rollback();
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
                conn.Dispose();
            }
        }
        /// <summary>
        /// 删除请购单
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public string Delete(List<ICSOutsourcingIssueDoc> infos)
        {
            List<ICSOutsourcingIssueDoc> szJson = new List<ICSOutsourcingIssueDoc>();
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空!");
            }
            string res = string.Empty;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
            conn.Open();
            SqlTransaction sqlTran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Transaction = sqlTran;
            cmd.Connection = conn;
            try
            {
                string sql = string.Empty;
                foreach (ICSOutsourcingIssueDoc info in infos)
                {
                    if (info.MTime < new DateTime(2000, 01, 01))
                        throw new Exception("请输入正确的操作时间:" + info.MTime);
                    sql = @" DELETE dbo.rdrecord11 WHERE ID='{0}'";
                    sql = string.Format(sql, info.ID);
                    DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据!");
                }
                cmd.Transaction.Commit();
                return res;
                ;
            }
            catch (Exception ex)
            {
                cmd.Transaction.Rollback();
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
                conn.Dispose();
            }
        }
        /// <summary>
        /// 
        /// 记录日志
        /// </summary>
        /// <param name="Bills"></param>
        private void LogInfo(List<ICSOutsourcingIssueDoc> Bills)
        {
            string HeadList = string.Empty;
            string BodyList = string.Empty;
            foreach (ICSOutsourcingIssueDoc head in Bills)
            {
                HeadList += "\r\n 表头主键ID:" + head.ID + ",仓库:" + head.WHCode + ",用户:" + head.User;
                foreach (ICSOutsourcingIssueDocs body in head.details)
                {
                    BodyList += "\r\n 表体主键ID: " + body.SourceDetailID + ",数量:" + body.Quantity;
                }
            }
            log.Info(HeadList);
            log.Info(BodyList);
        }
    }
}