public ActionResult Create(string Key, String PositionId, int PipeTypeId, int SentCount)
        {
            Account onlineAccount = UserSession.OnlineAccount;

            IPipeRepository pipeRepository = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>(unitOfWork);
            IPipeTypeRepository ptRepository = RepositoryFactory.GetRepository<IPipeTypeRepository, PipeType>(unitOfWork);

            if (PositionId == null)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("找不到目标垛位,垛位调度任务单({0})添加失败!", Key), DisappearDelay = 5000, Type = HintMessageType.Error };
            }
            PipePosition Position = RepositoryFactory.GetRepository<IPipePositionRepository, PipePosition>().FindBy(PositionId);
            if (PipeTypeId <1)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("找不到应该调度的管材型号,垛位调度任务单({0})添加失败!", Key), DisappearDelay = 5000, Type = HintMessageType.Error };
            }
            PipeType pt = ptRepository.FindBy(PipeTypeId);

            Key = onlineAccount.DetectionCompany.Code + Key;
            TransferNotice notice = new TransferNotice(Key, onlineAccount.DetectionCompany, pt, Position,onlineAccount, DateTime.Now);
            notice.SentCount = SentCount;
            notice.State = TransferNoticeState.Created;

            if (repository.FindByNotCache(Key) != null)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("垛位调度任务单号{0}已存在,请尝试使用其他编号", Key) };
                TempData["InvalidModel"] = notice;
            }
            else
            {
                repository.Add(notice);
                unitOfWork.Commit();

                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("垛位调度任务单({0})添加成功", Key), DisappearDelay = 5000 };
            }

            return RedirectToAction("Add");
        }
        public ActionResult Verify(string id)
        {
            OutgoingNotice notice = repository.FindByNotCache(id);
            if (notice == null)
            {
                throw new HttpException(404, "无法找到指定的发料通知单");
            }

            if (notice.State == OutgoingNoticeState.Done)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("发料通知单({0})不能重复审核", notice.Key), DisappearDelay = 5000, Type = HintMessageType.Error };
            }

            DateTime now = DateTime.Now;
            notice.State = OutgoingNoticeState.Done;
            notice.Verifier = UserSession.OnlineAccount;
            notice.DateVerified = now;
            repository[notice.Key] = notice;

            IPipeRepository pipeRepository = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>(unitOfWork);
            IPipeOutgoingRecordRepository porRepository = RepositoryFactory.GetRepository<IPipeOutgoingRecordRepository, PipeOutgoingRecord>(unitOfWork);

            porRepository.VerifyNoticeRecords(notice);
            unitOfWork.Commit();

            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("发料通知单({0})审核通过成功", notice.Key), DisappearDelay = 5000 };
            return RedirectToAction("Detail", new { id = id });
        }
        public ActionResult CancleVerify(string id)
        {
            OutgoingNotice notice = repository.FindByNotCache(id);
            if (notice == null)
            {
                throw new HttpException(404, "无法找到指定的发料通知单");
            }

            if (notice.State != OutgoingNoticeState.Done)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "未达到取消审核的条件,取消审核状态失败", DisappearDelay = 5000, Type = HintMessageType.Error };
                return RedirectToAction("Detail", new { id = id });
            }

            System.Data.DataTable dt = repository.FindByCount(notice);
            if (dt.Rows.Count == 0)
            {
                foreach (PipeOutgoingRecord record in notice.Records)
                {
                    PDCPMS.Model.Common.Pipe pipe = record.Pipe;
                    repository.CancleVerify(notice, pipe);
                }
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "取消审核成功", DisappearDelay = 5000, Type = HintMessageType.Normal };
            }
            else
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "该单子的管子状态已经发生改变,不能取消审核,请联系管理员", DisappearDelay = 5000, Type = HintMessageType.Normal };
            }

            return RedirectToAction("Detail", new { id = id });
        }
        public ActionResult Create(string Key, String DiggerId, int PipeTypeId, float Need, string Project, string Instruction)
        {
            IPipeRepository pipeRepository = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>(unitOfWork);
            IPipeTypeRepository ptRepository = RepositoryFactory.GetRepository<IPipeTypeRepository, PipeType>(unitOfWork);

            if (DiggerId == null)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("页面信息丢失,发料通知单({0})添加失败!", Key), DisappearDelay = 5000, Type = HintMessageType.Error };
            }

            PipeType pt = ptRepository.FindBy(PipeTypeId);
            //Digger digger = RepositoryFactory.GetRepository<IDiggerRepository, Digger>().FindBy(DiggerId);
            Digger digger = RepositoryFactory.GetRepository<IDiggerRepository, Digger>().FindNoCache(DiggerId);

            if (digger == null && digger.Name==null)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("找不到井名,发料通知单({0})添加失败!", Key), DisappearDelay = 5000, Type = HintMessageType.Error };
            }

            Account onlineAccount = UserSession.OnlineAccount;

            Key = onlineAccount.DetectionCompany.Code + Key;
            OutgoingNotice notice = new OutgoingNotice(Key, onlineAccount.DetectionCompany, pt, digger, onlineAccount, DateTime.Now);
            notice.Need = Need;
            notice.Project = Project;
            notice.Instruction = Instruction;
            notice.State = OutgoingNoticeState.Created;

            if (repository.FindByNotCache(Key) != null)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("发料通知单号{0}已存在,请尝试使用其他编号", Key) };
                TempData["InvalidModel"] = notice;
            }
            if (digger == null || onlineAccount == null || pt == null)
            {
                TempData["InvalidModel"] = notice;
                TempData["InvalidModel"] = notice;

                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("发料通知单({0})添加失败!", Key), DisappearDelay = 5000, Type = HintMessageType.Error };
            }
            else
            {
                repository.Add(notice);
                unitOfWork.Commit();

                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("发料通知单({0})添加成功", Key), DisappearDelay = 5000 };
            }

            return RedirectToAction("Add");
        }
        public ActionResult Update()
        {
            string diggerid = Request.Form["diggerid"];
            string key=Request.Form["id"];
            string pipetypeid = Request.Form["pipetypeid"];
            string Need = Request.Form["Need"];
            string Project = Request.Form["Project"];
            string Instruction = Request.Form["Instruction"];

            StringBuilder sb = new StringBuilder();

            sb.Append(" update outgoingnotice set diggerid='");
            sb.Append(diggerid);
            sb.Append("',pipetypeid=");
            sb.Append(pipetypeid);
            sb.Append(",need=");
            sb.Append(Need);
            sb.Append(",project='");
            sb.Append(Project);
            sb.Append("',instruction='");
            sb.Append(Instruction);
            sb.Append("' where outgoingnoticeid='");
            sb.Append(key + "'");

            IOutgoingNoticeRepository update = RepositoryFactory.GetRepository<IOutgoingNoticeRepository, OutgoingNotice>();
            update.Excute(sb.ToString());
            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("成功更新发料通知单({0})", key) };

            return RedirectToAction("Index");
        }
        public JsonResult Create(int noticeId)
        {
            BusinessCheckNotice businessCheckNotice = RepositoryFactory.GetRepository<IBusinessCheckNoticeRepository, BusinessCheckNotice>().FindBy(noticeId);
            if (businessCheckNotice == null)
            {
                return Json(new { success = false, message = "商检单不存在" });
            }

            PipeIncomeRecord incomeRecord = repository.FindBy(businessCheckNotice);
            if (incomeRecord != null)
            {
                return Json(new { success = false, message = "已制作了该商检任务的入库单,不能重量制作" });
            }

            string code = Request.Form["Code"];
            string unit = Request.Form["Unit"];
            string strPipes = Request.Form["Pipes"];

            if (string.IsNullOrEmpty(code))
            {
                return Json(new { success = false, message = "编码不能为空" });
            }
            incomeRecord = repository.FindBy(code);
            if (incomeRecord != null)
            {
                return Json(new { success = false, message = "编号已被占用,请尝试使用其他编号" });
            }

            businessCheckNotice.Waggons = RepositoryFactory.GetRepository<IDeliverWaggonRepository, DeliverWaggon>().FindBy(businessCheckNotice);

            #region scarface
            // IList<PDCPMS.Model.Common.Pipe> pipes = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>().FindBy(businessCheckNotice.Waggons);
            #endregion

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            IList<PDCPMS.DataContracts.Common.Pipe> pipeContracts = serializer.Deserialize<IList<PDCPMS.DataContracts.Common.Pipe>>(strPipes);
            IPipeRepository pipeRepository = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>(unitOfWork);
            IPipePositionRepository posRepository = RepositoryFactory.GetRepository<IPipePositionRepository, PipePosition>();

            incomeRecord = new PipeIncomeRecord(0, code, businessCheckNotice, UserSession.OnlineAccount, DateTime.Now);
            incomeRecord.State = PipeIncomeRecordState.Created;
            repository.Add(incomeRecord);

            unitOfWork.Commit();

            #region scarface
            //for (int i = pipes.Count - 1; i > -1; i--)
            //{
            //    PDCPMS.Model.Common.Pipe pipe = pipes[i];
            //    PDCPMS.DataContracts.Common.Pipe pc = pipeContracts.FirstOrDefault(p => p.Key == (long)pipe.Key);
            //    if (pc != null)
            //    {
            //        if (pc.BusinessLength != 0)
            //        {
            //            pipe.BusinessLength = pc.BusinessLength;
            //        }
            //        else
            //        {
            //            pipe.BusinessLength = new float?();
            //        }

            //        if (pc.Weight != 0)
            //        {
            //            pipe.Weight = pc.Weight;
            //        }
            //        else
            //        {
            //            pipe.Weight = new float?();
            //        }

            //        //if ((pipe.State & PipeState.NormalChecking) == PipeState.NormalChecking) // 已发起了常检则不允许更改垛位
            //        //{
            //        //}
            //        //else
            //        //{
            //            if (pc.PositionId != 0)
            //            {
            //                pipe.Position = posRepository.FindBy(pc.PositionId);
            //            }
            //        //}
            //    }

            //    pipe.State |= PipeState.IncomeRecordDoing;
            //    pipe.PipeIncomeRecord = incomeRecord;
            //    pipeRepository[pipe.Key] = pipe;
            //};

            //incomeRecord.TotalCount = businessCheckNotice.ReceiveCount;
            //incomeRecord.TotalLength = pipes.Sum(p => p.BusinessLength.HasValue ? p.BusinessLength.Value : 0);
            //incomeRecord.TotalWeight = pipes.Sum(p => p.Weight.HasValue ? p.Weight.Value : 0) / 1000;
            #endregion

            #region 2010-11-12 scarface 新增代码

            //获取前台Json的值遍历生产SQL
            StringBuilder sb = new StringBuilder();
            DateTime now = DateTime.Now;
            Oracle.DataAccess.Client.OracleConnection conn = new Oracle.DataAccess.Client.OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["PDCPDMConnection"].ConnectionString);
            CY.Utility.DBUtility.OracleUtility db = new CY.Utility.DBUtility.OracleUtility(conn);
            conn.Open();
            Oracle.DataAccess.Client.OracleTransaction tran = conn.BeginTransaction();
            try
            {
                sb.Append(" update Pipe set PipeIncomeRecordId = " + incomeRecord.Key + ",");
                sb.Append(string.Format(" state = (state + {0} - bitand(state,{0})),", (int)PipeState.IncomeRecordDoing));
                sb.Append(" PosLastChangeTime = to_date('" + now + "', 'yyyy-mm-dd HH24:mi:ss') ");
                IList<DeliverWaggon> waggons = businessCheckNotice.Waggons;
                if (waggons == null)
                {
                    throw new ArgumentNullException("waggons");
                }
                string waggonIds = string.Empty;
                for (int i = waggons.Count - 1; i > -1; i--)
                {
                    waggonIds += OracleDataHelper.GetSqlValue(waggons[i].Key);

                    if (i != 0)
                    {
                        waggonIds += ",";
                    }
                }
                sb.Append(string.Format(" Where DeliverWaggonId in ({0})", waggonIds));
                db.ExecuteSql(sb.ToString());

                for (int i = pipeContracts.Count - 1; i > -1; i--)
                {
                    sb = new StringBuilder();
                    sb.Append(" UPDATE Pipe  SET ");
                    sb.Append(" BusinessLength = " + pipeContracts[i].BusinessLength + ",");
                    sb.Append(" Weight = " + pipeContracts[i].Weight + ",");
                    sb.Append(" PosLastChangeTime = to_date('" + now + "', 'yyyy-mm-dd HH24:mi:ss'),");
                    sb.Append(" PositionId = " + pipeContracts[i].PositionId);
                    sb.Append(" WHERE PipeId = " + pipeContracts[i].Key + "");

                    db.ExecuteSql(sb.ToString());
                }
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                return Json(new { success = false, message = "管子信息保存出错!"+ex });
            }
            finally
            {
                if (conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                }
            }

            //查询并统计数据
            sb = new StringBuilder();
            sb.Append(" SELECT SUM(BUSINESSLENGTH) AS lh ,SUM(WEIGHT)/1000 AS wt,count(*) as c FROM Pipe WHERE PIPEINCOMERECORDID = " + incomeRecord.Key + "");
            DataTable dt = pipeRepository.ExcuteDs(sb.ToString());
            float tl = dt.Rows[0]["lh"].ToString() == "" ? 0 : float.Parse(dt.Rows[0]["lh"].ToString());
            float tw = dt.Rows[0]["wt"].ToString() == "" ? 0 : float.Parse(dt.Rows[0]["wt"].ToString());
            int tc = dt.Rows[0]["c"].ToString() == "" ? 0 : int.Parse(dt.Rows[0]["c"].ToString());

            sb = new StringBuilder();
            sb.Append(" UPDATE Pipeincomerecord SET totalcount=" + tc + ",TOTALLENGTH = " + tl + ",TOTALWEIGHT = " + tw + " WHERE PIPEINCOMERECORDID = " + incomeRecord.Key + "");
            //只执行一次查询 就更新数据库表
            pipeRepository.Execute(sb.ToString());

            #endregion

            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "保存成功" };
            return Json(new { success = true, message = "保存成功", recordId = incomeRecord.Key });
        }
        public ActionResult Add(int noticeId)
        {
            if (TempData["HintMessage"] != null)
            {
                ViewData["HintMessage"] = TempData["HintMessage"];
            }

            BusinessCheckNotice businessCheckNotice = RepositoryFactory.GetRepository<IBusinessCheckNoticeRepository, BusinessCheckNotice>().FindBy(noticeId);
            if (businessCheckNotice == null)
            {
                throw new HttpException(404, "商检单不存在");
            }

            PipeIncomeRecord incomeRecord = repository.FindBy(businessCheckNotice);
            if (incomeRecord != null)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "不能重复制作入库单", Type = Application.HintMessageType.Error, DisappearDelay = 5000 };
                return RedirectToAction("Detail", new { id = incomeRecord.Key });
            }

            DeliverNotice deliverNotice = businessCheckNotice.DeliverNotice;
            PipeQualityCertification pqc = RepositoryFactory.GetRepository<IPipeQualityCertificationRepository, PipeQualityCertification>().FindBy(deliverNotice);
            if (pqc == null)
            {
                Session["RedirectUrl"] = Url.Action("Add", new { noticeId = noticeId });
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "请先添加质证书" };
                return RedirectToAction("Add", "QualityCertification", new { noticeId = deliverNotice.Key });
            }

            IList<DeliverWaggon> deliverNoticeWaggons = RepositoryFactory.GetRepository<IDeliverWaggonRepository, DeliverWaggon>().FindBy(deliverNotice);
            IList<DeliverWaggon> incomeDoneWaggons = new List<DeliverWaggon>(); // 已收料
            IList<DeliverWaggon> incomeDoingWaggons = new List<DeliverWaggon>(); // 收料时行中,未审核完成
            IList<DeliverWaggon> notIncomeWaggons = new List<DeliverWaggon>(); // 已提检,尚未做收料
            IList<DeliverWaggon> notBusinessCheckWaggons = new List<DeliverWaggon>(); // 尚未发起提检、可能未到货
            IList<PipeIncomeRecord> incomeDoneRecords = new List<PipeIncomeRecord>();
            foreach (DeliverWaggon w in deliverNoticeWaggons)
            {
                BusinessCheckNotice bcn = w.BusinessCheckNotice;
                if (bcn == null)
                {
                    notBusinessCheckWaggons.Add(w);
                }
                else
                {
                    PipeIncomeRecord pir = repository.FindBy(bcn);
                    if (pir == null)
                    {
                        notIncomeWaggons.Add(w);
                    }
                    else
                    {
                        if (pir.State == PipeIncomeRecordState.Verified)
                        {
                            incomeDoneWaggons.Add(w);

                            if (incomeDoneRecords.Where(r => (int)r.Key == (int)pir.Key).Count() == 0)
                                incomeDoneRecords.Add(pir);
                        }
                        else
                        {
                            incomeDoingWaggons.Add(w);
                        }
                    }
                }
            }

            ViewData["deliverNoticeWaggons"] = deliverNoticeWaggons;
            ViewData["incomeDoneWaggons"] = incomeDoneWaggons;
            ViewData["incomeDoingWaggons"] = incomeDoingWaggons;
            ViewData["notIncomeWaggons"] = notIncomeWaggons;
            ViewData["notBusinessCheckWaggons"] = notBusinessCheckWaggons;
            ViewData["incomeDoneRecords"] = incomeDoneRecords;

            ViewData["BusinessCheckNotice"] = businessCheckNotice;
            businessCheckNotice.Waggons = RepositoryFactory.GetRepository<IDeliverWaggonRepository, DeliverWaggon>().FindBy(businessCheckNotice);
            ViewData["Positions"] = RepositoryFactory.GetRepository<IPipePositionRepository, PipePosition>().Find(businessCheckNotice.DeliverNotice.Company, PipePositionType.NotGiven, int.MaxValue - 1, 1);

            int pageIndex = 1;
            int pageSize = 100;
            int recordCount = 0;
            ViewData["PageSize"] = pageSize;
            if (!string.IsNullOrEmpty(Request.QueryString["p"]))
            {
                int p;
                if (int.TryParse(Request.QueryString["p"], out p))
                    if (p > 0)
                        pageIndex = p;
            }
            ViewData["PageIndex"] = pageIndex;

            //ViewData["Pipes"] = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>().FindBy(businessCheckNotice.Waggons);

            ViewData["PipesDs"] = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>().FindBy(businessCheckNotice.Waggons, pageSize, pageIndex, ref recordCount);
            ViewData["RecordCount"] = recordCount;
            ViewData["QualityCertification"] = pqc;

            return View();
        }
        public JsonResult UpdateTask(string code, string items,string team,string faxno,string diggerid)
        {
            NormalCheckTask task = repository.FindByCode(code);
            if (task == null)
            {
                throw new HttpException(404, "未找到指定常检任务");
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("update normalchecktask set diggerid='");
            sb.Append(diggerid + "',team='"+team+"',faxno='"+faxno+"'");
            sb.Append(" where normalchecktaskid='");
            sb.Append(task.Key.ToString()+"'");

            INormalCheckTaskRepository edit = RepositoryFactory.GetRepository<INormalCheckTaskRepository, NormalCheckTask>();
            edit.Excute(sb.ToString());
            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("成功修改常检任务({0})", code) };
            return Json(new { success = true, taskId = code });
        }
        public ActionResult Verify(string code)
        {
            NormalCheckTask task = repository.FindByCode(code);
            if (task == null)
            {
                throw new HttpException(404, "未找到指定常检任务");
            }

            if (!task.CanBeVerified)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "未达到审核条件,审核失败", DisappearDelay = 5000, Type = HintMessageType.Error };
                return RedirectToAction("Detail", new { code = code });
            }

            task.Verifer = UserSession.OnlineAccount;
            task.DateVerified = DateTime.Now;
            task.State = NormalCheckTaskState.Verified;
            repository[task.Key] = task;

            IPipeRepository pipeRepository = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>(unitOfWork);
            INormalCheckResultRepository resultRepositoryFactory = RepositoryFactory.GetRepository<INormalCheckResultRepository, NormalCheckResult>(unitOfWork);

            //task.Records.ForEach<NormalCheckRecord>(r =>
            //{
            //    PDCPMS.Model.Common.Pipe p = r.Pipe;

            //    totalCommerceLength += p.BusinessLength.HasValue ? (p.BusinessLength == null ? 0 : p.BusinessLength.Value) : 0;
            //    totalWorkLength += p.WorkLength.HasValue ? (p.WorkLength == null ? 0 : p.WorkLength.Value) : 0;

            //    if (r.IsValid.HasValue && r.IsValid.Value)
            //    {
            //        if ((p.State & PipeState.CheckInvalid) == PipeState.CheckInvalid)
            //        {
            //            p.State ^= PipeState.CheckInvalid;
            //        }

            //        p.State |= PipeState.CheckValid;

            //        validCount += 1;

            //        validCommerceLength += p.BusinessLength.HasValue ? (p.WorkLength == null ? 0 : p.WorkLength.Value) : 0;
            //        validWorkLength += p.WorkLength.HasValue ? (p.WorkLength == null ? 0 : p.WorkLength.Value) : 0;
            //    }
            //    else
            //    {
            //        if ((p.State & PipeState.CheckValid) == PipeState.CheckValid)
            //        {
            //            p.State ^= PipeState.CheckValid;
            //        }

            //        p.State |= PipeState.CheckInvalid;
            //    }

            //    pipeRepository[p.Key] = p;
            //});

            //查找工作总长度
            DataTable dtTotal = pipeRepository.GetNormalCheckTaskPipeTotalData(task);
            //查找合格的工作总长度
            DataTable dtValid = pipeRepository.GetNormalCheckTaskPipeValidData(task);

            //totalCommerceLength = Convert.ToSingle(dtTotal.Rows[0]["BusinessLength"]);
            //validWorkLength = Convert.ToSingle(dtValid.Rows[0]["BusinessLength"]);

            ////2010-12-02 by hunherby
            //pipeRepository.BackToPipeBy(task, pipe);

            //2010-10-21 by huncherby

            float totalCommerceLength = 0;
            float totalWorkLength = 0;
            float validCommerceLength = 0;
            float validWorkLength = 0;
            int validCount = 0;
            //总的
            totalCommerceLength = Convert.ToSingle(dtTotal.Rows[0]["BusinessLength"] == DBNull.Value ? "0" : dtTotal.Rows[0]["BusinessLength"].ToString());
            totalWorkLength = Convert.ToSingle(dtTotal.Rows[0]["WorkLength"] == DBNull.Value ? "0" : dtTotal.Rows[0]["WorkLength"].ToString());
            //合格的
            validCommerceLength = Convert.ToSingle(dtValid.Rows[0]["BusinessLength"] == DBNull.Value ? "0" : dtValid.Rows[0]["BusinessLength"].ToString());
            validWorkLength = Convert.ToSingle(dtValid.Rows[0]["WorkLength"] == DBNull.Value ? "0" : dtValid.Rows[0]["WorkLength"].ToString());
            validCount = Convert.ToInt32(dtValid.Rows[0]["count(*)"]);

            NormalCheckResult result = new NormalCheckResult(
                task.Key.ToString(),
                task,
                task.Count.Value,
                totalWorkLength,
                validCount,
                validWorkLength,
                totalWorkLength - validWorkLength,
                task.Verifer,
                task.DateVerified.Value);
            result.TotalCommerceLength = totalCommerceLength;
            result.ValidCommerceLength = validCommerceLength;
            result.InValidCommerceLength = totalCommerceLength - validCommerceLength;

            resultRepositoryFactory.Add(result);

            unitOfWork.Commit();

            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "审核成功", DisappearDelay = 5000, Type = HintMessageType.Normal };
            return RedirectToAction("Detail", new { code = code });
        }
        public JsonResult Update(string code, string items)
        {
            #region 基本信息
            if (string.IsNullOrEmpty(code))
            {
                return Json(new { success = false, message = "未指定常检任务单" });
            }

            NormalCheckTask task = repository.FindByCode(code);

            if (string.IsNullOrEmpty(items))
            {
                return Json(new { success = false, message = "未指定调度项" });
            }

            IList<PDCPMS.DataContracts.Transfer.TransferItem> transferItemContracts;
            transferItemContracts = new JavaScriptSerializer().Deserialize<IList<PDCPMS.DataContracts.Transfer.TransferItem>>(items);

            if (transferItemContracts.Count < 1)
            {
                return Json(new { success = false, message = "未指定调度项" });
            }

            PipeType pipeType = null;
            //Digger targetDigger = null;
            if (Convert.ToInt32(task.PipeType.Key) < 1)
            {
                return Json(new { success = false, message = "未指定管材类型" });
            }
            pipeType = RepositoryFactory.GetRepository<IPipeTypeRepository, PipeType>().FindBy(task.PipeType.Key);

            if (pipeType == null)
            {
                return Json(new { success = false, message = "未指定管材类型" });
            }

            #endregion

            ITransferTaskRepository transferTaskRepository = RepositoryFactory.GetRepository<ITransferTaskRepository, TransferTask>(unitOfWork);
            ITransferItemRepository transferItemRepository = RepositoryFactory.GetRepository<ITransferItemRepository, TransferItem>(unitOfWork);
            ITransferRecordRepository transferRecordRepository = RepositoryFactory.GetRepository<ITransferRecordRepository, TransferRecord>(unitOfWork);
            IPipePositionRepository posRepository = RepositoryFactory.GetRepository<IPipePositionRepository, PipePosition>();
            IPipeRepository pipeRepository = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>(unitOfWork);

            System.Data.DataTable dt2 = retory.FindNormalCheckRecords(task);
            int j = 0;
            StringBuilder sb = new StringBuilder();
            sb.Append("Begin ");

            foreach (PDCPMS.DataContracts.Transfer.TransferItem tic in transferItemContracts)
            {
                PipePosition prePos = posRepository.FindBy(tic.PrevPosId);
                PipePosition newPos = posRepository.FindBy(tic.NewPosId);

                System.Data.DataTable dt = pipeRepository.FindByMyCondition(prePos, pipeType, PipeState.Received | PipeState.Storing, PipeState.Transfering | PipeState.NormalChecking);

                if (prePos == null || newPos == null || tic.Count < 0)
                {
                    return Json(new { success = false, message = "你的调度项输入有误" });
                }

                TransferItem item = new TransferItem(Guid.NewGuid().ToString("N"), task.TransferTask);

                item.PrevPos = prePos;
                item.NewPos = newPos;
                item.Count = tic.Count;

                //改变数量
                //retory.AddNormalCheck(task, TotalCount);

                sb.Append("update normalchecktask set count=count+");
                sb.Append(tic.Count);
                sb.Append(" where normalchecktaskid='");
                sb.Append(task.Key.ToString()+"';");

                sb.Append("update transfertask set totalcount=totalcount+");
                sb.Append(tic.Count);
                sb.Append(" where TransferTaskid='");
                sb.Append(task.TransferTask.Key.ToString() + "';");

                if (dt.Rows.Count < tic.Count)
                {
                    return Json(new { success = false, message = string.Format("调度失败:垛位({0})已无{1}根可检测的存货,可能已经被调至别处", prePos.ToString(), tic.Count) });
                }
                #region 新增常检任务

                //新增transferitem
                string TransferItemId = Guid.NewGuid().ToString("N");
                string TransferTaskId_Forignkey = task.TransferTask.Key.ToString();
                //int Count = TotalCount;
                string PrevPositionId = item.PrevPos.Key.ToString();
                string NewPositionId = item.NewPos.Key.ToString();
                System.Data.DataTable dt1 = transferItemRepository.FindTransfer(task, item);

                if (dt1.Rows.Count > 0)
                {
                    sb.Append("update transferitem set count=count+");
                    sb.Append(tic.Count);
                    sb.Append(" where TransferTaskid='");
                    sb.Append(task.TransferTask.Key.ToString() + "' and prevpositionid=");
                    sb.Append(dt1.Rows[0]["PrevPositionId"].ToString() + ";");
                }
                else
                {
                    sb.Append("Insert Into TransferItem(TransferItemId, TransferTaskId, Count, PrevPositionId, NewPositionId)Values(");
                    sb.Append("'" + TransferItemId + "',");
                    sb.Append("'" + TransferTaskId_Forignkey + "',");
                    sb.Append("" + tic.Count + ",");
                    sb.Append("'" + PrevPositionId + "',");
                    sb.Append("'" + NewPositionId + "');");
                }
                 for (int i = 0; i < tic.Count; i++)
                {
                    j++;
                    //新增TransferRecord
                    string TransferRecordId = Guid.NewGuid().ToString("N");
                    string TransferItemId_key = dt1.Rows[0]["TransferItemId"].ToString();
                    string DateCreated = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    string PrevPositionId_Record = item.PrevPos.Key.ToString();
                    string NewPositionId_Record = item.NewPos.Key.ToString();
                    string PipeId = dt.Rows[i]["pipeid"].ToString();

                    sb.Append("Insert Into TransferRecord(TransferRecordId,TransferItemId,DateCreated,DateFinished,PrevPositionId,NewPositionId,PipeId)Values(");
                    sb.Append("'" + TransferRecordId + "',");
                    sb.Append("'" + TransferItemId_key + "',");
                    sb.Append("to_date('" + DateCreated + "', 'yyyy-mm-dd HH24:mi:ss'),");
                    sb.Append("null,");
                    sb.Append("'" + PrevPositionId_Record + "',");
                    sb.Append("'" + NewPositionId_Record + "',");
                    sb.Append("'" + PipeId + "');");

                    //更新pipe
                    sb.Append("update Pipe set state = (state + ");

                    if (task.State == NormalCheckTaskState.Created)
                    {

                        sb.Append((int)PipeState.Transfering);
                        sb.Append(" - bitand(state, ");
                        sb.Append((int)PipeState.Transfering);
                        sb.Append(" ))");
                    }
                    else
                    {
                        sb.Append((int)PipeState.NormalChecking);
                        sb.Append(" - bitand(state, ");
                        sb.Append((int)PipeState.NormalChecking);
                        sb.Append(")),positionid = ");
                        sb.Append("'" + NewPositionId_Record + "',");
                        sb.Append(" prevposid= ");
                        sb.Append("'" + PrevPositionId_Record + "',poslastchangetime=");
                        sb.Append("to_date('" + DateCreated + "', 'yyyy-mm-dd HH24:mi:ss')");
                    }

                    sb.Append(" Where PipeId = ");
                    sb.Append(dt.Rows[i]["PipeId"].ToString() + ";");

                    if ((int)task.State >= (int)NormalCheckTaskState.Received && task.Approver != null)
                    {
                        int orderno = Convert.ToInt32(dt2.Rows[0]["max(orderno)"]) + j;
                        //新增Normalcheckrecords记录
                        string normalchecktaskid = Guid.NewGuid().ToString("N");

                        sb.Append("Insert Into normalcheckrecord(normalcheckrecordid,pipeid,normalchecktaskid,datecreated,orderno ) Values (");

                        sb.Append("'" + normalchecktaskid + "',");
                        sb.Append("'" + PipeId + "',");
                        sb.Append("'" + task.Key + "',");
                        sb.Append("to_date('" + DateCreated + "', 'yyyy-mm-dd HH24:mi:ss'),");
                        sb.Append("'" + orderno.ToString() + "' );");
                    }

                }
            }
            #endregion

            sb.Append(" End;");

            INormalCheckTaskRepository AddNCK = RepositoryFactory.GetRepository<INormalCheckTaskRepository, NormalCheckTask>();
            AddNCK.Excute(sb.ToString());

            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "成功新增常检任务记录!" };
            return Json(new { success = true ,code=task.Code});
        }
        public ActionResult CheckResults(string code)
        {
            NormalCheckTask task = repository.FindByCode(code);

            if (task == null)
            {
                throw new HttpException(404, "未找到指定常检任务");
            }

            if ((int)task.State < (int)NormalCheckTaskState.Received)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("常检任务({0})尚未接收,暂不能维护检测数据", code), DisappearDelay = 5000, Type = HintMessageType.Error };
                return RedirectToAction("Detail", new { code = code });
            }
            if (task.State == NormalCheckTaskState.Verified)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("常检任务({0})已审核存档,不允许被编辑", code), DisappearDelay = 5000, Type = HintMessageType.Error };
                return RedirectToAction("Detail", new { code = code });
            }

            if (TempData["HintMessage"] != null)
            {
                ViewData["HintMessage"] = TempData["HintMessage"];
            }
            //List<NormalCheckRecord> normalCheckRecord = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>().FindByReturnDs(task, pageSize, pageIndex);
            //task.Records = normalCheckRecord;

            //2010-11-7 BY huncherby 分页
            #region
            int pageIndex = 1;
            int pageSize = 60;
            //int count = 0;
            ViewData["PageSize"] = pageSize;
            if (!string.IsNullOrEmpty(Request.QueryString["p"]))
            {
                int p;
                if (int.TryParse(Request.QueryString["p"], out p))
                    if (p > 0)
                        pageIndex = p;
            }
            ViewData["PageIndex"] = pageIndex;
            #endregion

            ViewData["totalcounts"] = RepositoryFactory.GetRepository<INormalCheckRecordRepository, NormalCheckRecord>().FindByNomalchecktotal(task);

            ViewData["workno"] = RepositoryFactory.GetRepository<INormalCheckRecordRepository, NormalCheckRecord>().workno(task);

            ViewData["NormalCheckRecord"] = RepositoryFactory.GetRepository<INormalCheckRecordRepository, NormalCheckRecord>().FindBy(task, pageIndex, pageSize);
            //task.Records = records;
            return View(task);
        }
        public ActionResult Receive(string code)
        {
            NormalCheckTask task = repository.FindByCode(code);
            if (task == null)
            {
                throw new HttpException(404, "未找到指定常检任务");
            }

            //if (!task.TransferTask.IsFinished)
            if (task.State != NormalCheckTaskState.Transferd)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("常检任务({0})尚未发货,暂不能接收", code), DisappearDelay = 5000, Type = HintMessageType.Error };
                return RedirectToAction("Detail", new { code = code });
            }

            if (task.Receiver != null && task.DateReceived.HasValue)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("不能重复接收常检任务({0})", code), DisappearDelay = 5000, Type = HintMessageType.Error };
                return RedirectToAction("Detail", new { code = code });
            }

            if (TempData["HintMessage"] != null)
            {
                ViewData["HintMessage"] = TempData["HintMessage"];
            }

            if (TempData["InvalidModel"] != null)
            {
                NormalCheckTask t = TempData["InvalidModel"] as NormalCheckTask;
                if (t != null)
                {
                    return View(t);
                }
            }

            return View(task);
        }
        public ActionResult MainCheckerSign(string code)
        {
            NormalCheckTask task = repository.FindByCode(code);
            if (task == null)
            {
                throw new HttpException(404, "未找到指定常检任务");
            }

            if (task.Finisher == null)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "该任务尚未录入检测数据,主检暂不能签字", DisappearDelay = 5000, Type = HintMessageType.Error };
                return RedirectToAction("Detail", new { code = code });
            }

            if (task.MainChecker != null)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "该任务主检已签字,不能重复签字", DisappearDelay = 5000, Type = HintMessageType.Error };
                return RedirectToAction("Detail", new { code = code });
            }

            task.MainChecker = UserSession.OnlineAccount;
            repository[task.Key] = task;
            unitOfWork.Commit();

            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "主检已签字成功", DisappearDelay = 5000, Type = HintMessageType.Normal };
            return RedirectToAction("Detail", new { code = code });
        }
        public ActionResult CancleVerify(string code)
        {
            NormalCheckTask task = repository.FindByCode(code);
            if (task == null)
            {
                throw new HttpException(404, "未找到指定常检任务");
            }

            if (task.State != NormalCheckTaskState.Verified)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "未达到取消审核的条件,取消审核状态失败", DisappearDelay = 5000, Type = HintMessageType.Error };
                return RedirectToAction("Detail", new { code = code });
            }

            repository.CancleVerify(task);
            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "取消审核成功", DisappearDelay = 5000, Type = HintMessageType.Normal };
            return RedirectToAction("Detail", new { code = code });
        }
        public ActionResult Verify(int id)
        {
            PipeIncomeRecord record = repository.FindByNotCache(id);
            if (record == null)
            {
                throw new HttpException(404, "入库单不存在");
            }

            //IList<PDCPMS.Model.Common.Pipe> pipes = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>().FindBy(record);

            bool canVerify =  record.State == PDCPMS.Model.Income.PipeIncomeRecordState.Created &&
                //record.BusinessCheckNotice.State == PDCPMS.Model.Income.BusinessCheckNoticeState.Done &&
                record.Keeper != null &&
                record.Clerk != null &&
                record.Measurer != null &&
                (record.Verifier == null);

            if (!canVerify)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "入库单暂不允许被审核或已经审核通过", Type = HintMessageType.Error, DisappearDelay = 5000 };
            }
            else
            {
                IPipeTypeRepository ptRepository = RepositoryFactory.GetRepository<IPipeTypeRepository, PipeType>(unitOfWork);
                IPipeRepository pipeRepository = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>(unitOfWork);

                PipeType pt = record.PipeType;

                //2010-11-16 by huncherby 直接赋值0
                pt.AvgWeiht = (pt.AvgWeiht * pt.TotalCount + (double)record.TotalWeight * record.TotalCount / (double)record.TotalLength) / (pt.TotalCount + record.TotalCount);
                //pt.AvgWeiht = 0;

                pt.TotalCount += record.TotalCount;
                pt.TotalLength += (decimal)record.TotalLength;
                pt.TotalWeight += (decimal)record.TotalWeight;
                ptRepository[pt.Key] = pt;

                record.Verifier = UserSession.OnlineAccount;
                record.VerifyTime = DateTime.Now;
                record.State = PipeIncomeRecordState.Verified;

                repository[record.Key] = record;

                //for (int i =0, j = pipes.Count; i < j; i++)
                //{
                //    PDCPMS.Model.Common.Pipe pipe = pipes[i];

                //    pipe.State |= PipeState.IncomeRecordDone;
                //    pipe.State |= PipeState.Storing;

                //    pipeRepository[pipe.Key] = pipe;
                //}

                // Li Zheng 2010.11.18
                pipeRepository.VerifyPipeBy(record);

                unitOfWork.Commit();

                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "入库单审核成功", Type = HintMessageType.Normal, DisappearDelay = 15000 };
            }

            return RedirectToAction("Detail", new { id = id });
        }
        public JsonResult CreateTask(int pipeTypeId, String code, String diggerId,String team,String faxno, String items)
        {
            string pipeneednoticeitemid = Request.Form["needlength"].ToString();
            PipeType pipeType = null;
            Digger targetDigger = null;
            IList<PDCPMS.DataContracts.Transfer.TransferItem> transferItemContracts;
            Account onlineAccount = UserSession.OnlineAccount;

            #region Get Basic Data

            if (onlineAccount.DetectionCompany == null) { return Json(new { success = false, message = "你无权发起常检任务" }); }

            if (string.IsNullOrEmpty(code))
            {
                return Json(new { success = false, message = "编号不能为空" });
            }
            Regex codePattern = new Regex("^[-|a-z|A-Z|0-9]+$");
            if (!codePattern.IsMatch(code))
            {
                return Json(new { success = false, message = "编号格式不正确,只能为英文字母、数字或者短横线(-)的组合" });
            }

            if (null != repository.FindByCode(code))
            {
                return Json(new { success = false, message = string.Format("编号为{0}的常检任务存在,请尝试使用其他编号", code) });
            }

            if (string.IsNullOrEmpty(items))
            {
                return Json(new { success = false, message = "未指定调度项" });
            }
            transferItemContracts = new JavaScriptSerializer().Deserialize<IList<PDCPMS.DataContracts.Transfer.TransferItem>>(items);
            if (transferItemContracts.Count < 1)
            {
                return Json(new { success = false, message = "未指定调度项" });
            }

            if (pipeTypeId < 1)
            {
                return Json(new { success = false, message = "未指定管材类型" });
            }
            pipeType = RepositoryFactory.GetRepository<IPipeTypeRepository, PipeType>().FindBy(pipeTypeId);

            if (pipeType == null)
            {
                return Json(new { success = false, message = "未指定管材类型" });
            }
            if (!string.IsNullOrEmpty(diggerId))
            {
                targetDigger = RepositoryFactory.GetRepository<IDiggerRepository, Digger>().FindBy(diggerId);
            }

            #endregion

            ITransferTaskRepository transferTaskRepository = RepositoryFactory.GetRepository<ITransferTaskRepository, TransferTask>(unitOfWork);
            ITransferItemRepository transferItemRepository = RepositoryFactory.GetRepository<ITransferItemRepository, TransferItem>(unitOfWork);
            ITransferRecordRepository transferRecordRepository = RepositoryFactory.GetRepository<ITransferRecordRepository, TransferRecord>(unitOfWork);
            IPipePositionRepository posRepository = RepositoryFactory.GetRepository<IPipePositionRepository, PipePosition>();
            IPipeRepository pipeRepository = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>(unitOfWork);
            DateTime now = DateTime.Now;

            StringBuilder sb = new StringBuilder();
            sb.Append("Begin ");
            TransferTask transferTask = new TransferTask(Guid.NewGuid().ToString("N"), pipeType, onlineAccount.DetectionCompany, onlineAccount, now, true);

            #region 我的修改insert TransferTask
            string TransferTaskId = Guid.NewGuid().ToString("N");
            string DateCreated = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string CreatorId = onlineAccount.Key.ToString();
            int TotalCount = transferItemContracts[0].Count;
            string PipeTypeId = pipeTypeId.ToString();
            string DetectionCompanyId = onlineAccount.DetectionCompany.Key.ToString();
            sb.Append("Insert Into TransferTask(TransferTaskId,IsSystemTask,DateCreated,CreatorId,IsFinished,DateFinished,TotalCount,PipeTypeId,DetectionCompanyId,\"Comment\")Values(");
            sb.Append("'" + TransferTaskId + "',");
            sb.Append("1,");
            sb.Append("to_date('" + DateCreated + "', 'yyyy-mm-dd HH24:mi:ss'),");
            sb.Append("'" + CreatorId + "',");
            sb.Append("0,");
            sb.Append("null,");
            sb.Append("" + TotalCount + ",");
            sb.Append("'" + PipeTypeId + "',");
            sb.Append("'" + DetectionCompanyId + "',");
            sb.Append("'');");
            #endregion
            TotalCount = 0;

            foreach (PDCPMS.DataContracts.Transfer.TransferItem tic in transferItemContracts)
            {
                PipePosition prePos = posRepository.FindBy(tic.PrevPosId);
                PipePosition newPos = posRepository.FindBy(tic.NewPosId);

                if (prePos == null || newPos == null || tic.Count < 0)
                {
                    return Json(new { success = false, message = "你的调度项输入有误" });
                }

                TransferItem item = new TransferItem(Guid.NewGuid().ToString("N"), transferTask);

                item.PrevPos = prePos;
                item.NewPos = newPos;
                item.Count = tic.Count;

                #region 我的修改 TransferItem Insert
                string TransferItemId = Guid.NewGuid().ToString("N");
                string TransferTaskId_Forignkey = TransferTaskId;
                int Count = TotalCount;
                string PrevPositionId = item.PrevPos.Key.ToString();
                string NewPositionId = item.NewPos.Key.ToString();
                sb.Append("Insert Into TransferItem(TransferItemId, TransferTaskId, Count, PrevPositionId, NewPositionId)Values(");
                sb.Append("'" + TransferItemId + "',");
                sb.Append("'" + TransferTaskId_Forignkey + "',");
                sb.Append("" + tic.Count + ",");
                sb.Append("'" + PrevPositionId + "',");
                sb.Append("'" + NewPositionId + "');");
                #endregion

                System.Data.DataTable dt = pipeRepository.FindByMyCondition(prePos, pipeType, PipeState.Received | PipeState.Storing, PipeState.Transfering | PipeState.NormalChecking);

                if (dt.Rows.Count < tic.Count)
                {
                    return Json(new { success = false, message = string.Format("调度失败:垛位({0})已无{1}根可检测的存货,可能已经被调至别处", prePos.ToString(), tic.Count) });
                }
                for (int i = 0; i < tic.Count; i++)
                {
                    #region 我改的 TransferRecord Insert
                    string TransferRecordId = Guid.NewGuid().ToString("N");
                    string TransferItemId_ForignKey = TransferItemId;
                    string DateCreated_Record = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    string PrevPositionId_Record = item.PrevPos.Key.ToString();
                    string NewPositionId_Record = item.NewPos.Key.ToString();
                    string PipeId = dt.Rows[i]["pipeid"].ToString();

                    sb.Append("Insert Into TransferRecord(TransferRecordId,TransferItemId,DateCreated,DateFinished,PrevPositionId,NewPositionId,PipeId)Values(");
                    sb.Append("'" + TransferRecordId + "',");
                    sb.Append("'" + TransferItemId_ForignKey + "',");
                    sb.Append("to_date('" + DateCreated + "', 'yyyy-mm-dd HH24:mi:ss'),");
                    sb.Append("null,");
                    sb.Append("'" + PrevPositionId_Record + "',");
                    sb.Append("'" + NewPositionId_Record + "',");
                    sb.Append("'" + PipeId + "');");

                    //2010-12-01 by huncherby  发起常检任务改变状态
                    sb.Append("update Pipe set state = (state + ");
                    sb.Append((int)PipeState.Transfering);
                    sb.Append(" - bitand(state, ");
                    sb.Append((int)PipeState.Transfering);
                    sb.Append(" )) Where PipeId = ");

                    sb.Append(dt.Rows[i]["PipeId"].ToString());
                    sb.Append(";");

                    #endregion
                }
                TotalCount += item.Count;
                transferTask.TotalCount += item.Count;
            }

            NormalCheckTask ncTask = new NormalCheckTask(Guid.NewGuid().ToString("N"), code, onlineAccount.DetectionCompany, pipeType, targetDigger, transferTask, onlineAccount, now);

            #region 我的修改 NormalCheckTask Insert
            string NormalCheckTaskId = Guid.NewGuid().ToString("N");
            string PipeTypeId_ForignKey = PipeTypeId;
            string DetectionCompanyId_ForignKey = DetectionCompanyId;
            string DiggerId = diggerId;
            string TransferTaskId_ForignKey = TransferTaskId;
            string Code = code;
            string DateCreated_NCTask = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            int Count_NCTask = TotalCount;
            //string pipeneednoticeitemid = null;

            sb.Append("Insert Into NormalCheckTask(NormalCheckTaskId,PipeTypeId,DetectionCompanyId,DiggerId,TransferTaskId,State,Code,WorkNO,CreatorId,DateCreated,SenderId,DateSent,ReceiverId,DateReceived,CheckItemCreatorId,CheckItemDateCreated,Count,CheckStandard,IsNeedMark,IsCheckAppearance,IsCheckThickness,IsCheckLength,IsNeedWash,IsCheckUnBlock,IsCheckPressure,CheckPressureType,IsCheckCloseness,IsCheckBodyCrack,CheckBodyCrackType,IsCheckBlindCrack,\"Comment\",FinisherId,DateFinished,CheckTools,CheckConclusion,ReportComment,MainCheckId,VeriferId,DateVerified,ApproverId,DateApproved,ReportNO,team,faxno,pipeneednoticeitemid)Values(");
            sb.Append("'" + NormalCheckTaskId + "',");
            sb.Append("'" + PipeTypeId_ForignKey + "',");
            sb.Append("'" + DetectionCompanyId_ForignKey + "',");
            sb.Append("'" + diggerId + "',");
            sb.Append("'" + TransferTaskId_ForignKey + "',");
            sb.Append("0,");
            sb.Append("'" + Code + "',");
            sb.Append("'',");
            sb.Append("'" + CreatorId + "',");
            sb.Append("to_date('" + DateCreated_NCTask + "', 'yyyy-mm-dd HH24:mi:ss'),");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("'" + Count_NCTask + "',");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("-1,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("-1,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,");
            sb.Append("null,'"+team+"','"+faxno+"',");
            sb.Append("'" + pipeneednoticeitemid + "');");
            sb.Append(" End;");
            #endregion
            INormalCheckTaskRepository NCTaskR = RepositoryFactory.GetRepository<INormalCheckTaskRepository, NormalCheckTask>();
            NCTaskR.Excute(sb.ToString());
            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("成功发起常检任务({0})", Code) };
            return Json(new { success = true, taskId = Code });
        }
        public ActionResult CancleVerify(int id)
        {
            PipeIncomeRecord record = repository.FindByNotCache(id);
            if (record == null)
            {
                throw new HttpException(404, "入库单不存在");
            }

            bool canVerify = record.State == PDCPMS.Model.Income.PipeIncomeRecordState.Verified &&
                (record.Verifier != null);

            if (!canVerify)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "入库单暂不允许被取消审核", Type = HintMessageType.Error, DisappearDelay = 5000 };
            }
            else
            {
                IPipeTypeRepository ptRepository = RepositoryFactory.GetRepository<IPipeTypeRepository, PipeType>(unitOfWork);
                IPipeRepository pipeRepository = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>(unitOfWork);

                PipeType pt = record.PipeType;
                if (pt.TotalCount - record.TotalCount != 0)
                {
                    pt.AvgWeiht = (pt.AvgWeiht * pt.TotalCount - (double)record.TotalWeight * record.TotalCount / (double)record.TotalLength) / (pt.TotalCount - record.TotalCount);
                }
                pt.TotalCount -= record.TotalCount;
                pt.TotalLength -= (decimal)record.TotalLength;
                pt.TotalWeight -= (decimal)record.TotalWeight;
                ptRepository[pt.Key] = pt;

                record.Verifier = null;
                record.VerifyTime = null;
                record.State = PipeIncomeRecordState.Created;

                repository[record.Key] = record;

                pipeRepository.VerifyPipeBy(record);

                unitOfWork.Commit();

                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "入库单取消审核成功", Type = HintMessageType.Normal, DisappearDelay = 15000 };
            }

            return RedirectToAction("Detail", new { id = id });
        }
        public ActionResult DeleteNCT(string code)
        {
            NormalCheckTask task = repository.FindByCode(code);

            if (task == null)
            {
                throw new HttpException(404, "无法找到指定常检任务单");
            }

            if (task.State != NormalCheckTaskState.Created && task.State != NormalCheckTaskState.Transferd)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "常检单已被批准检测,不允许删除", Type = HintMessageType.Error };
                return RedirectToAction("Index");
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Begin ");

                //还原管材状态

                sb.Append(" update pipe set state=(state - bitand(state, ");

                if (task.State == NormalCheckTaskState.Created)
                {
                    sb.Append((int)PipeState.Transfering);
                    sb.Append(" )) ");
                }
                else if(task.State == NormalCheckTaskState.Transferd)
                {
                    sb.Append((int)PipeState.NormalChecking);
                    sb.Append(" )) ");
                    sb.Append(" ,positionid=prevposid,prevposid=null,poslastchangetime=null ");
                }

                sb.Append(" Where pipeId in (select c.pipeid from transfertask a,transferitem b, transferrecord c, normalchecktask d where a.transfertaskid = d.transfertaskid and a.transfertaskid = b.transfertaskid and b.transferitemid = c.transferitemid and d.normalchecktaskid ='");

                sb.Append(task.Key.ToString());
                sb.Append("');");

                //sb = new StringBuilder();

                // 删除信息
                sb.Append("delete from transferrecord where transferitemid in (select transferitemid from transferitem where transfertaskid='");
                sb.Append(task.TransferTask.Key.ToString());
                sb.Append("');");

                //sb = new StringBuilder();

                sb.Append(" delete from TransferItem where TransferTaskid='");
                sb.Append(task.TransferTask.Key.ToString());
                sb.Append("';");

                //sb = new StringBuilder();

                sb.Append(" delete from TransferTask where TransferTaskid='");
                sb.Append(task.TransferTask.Key.ToString());
                sb.Append("';");

                //sb = new StringBuilder();

                sb.Append(" delete from normalchecktask where normalchecktaskid='");
                sb.Append(task.Key.ToString());
                sb.Append("';");

                sb.Append(" End;");

                INormalCheckTaskRepository NCK = RepositoryFactory.GetRepository<INormalCheckTaskRepository, NormalCheckTask>();

                NCK.Excute(sb.ToString());

                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = String.Format("常检任务(#{0})删除成功", task.Code) };
            }

            return RedirectToAction("Index");
        }
        public ActionResult DeleteIncome(int id)
        {
            PipeIncomeRecord record = repository.FindByNotCache(id);
            if (record == null)
            {
                throw new HttpException(404, "无法找到指定收料单");
            }

            if (record.State != PipeIncomeRecordState.Created)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "收料单已被签字,不允许删除", Type = HintMessageType.Error };
                return RedirectToAction("Index");
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                //sb.Append("begin ");

                sb.Append(" update pipe set state=(state-bitand(state, ");
                sb.Append((int)PipeState.IncomeRecordDoing);
                sb.Append(" )), BusinessLength = null");
                sb.Append(" ,Weight = null");
                sb.Append(" ,PosLastChangeTime = null");
                sb.Append(" ,PositionId =14 ");
                //sb.Append(" ,pipeincomerecordid=null");
                sb.Append(" WHERE pipeincomerecordid = ");
                sb.Append(record.Key);
                sb.Append(";");

                IPipeRepository pipeRepository = RepositoryFactory.GetRepository<IPipeRepository, PDCPMS.Model.Common.Pipe>();
                pipeRepository.Executeincome(sb.ToString());

                sb = new StringBuilder();

                //删除收料单信息
                sb.Append("delete from pipeincomerecord where pipeincomerecordid= ");
                sb.Append(record.Key.ToString());

                //sb.Append(" end;");

                IPipeIncomeRecordRepository income = RepositoryFactory.GetRepository<IPipeIncomeRecordRepository, PipeIncomeRecord>();

                income.Excute(sb.ToString());

                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = String.Format("收料单(#{0})删除成功", record.Key) };
            }

            return RedirectToAction("Index");
        }
        //2010-12-08 by huncherby 删除流转卡
        public ActionResult DeleteReceive(string code)
        {
            NormalCheckTask task = repository.FindByCode(code);
            System.Data.DataTable dt= retory.Findcounts(task);
            if (task == null)
            {
                throw new HttpException(404, "未找到指定常检任务");
            }
            if (task.State != NormalCheckTaskState.Received)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "流转卡已被审核通过,不允许删除", Type = HintMessageType.Error };
                return RedirectToAction("Index");
            }
            else
            {
                if (dt.Rows.Count == 0)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("begin ");

                    //删除流转卡信息
                    sb.Append(" update normalchecktask set state= ");
                    sb.Append((int)NormalCheckTaskState.Transferd);
                    sb.Append(",workno=null,reportno=null,receiverid=null,datereceived=null,checkitemcreatorid=null, checkitemdatecreated=null,checkstandard=null,isneedmark=null,ischeckappearance=null,ischeckthickness=null,ischecklength=null,isneedwash=null,ischeckunblock=null,ischeckpressure=null,ischeckcloseness=null,ischeckbodycrack=null,ischeckblindcrack=null,checktools=null,approverid=null where normalchecktaskid ='");
                    sb.Append(task.Key.ToString());
                    sb.Append("';");

                    sb.Append(" update pipe set code=null,worklength=null where code like '%"+task.WorkNO+"%';");

                    sb.Append(" delete from normalcheckrecord where normalchecktaskid ='");
                    sb.Append(task.Key.ToString());
                    sb.Append("';");

                    sb.Append(" end;");
                    INormalCheckTaskRepository NCK = RepositoryFactory.GetRepository<INormalCheckTaskRepository, NormalCheckTask>();

                    NCK.Excute(sb.ToString());

                    TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = String.Format("流转卡(#{0})删除成功", task.Code) };
                }
                else
                {
                    TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "已有检测数据,请先清空检测数据所有的工序号并保存才允许删除", Type = HintMessageType.Error };
                    return RedirectToAction("Index");
                }

            }

            return RedirectToAction("Index");
        }
        public ActionResult MeasurerSign(int id)
        {
            PipeIncomeRecord record = repository.FindByNotCache(id);
            if (record == null)
            {
                throw new HttpException(404, "入库单不存在");
            }

            if (record.Measurer != null)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "计量员已经签过字了,不能重复签字", Type = HintMessageType.Error, DisappearDelay = 5000 };
            }
            else
            {
                record.Measurer = UserSession.OnlineAccount;
                repository[record.Key] = record;

                unitOfWork.Commit();

                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "计量员签字成功" };
            }

            return RedirectToAction("Detail", new { id = id });
        }
        public ActionResult DoReceive(string code, string WorkNO,
            Boolean IsCheckAppearance,
            Boolean IsNeedWash,
            Boolean IsNeedMark,
            Boolean IsCheckLength,
            Boolean IsCheckThickness,
            Boolean IsCheckUnBlock,
            Boolean IsCheckBodyCrack,
            Boolean IsCheckBlindCrack,
            Boolean IsCheckPressure,
            Boolean IsCheckCloseness,
            CheckBodyCrackType CheckBodyCrackType,
            CheckPressureType CheckPressureType)
        {
            NormalCheckTask task = repository.FindByCode(code);
            if (task == null)
            {
                throw new HttpException(404, "未找到指定常检任务");
            }

            //if (!task.TransferTask.IsFinished)
            if (task.State != NormalCheckTaskState.Transferd)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("常检任务({0})尚未发货,暂不能接收", code), DisappearDelay = 5000, Type = HintMessageType.Error };
                return RedirectToAction("Detail", new { code = code });
            }

            if (task.Receiver != null && task.DateReceived.HasValue)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("不能重复接收常检任务({0})", code), DisappearDelay = 5000, Type = HintMessageType.Error };
                return RedirectToAction("Detail", new { code = code });
            }

            task.IsCheckAppearance = IsCheckAppearance;
            task.IsNeedWash = IsNeedWash;
            task.IsNeedMark = true;
            task.IsCheckLength = IsCheckLength;
            task.IsCheckThickness = IsCheckThickness;
            task.IsCheckUnBlock = IsCheckUnBlock;
            task.IsCheckBodyCrack = IsCheckBodyCrack;
            task.IsCheckBlindCrack = IsCheckBlindCrack;
            task.IsCheckPressure = IsCheckPressure;
            task.IsCheckCloseness = IsCheckCloseness;

            if (task.IsCheckBodyCrack.Value)
            {
                task.CheckBodyCrackType = CheckBodyCrackType;
            }
            else
            {
                task.CheckBodyCrackType = Model.NormalCheck.CheckBodyCrackType.NotGiven;
            }

            if (task.IsCheckPressure.Value)
            {
                task.CheckPressureType = CheckPressureType;
            }
            else
            {
                task.CheckPressureType = Model.NormalCheck.CheckPressureType.NotGiven;
            }

            task.Comment = Request.Form["Comment"];
            task.CheckStandard = Request.Form["CheckStandard"];
            task.Samplingmethod = Request.Form["Samplingmethod"];
            task.CheckTools = Request.Form["CheckTools"];

            if (string.IsNullOrEmpty(WorkNO))
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "工序号不能为空", Type = HintMessageType.Error, DisappearDelay = 5000 };
                TempData["InvalidModel"] = task;
                return RedirectToAction("Detail", new { code = code });
            }

            if (null != repository.FindByWorkNO(task.Company.Code + WorkNO))
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("工序号({0})已经存在", WorkNO), Type = HintMessageType.Error, DisappearDelay = 5000 };
                TempData["InvalidModel"] = task;
                return RedirectToAction("Detail", new { code = code });
            }

            task.WorkNO = task.Company.Code + WorkNO;
            task.State = NormalCheckTaskState.Received;
            task.CheckItemCreator = task.Receiver = UserSession.OnlineAccount;
            task.CheckItemDateCreated = task.DateReceived = DateTime.Now;

            repository[task.Key] = task;

            unitOfWork.Commit();

            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "创建流转卡成功" };

            return RedirectToAction("Detail", new { code = code });
        }
        public ActionResult Records(string id)
        {
            //OutgoingNotice notice = repository.FindBy(id);
            OutgoingNotice notice = repository.FindByNotCache(id);

            if (notice == null)
            {
                throw new HttpException(404, "无法找到指定的发料通知单");
            }

            if (notice.State == OutgoingNoticeState.Done)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("发料通知单({0})已完成,不能进行编辑", notice.Key) };
                return RedirectToAction("Detail", new { id = id });
            }

            if (TempData["HintMessage"] != null)
            {
                ViewData["HintMessage"] = TempData["HintMessage"];
            }

            #region 资阳上线修改-发料 2011-3-7 by huncherby
            Account onlineAccount = UserSession.OnlineAccount;
            #endregion

            string workno = Request.QueryString["workno"];

            ViewData["workno"] = RepositoryFactory.GetRepository<INormalCheckTaskRepository, NormalCheckTask>().Findworkno(notice,onlineAccount);
            //右边
            ViewData["Commen"] = RepositoryFactory.GetRepository<INormalCheckRecordRepository, NormalCheckRecord>().FindByoutgoing(notice,workno,onlineAccount);

            return View(notice);
        }
        public ActionResult Create([ModelBinder(typeof(QualityCertificationModelBinder))]PipeQualityCertification model, int noticeId)
        {
            DeliverNotice notice = RepositoryFactory.GetRepository<IDeliverNoticeRepository, DeliverNotice>().FindBy(noticeId);
            if (notice == null)
            {
                throw new HttpException(404, "来料单不存在");
            }

            PipeQualityCertification pqc = repository.FindBy(notice);
            if (pqc != null)
            {
                return RedirectToAction("Detail", new { id = pqc.Key });
            }

            #region Attachment

            Regex fileReg = new Regex(@"(?<name>.*)\.(jpe?g|gif|bmp|png)$", RegexOptions.IgnoreCase);
            HttpPostedFileBase attachmentFile = Request.Files["Attachment"] as HttpPostedFileBase;
            if (attachmentFile != null)
            {
                if (fileReg.IsMatch(attachmentFile.FileName))
                {
                    string absolutPathDir = "/UserFiles/PipeQualityCertification/";
                    string filePath = Server.MapPath(absolutPathDir);
                    string fileName = noticeId + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + (new Random(DateTime.Now.Second)).Next(1, 999).ToString("000");

                    DirectoryInfo di = new DirectoryInfo(filePath);
                    if (!di.Exists)
                        di.Create();

                    string prevName = attachmentFile.FileName;
                    prevName = fileReg.Replace(prevName, new MatchEvaluator(delegate(Match m)
                    {
                        return m.ToString().Replace(m.Groups["name"].Value, fileName);
                    }));

                    attachmentFile.SaveAs(filePath + prevName);
                    model.AttachmentPath = absolutPathDir + prevName;
                }
            }

            #endregion

            ReadOnlyCollection<BrokenRule> brokenRules = model.GetBrokenRules();

            if (brokenRules.Count == 0)
            {
                repository.Add(model);
                unitOfWork.Commit();

                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "质证书添加成功" };
            }
            else
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "你的输入有误,质证书添加失败" };
                TempData["BrokenRules"] = brokenRules;
                TempData["InvalidModel"] = model;
            }

            if (Session["RedirectUrl"] != null)
            {
                string url = Session["RedirectUrl"].ToString();
                Session["RedirectUrl"] = null;
                return Redirect(url);
            }

            return RedirectToAction("Detail", "QualityCertification", new { id = model.Key });
        }
        public ActionResult UpdateTotal()
        {
            string id = Request.Form["Key"];
            string sl = Request.Form["SentBusinessLength"];
            string sw = Request.Form["SentWeight"];
            string length = Request.Form["SentWorklength"];
            string count=Request.Form["SentCount"];

            StringBuilder sb = new StringBuilder();

            sb.Append(" update outgoingnotice set SentBusinessLength='" + sl + "',SentWeight='" + sw + "',SentWorklength='" + length + "',SentCount='"+count+"' where outgoingnoticeid='" + id + "'");

            IOutgoingNoticeRepository update = RepositoryFactory.GetRepository<IOutgoingNoticeRepository, OutgoingNotice>();
            update.Excute(sb.ToString());
            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("成功更新发料单({0})", id) };

            return RedirectToAction("Index");
        }
        public ActionResult Delete(string id)
        {
            if (TempData["HintMessage"] != null)
            {
                ViewData["HintMessage"] = TempData["HintMessage"];
            }

            PipeQualityCertification pqc = repository.FindByNotCache(id);
            if (pqc == null)
            {
                throw new HttpException(404, "质证书不存在");
            }

            if (pqc.AttachmentPath != null)
            {
                string fileName = Server.MapPath(pqc.AttachmentPath);
                System.IO.FileInfo fi = new System.IO.FileInfo(fileName);
                if (fi.Exists)
                {
                    fi.Delete();
                }
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("delete from  pipequalitycertification where pipequalitycertificationid='" + id + "'");

            repository.Excute(sb.ToString());

            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = String.Format("质证书{0}删除成功", pqc.Code) };
            return RedirectToAction("Index","DeliverNotice");
        }
        public ActionResult DeleteOutgoingNotice(string id)
        {
            OutgoingNotice notice = repository.FindByNotCache(id);
            IList<PipeOutgoingRecord> record = recordRepository.FindBy(notice);

            if (notice == null)
            {
                throw new HttpException(404, "无法找到指定的发料通知单");
            }

            if (notice.State != OutgoingNoticeState.Created)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "发料通知单已被接收,不允许删除", Type = HintMessageType.Error };
                return RedirectToAction("Index");
            }
            else
            {
                if (record.Count != 0)
                {
                    TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = "该发料单已经添加维护记录,不允许删除!", Type = HintMessageType.Error };
                    return RedirectToAction("Index");
                }
                else
                {
                    StringBuilder sb = new StringBuilder();

                    sb.Append(" delete from outgoingnotice where outgoingnoticeid='");
                    sb.Append(notice.Key.ToString());
                    sb.Append("'");

                    IOutgoingNoticeRepository outgoingnotice = RepositoryFactory.GetRepository<IOutgoingNoticeRepository, OutgoingNotice>();

                    outgoingnotice.Excute(sb.ToString());

                    TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = String.Format("发料单(#{0})删除成功", notice.Key) };
                }
            }

            return RedirectToAction("Index");
        }
        public ActionResult Update([ModelBinder(typeof(QualityCertificationModelBinder))]PipeQualityCertification model, string id)
        {
            if (TempData["HintMessage"] != null)
            {
                ViewData["HintMessage"] = TempData["HintMessage"];
            }

            PipeQualityCertification pqc = repository.FindByNotCache(id);
            if (pqc == null)
            {
                throw new HttpException(404, "质证书不存在");
            }

            #region Attachment

            Regex fileReg = new Regex(@"(?<name>.*)\.(jpe?g|gif|bmp|png)$", RegexOptions.IgnoreCase);
            HttpPostedFileBase attachmentFile = Request.Files["Attachment"] as HttpPostedFileBase;
            if (attachmentFile != null)
            {
                if (fileReg.IsMatch(attachmentFile.FileName))
                {
                    string absolutPathDir = "/UserFiles/PipeQualityCertification/";
                    string filePath = Server.MapPath(absolutPathDir);
                    string fileName = pqc.DeliverNotice.Key.ToString() + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + (new Random(DateTime.Now.Second)).Next(1, 999).ToString("000");

                    DirectoryInfo di = new DirectoryInfo(filePath);
                    if (!di.Exists)
                        di.Create();

                    string prevName = attachmentFile.FileName;
                    prevName = fileReg.Replace(prevName, new MatchEvaluator(delegate(Match m)
                    {
                        return m.ToString().Replace(m.Groups["name"].Value, fileName);
                    }));

                    attachmentFile.SaveAs(filePath + prevName);
                    model.AttachmentPath = absolutPathDir + prevName;
                }
            }

            #endregion

            StringBuilder sb = new StringBuilder();

            sb.Append("update pipequalitycertification set code='" + model.Code.ToString() + "',totalcount=" + model.TotalCount + ",totallength=" + model.TotalLength + ",totalweight=" + model.TotalWeight + ",attachmentpath='"+model.AttachmentPath+"' where pipequalitycertificationid='" + id + "'");

            repository.Excute(sb.ToString());

            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = String.Format("质证书{0}修改成功", model.Code) };
            //ReadOnlyCollection<BrokenRule> brokenRules = model.GetBrokenRules();

            return RedirectToAction("Detail", "QualityCertification", new { id = id });
        }
Beispiel #29
0
        public ActionResult Index(string reason)
        {
            if (TempData["HintMessage"] != null)
            {
                ViewData["HintMessage"] = TempData["HintMessage"];
            }

            if (!string.IsNullOrEmpty(reason))
            {
                ViewData["HintMessage"] = new PDCPMS.Application.HintMessage() { Content = reason };
            }

            Account onlineAccount = UserSession.OnlineAccount;
            HomeIndexModel model = new HomeIndexModel();
            DetectionCompany company = UserSession.OnlineAccount.DetectionCompany;

            IEnumerable<NewsCategory> categorys = newsCategoryRepository.FindAll().Take(3).ToList();

            Dictionary<NewsCategory, IEnumerable<News>> news = new Dictionary<NewsCategory, IEnumerable<News>>();

            int pageIndex = 1;
            int pageSize = 10;

            if (!string.IsNullOrEmpty(Request.QueryString["p"]))
            {
                int p;
                if (int.TryParse(Request.QueryString["p"], out p))
                    if (p > 0)
                        pageIndex = p;
            }

            string CC = null;
            PagedList<News> Newslist = null;
            string count=null;

            foreach (var nc in categorys)
            {
                Newslist=newsRepository.Find(null, nc, null, null, null, null, pageSize, pageIndex);
                news.Add(nc, Newslist);

                StringBuilder sb = new StringBuilder();
                sb.Append("select count(*) as totalcount from news where categoryid='" + nc.Key + "'");
                DataTable dt = RepositoryFactory.GetRepository<IPipeTypeRepository, PipeType>().ExcuteDs(sb.ToString());
                count+= (dt.Rows[0]["totalcount"].ToString() == "" ? "0" : dt.Rows[0]["totalcount"].ToString())+"-";
            }
            count.Remove(count.Length-1,1);
            string[] counts = count.Split('-');
            ViewData["count1"] = counts[0];
            ViewData["count2"] = counts[1];
            ViewData["p"] = pageIndex;
            model.News = news;

            PagedList<DeliverNotice> deliverNotices = deliverNoticeRepository.FindNotDo(pageIndex, pageSize, onlineAccount, CC,null,null, company);
            model.DeliverNotices = deliverNotices;

            PagedList<BusinessCheckNotice> businessCheckNotices = businessCheckNoticeRespository.FindNotDo(pageIndex, pageSize,null, onlineAccount);
            model.BusinessCheckNotices = businessCheckNotices;

            PagedList<PipeIncomeRecord> pipeIncomeRecords = pipeIncomeRecordRepository.FindNotDo(pageIndex,pageSize,null,onlineAccount);
            model.PipeIncomeRecords = pipeIncomeRecords;

            PagedList<PipeNeedNotice> pipeNeedNotices = pipeNeedNoticeRepository.FindNotDo(pageIndex,pageSize,onlineAccount);
            model.PipeNeedNotices = pipeNeedNotices;

            PagedList<NormalCheckTask> normalCheckTasks = normalCheckTaskRepository.FindNotDo(pageIndex, pageSize, null, onlineAccount);
            model.NormalCheckTasks = normalCheckTasks;

            PagedList<OutgoingNotice> outgointNotices = outgoingNoticeRepository.FindNotDo(pageIndex, pageSize,null,onlineAccount);
            model.OutgoingNotices = outgointNotices;

            PagedList<ReturningNotice> ReturningNotice = ReturningNoticeRepository.FindNotDo(pageIndex, pageSize,null,onlineAccount);
            model.ReturningNotice = ReturningNotice;

            return View(model);
        }
        public ActionResult Verify(string id)
        {
            TransferNotice notice = repository.FindByNotCache(id);
            if (notice == null)
            {
                throw new HttpException(404, "无法找到指定的垛位调度任务单");
            }

            if (notice.State == TransferNoticeState.Done)
            {
                TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("垛位调度任务单({0})不能重复审核", notice.Key), DisappearDelay = 5000, Type = HintMessageType.Error };
            }

            DateTime now = DateTime.Now;
            notice.State = TransferNoticeState.Done;
            notice.Verifier = UserSession.OnlineAccount;
            notice.DateVerified = now;
            repository[notice.Key] = notice;

            unitOfWork.Commit();

            TempData["HintMessage"] = new PDCPMS.Application.HintMessage { Content = string.Format("垛位调度任务单({0})审核通过成功", notice.Key), DisappearDelay = 5000 };
            return RedirectToAction("Detail", new { id = id });
        }