/// <summary>
 /// 添加新的工程项目,初始化流程状态
 /// </summary>
 /// <param name="newprj"></param>
 /// <param name="createdby"></param>
 public void AddProject(Project newprj,int createdby)
 {
     //获取开始节点
     var prjtype = _rep.SingleOrDefault<ProjectType>(x => x.Id == newprj.ProjectTypeId);
     var startnode = prjtype.WorkFlow.TaskNodes.SingleOrDefault(x => x.BuildIn == "1");
     newprj.FlowLogs.Add(new FlowLog
                             {
                                 StartDate = DateTime.Now,
                                 TaskId = startnode.TaskId,
                                 IsActive = true,
                                 TodoBy = createdby,
                                 Project = newprj
                             });
        // newprj.Contracts.Add(new Contract { Project = newprj});
     _rep.Add(newprj);
     _rep.Save();
 }
        private void FixupProject(Project previousValue)
        {
            if (previousValue != null && previousValue.Contracts.Contains(this))
            {
                previousValue.Contracts.Remove(this);
            }

            if (Project != null)
            {
                if (!Project.Contracts.Contains(this))
                {
                    Project.Contracts.Add(this);
                }
                if (ProjectId != Project.ProjectId)
                {
                    ProjectId = Project.ProjectId;
                }
            }
        }
 public void AddDoneProject(Project newprj, int createdby)
 {
     // var prjtype = _rep.Single<ProjectType>(x => x.Id == newprj.ProjectTypeId);
        // var startnode = prjtype.WorkFlow.TaskNodes.SingleOrDefault(x => x.BuildIn == "1");
     newprj.FlowLogs.Add(new FlowLog
     {
         StartDate = DateTime.Now,
         EndDate = DateTime.Now,
         TaskId = 31,//直接把已竣工的项目置为归档状态
         IsActive = false,
         TodoBy = createdby,
         Project = newprj
     });
     // newprj.Contracts.Add(new Contract { Project = newprj});
     _rep.Add(newprj);
     _rep.Save();
 }
        //如果以前已经录入或者导入该项目,则更新工程信息和施工商信息
        private void UpdateProject(Project project, DateTime? recievedrawingdate, string contractno, double? contractamount, double? aqcsfee, double? gxchfee, DateTime? planstartdate, DateTime? planenddate, string contractcompanyName, string prjtype, double? sumfee, string subcompanyName)
        {
            //  project.VoltageLevelId = GetVoltageId(voltage);
            Contract prjcontract;
            SubContract subContract;
            if (project.Contracts.Any())
            {
                prjcontract = project.ConstructContracts[0];
              //  prjcontract.SignOn = signon;
                prjcontract.CompanyId = GetCompanyId(contractcompanyName);
                prjcontract.ContractAmount = contractamount.HasValue? (decimal) contractamount:0;
              //  prjcontract.BalanceAmount = balanceamount.HasValue? (decimal) balanceamount:0;
             //   prjcontract.BalanceDate = balancedate;
                prjcontract.PlanStartDate = planstartdate;
                prjcontract.PlanEndDate = planenddate;
              //  prjcontract.ActualStartDate = actualstartdate;
              //prjcontract.ActualEndDate = actualenddate;
                prjcontract.RecieveDrawningDate = recievedrawingdate;
                prjcontract.AcwmFee = aqcsfee.HasValue? (decimal)aqcsfee :0;
                prjcontract.GxchFee = gxchfee.HasValue ? (decimal) gxchfee : 0;
               // prjcontract.IsBalance = balancedate.HasValue;
                prjcontract.ContractNo = contractno;
                prjcontract.SumFee = sumfee.HasValue ? (decimal) sumfee : 0;
                // prjcontract.SubCompanyId = GetSubCompanyId(subcompany);
            }
            //如果该项目还未发包给承包商 则新增记录
            else
            {
                project.Contracts.Add(new Contract
                {
                    Project = project,
                    CompanyId = GetCompanyId(contractcompanyName),
                    ContractNo = contractno,
                    ContractAmount = contractamount.HasValue?  (decimal)contractamount : 0,
                  //  BalanceAmount = balanceamount.HasValue? (decimal)balanceamount :0,
                   // BalanceDate = balancedate,
                    PlanStartDate = planstartdate,
                    PlanEndDate = planenddate,
                    //ActualStartDate = actualstartdate,
                    //ActualEndDate = actualenddate,
                    RecieveDrawningDate = recievedrawingdate,
                    //IsBalance = balancedate.HasValue,
                    AcwmFee = aqcsfee.HasValue? (decimal)aqcsfee:0,
                    GxchFee=gxchfee.HasValue ? (decimal) gxchfee : 0,
                    SumFee = sumfee.HasValue? (decimal)sumfee:0,
                    //   SubCompanyId = GetSubCompanyId(subcompany),
                    BidTypeId = 2,
                    CreatedOn = DateTime.Now,
                    CreatedBy = CurrentUser.UserName
                });

            }
            if (project.SubContracts.Any())
            {
                subContract = project.SubContracts.FirstOrDefault();
                //  prjcontract.SignOn = signon;
                subContract.SubCompanyId = GetCompanyId(contractcompanyName);
                subContract.CreatedOn = DateTime.Now.Date;
                subContract.CreateBy = CurrentUser.UserName;
            }
            //如果该项目还未发包给承包商 则新增记录
            else
            {

                project.SubContracts.Add(new SubContract
                {
                    Project = project,
                    SubCompanyId = GetCompanyId(subcompanyName),
                    CreatedOn = DateTime.Now.Date,
                    CreateBy = CurrentUser.UserName
                });
            }
            project.ProjectTypeId = GetTypeId(prjtype);
            Repository.Save();
        }
        /// <summary>
        /// 导入实际竣工日期
        /// </summary>
        /// <param name="sheet"></param>
        private void ImportSubContract(Sheet sheet)
        {
            var rows = sheet.GetRowEnumerator();
            rows.MoveNext();
            while (rows.MoveNext())
            {
                HSSFRow row = (HSSFRow)rows.Current;
                var cell = row.GetCell(1);
                if (cell == null) continue;
                cell.SetCellType(CellType.STRING);
                var erpaccount = cell.StringCellValue.Trim();
                if (string.IsNullOrEmpty(erpaccount)) continue;// 如果没有erp账号不导入

                cell = row.GetCell(2);
                if (cell != null)
                    cell.SetCellType(CellType.STRING);
                else continue;
                var prjname = cell.StringCellValue.Trim();
                if (string.IsNullOrEmpty(prjname)) continue; //没有工程名称 不导入

                //cell = row.GetCell(4);
                //if (cell != null)
                //    cell.SetCellType(CellType.STRING);
                //else continue;
                //var subcompanyname = cell.StringCellValue.Trim(); // 分包施工单位名称
                //if (string.IsNullOrEmpty(subcompanyname)) continue; //没有分包单位 不导入

                //double? balanceamount = null;
                //cell = row.GetCell(7);
                //if (cell != null)
                //{
                //    cell.SetCellType(CellType.NUMERIC);
                //    balanceamount = cell.NumericCellValue; //分包结算价
                //}

                //double? contractamount = null;
                //cell = row.GetCell(6);
                //if (cell != null)
                //{
                //    cell.SetCellType(CellType.NUMERIC);
                //    contractamount = cell.NumericCellValue; //分包合同价
                //}

                DateTime? startdate = null;
                DateTime? enddate = null;
                //cell = row.GetCell(4);
                //if (cell != null && !string.IsNullOrEmpty(cell.ToString()))
                //{
                //    startdate = cell.DateCellValue; //实际开工日期
                //}

                cell = row.GetCell(0);
                if (cell != null && !string.IsNullOrEmpty(cell.ToString()))
                {
                    enddate = cell.DateCellValue; //实际竣工
                }
                // 更新和保存二级施工单位信息
                var prj =
                    Repository.SingleOrDefault<Project>(x => x.ErpCode.Trim() == erpaccount && x.ProjectName.Trim() == prjname);
                if(prj ==null)
                {
                     prj = new Project
                    {
                        ErpCode = erpaccount,

                        ProjectName = prjname,
                        ProjectTypeId = GetTypeIdByErpcode(erpaccount),
                        IsOnProcessed = false,
                        IsFinished = true,
                        CreatedBy = CurrentUser.UserName,
                        CreatedOn = DateTime.Now
                    };
                     _projectService.AddDoneProject(prj, CurrentUser.UserId);
                }

                var subcontract =
                    prj.SubContracts.SingleOrDefault(x => enddate.HasValue && (x.EndDate.HasValue && x.EndDate.Value.Date.CompareTo(enddate.Value.Date)==0));

                if (subcontract==null)
                {
                    prj.SubContracts.Add(new SubContract{CreatedOn = DateTime.Now,CreateBy = User.Identity.Name,
                                                        // SubContractAmount = contractamount.HasValue ? (decimal)contractamount.Value : 0,
                                                       //  SubBalanceAmount = balanceamount.HasValue ? (decimal)balanceamount.Value :0,
                                                       //  StartDate = startdate,
                                                         EndDate = enddate,
                                                         ProjectId = prj.ProjectId,
                                                         //SubCompanyId = GetConstructCompanyId(subcompanyname)
                    });
                }
                else
                {
                   // subcontract.SubContractAmount = contractamount.HasValue ? (decimal) contractamount.Value : 0;
                   // subcontract.SubBalanceAmount = balanceamount.HasValue ? (decimal) balanceamount : 0;
                   // subcontract.StartDate = startdate;
                    subcontract.EndDate = enddate;
                }
                Repository.Save();
            }
        }
        public virtual ActionResult Create(ProjectViewModel toadd)
        {
            if (ModelState.IsValid &&
                !Repository.All<Project>().Any( x=> x.ErpCode.Equals(toadd.ErpCode) && x.ProjectName.Trim().Equals(toadd.ProjectName.Trim())))
            {

                var newprj = new Project();
                TryUpdateModel(newprj);
                newprj.IsFinished = false;
                newprj.IsOnProcessed = true;
                _projectService.AddProject(newprj, CurrentUser.UserId);
                return RedirectToAction(MVC.Project.TodoList());
            }
            ModelState.AddModelError("","已经存在同样帐号和名称的工程");
            return View(toadd);
        }
        private void AddNewProject(string erpaccount, string account, string prjName, string voltage, DateTime? recievedrawingdate, string contractno, double? contractamount, double? aqcsfee, double? gxchfee, DateTime? planstartdate, DateTime? planenddate, string contractcompanyName, string prjtype, double? sumfee, string subcompanyName)
        {
            var prj = new Project
                          {
                              ErpCode = erpaccount,
                              Account = account,
                              ProjectName = prjName,
                              ProjectTypeId = GetTypeId(prjtype),
                             // SubTypeId = GetSubTypeId(account),
                              VoltageLevelId = GetVoltageId(voltage),
                              IsOnProcessed = true,
                              IsFinished = false,
                              CreatedBy = CurrentUser.UserName,
                              CreatedOn = DateTime.Now
                          };
            // add new contract
            prj.Contracts.Add(new Contract
                                  {
                                      Project = prj,
                                      CompanyId = GetCompanyId(contractcompanyName),
                                      ContractNo = contractno,
                                      ContractAmount = contractamount.HasValue? (decimal)contractamount:0,
                                      //BalanceAmount = balanceamount.HasValue? (decimal)balanceamount:0,
                                      //BalanceDate = balancedate,
                                      PlanStartDate =   planstartdate,
                                      PlanEndDate = planenddate,
                                      //ActualStartDate = actualstartdate,
                                      //ActualEndDate = actualenddate,
                                      RecieveDrawningDate = recievedrawingdate,
                                      //IsBalance = balancedate.HasValue,
                                      AcwmFee = aqcsfee.HasValue?  (decimal)aqcsfee:0,
                                      GxchFee = gxchfee.HasValue? (decimal)gxchfee:0,
                                      BidTypeId = 2,
                                      CreatedOn = DateTime.Now,
                                      SumFee = sumfee.HasValue? (decimal)sumfee:0,
                                      CreatedBy = CurrentUser.UserName

                                  });
            prj.SubContracts.Add(new SubContract
                                     {
                                         Project = prj,
                                         SubCompanyId = GetCompanyId(subcompanyName),
                                         CreatedOn = DateTime.Now.Date,
                                         CreateBy = CurrentUser.UserName
                                     });
            // set flowlog and flow state for current project
            _projectService.AddProject(prj,CurrentUser.UserId);
        }
        private void FixupProject(Project previousValue)
        {
            if (previousValue != null && previousValue.FlowLogs.Contains(this))
            {
                previousValue.FlowLogs.Remove(this);
            }

            if (Project != null)
            {
                if (!Project.FlowLogs.Contains(this))
                {
                    Project.FlowLogs.Add(this);
                }
                if (ProjectId != Project.ProjectId)
                {
                    ProjectId = Project.ProjectId;
                }
            }
            else if (!_settingFK)
            {
                ProjectId = null;
            }
        }