unit ProjectFme;

interface

uses
  BillsCompileFme, BillsMeasureFme, PhaseCompareFme, DealPaymentFme,
  BillsGatherFme, ZJJLFme, BGLFme, ReportsFrm, SearchFme, BookmarkFme,
  ProjectData, UtilMethods, Globals, mEncryptEditions, DealBillsFme,
  PriceMarginFme, OtherMeasureFme,
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ImgList, XPMenu, Buttons, ComCtrls, ToolWin, ExtCtrls, JimPages,
  StdCtrls, JimCombos, dxsbar, ActnList, dxBar, OrderCheckerFme, CheckerFme,
  CslButton, UpFileManageFrame, UpFileManageUnit;

type
  TProjectFrame = class(TFrame)
    xpm: TXPMenu;
    ilstExpend: TImageList;
    pnlViewControl: TPanel;
    pnlView: TPanel;
    pnlToolBar: TPanel;
    tbToolsButton: TToolBar;
    tobtnStandardBills: TToolButton;
    tobtnDealPayment: TToolButton;
    tobtnSearch: TToolButton;
    sbtnExpend: TSpeedButton;
    tbXmjBills: TToolBar;
    tbExpand: TToolButton;
    tbSeparator: TToolButton;
    sprAssistant: TSplitter;
    jpsAssistant: TJimPages;
    jpsAssistantDealPayment: TJimPage;
    jpsAssistantSearch: TJimPage;
    dxsbViewControl: TdxSideBar;
    dxsbsViewControl: TdxSideBarStore;
    xbiBillsCompile: TdxStoredSideItem;
    jpsAssistantStandardBills: TJimPage;
    jpsMain: TJimPages;
    jpsMainBillsMeasure: TJimPage;
    xbiBillsGather: TdxStoredSideItem;
    jpsMainBillsGather: TJimPage;
    ilstLarge: TImageList;
    ilstSmall: TImageList;
    xbiStageCompare: TdxStoredSideItem;
    xbiCompleteDegree: TdxStoredSideItem;
    xbiReport: TdxStoredSideItem;
    jpsMainStageCompare: TJimPage;
    tobtnZJJL: TToolButton;
    tobtnBGL: TToolButton;
    jpsAssistantZJJL: TJimPage;
    jpsAssistantBGL: TJimPage;
    dxpmExpandBills: TdxBarPopupMenu;
    alProject: TActionList;
    actnFirstLevel: TAction;
    actnSecondLevel: TAction;
    actnThirdLevel: TAction;
    actnFourthLevel: TAction;
    actnFifthLevel: TAction;
    actnAllLevel: TAction;
    actnAllXmj: TAction;
    xbiBillsMeasure: TdxStoredSideItem;
    jpsMainBillsCompile: TJimPage;
    pnlPhaseSelect: TPanel;
    jcbAudit: TJimComboBox;
    jcbPhase: TJimComboBox;
    tobtnShowChecker: TToolButton;
    jpsAssistantChecker: TJimPage;
    btnSubmit: TCslButton;
    btnPass: TCslButton;
    btnNotPass: TCslButton;
    pnlNewPhase: TPanel;
    btnNewPhase: TCslButton;
    pnlProjectCheckStatus: TPanel;
    actnCurPhase: TAction;
    tobtnBookmark: TToolButton;
    jpsAssistantBookmark: TJimPage;
    jpsAssistantUpFile: TJimPage;
    tobtnUpFile: TToolButton;
    jpsAssistantDealBills: TJimPage;
    tobtnDealBills: TToolButton;
    actnAllPeg: TAction;
    jpsMainPriceMargin: TJimPage;
    xbiPriceMargin: TdxStoredSideItem;
    dxsbsViewControlItem8: TdxStoredSideItem;
    jpsMainOtherMeasure: TJimPage;
    procedure tobtnStandardBillsClick(Sender: TObject);
    procedure jcbPhaseChanged(Sender: TObject);
    procedure sbtnExpendClick(Sender: TObject);
    procedure jcbAuditChanged(Sender: TObject);
    procedure dxsbViewControlItemClick(Sender: TObject;
      Item: TdxSideBarItem);
    procedure dxpmExpandBillsPopup(Sender: TObject);
    procedure actnFirstLevelExecute(Sender: TObject);
    procedure tbExpandClick(Sender: TObject);
    procedure actnAllXmjExecute(Sender: TObject);
    procedure btnSubmitClick(Sender: TObject);
    procedure btnPassClick(Sender: TObject);
    procedure btnNotPassClick(Sender: TObject);
    procedure btnNewPhaseClick(Sender: TObject);
    procedure actnCurPhaseExecute(Sender: TObject);
    procedure tobtnUpFileClick(Sender: TObject);
    procedure jpsAssistantActivePageChanged(Sender: TObject);
    procedure actnAllPegExecute(Sender: TObject);
  private
    FProjectData: TProjectData;

    FBillsCompileFrame: TBillsCompileFrame;
    FBillsMeasureFrame: TBillsMeasureFrame;
    FBillsGatherFrame: TBillsGatherFrame;
    FPriceMarginFrame: TPriceMarginFrame;
    FPhaseCompareFrame: TPhaseCompareFrame;
    FOtherMeasureFrame: TOtherMeasureFrame;

    FCheckerFrame: TCheckerFrame;

    FDealPaymentFrame: TDealPaymentFrame;
    FZJJLFrame: TZJJLFrame;
    FBGLFrame: TBGLFrame;
    FSearchFrame: TSearchFrame;
    FBookmarkFrame: TBookmarkFrame;
    FUpFileManageView: TUpFileManageView;
    FDealBillsFrame: TDealBillsFrame;

    procedure CreateBillsFrame;
    procedure CreateDealPaymentFrame;
    procedure CreateBillsGatherFrame;
    procedure CreatePriceMarginFrame;
    procedure CreateCheckerFrame;
    procedure CreateUpFile;
    procedure CreateFrames;
    procedure InitialForVersions;

    procedure OpenCompare;
    procedure CloseCompare;

    // 刷新各界面只读、显示等
    procedure RefreshProjectState;

    // Change Main View
    procedure BeforeChangeView(APageIndex: Integer);
    procedure AfterChangeView(APageIndex: Integer);
    procedure ChangeView(APageIndex: Integer);

    procedure AdjustFramesDisplay;

    procedure SaveLog(AStr: string);

    procedure ExpandNodeTo(ALevel: Integer);
    procedure ExpandAllXmj;
    procedure ExpandCurPhase;

    procedure SetAssistantViewVisible(AVisible: Boolean);
    procedure SetImageOfsbtnExpend(AExpend: Boolean);
    procedure ControlAssistantButtonsDown(ATag: Integer);
    procedure ExpandBookmarkFrame(AExpandFrame: Boolean);

    procedure UpToWeb(ACheckPassed: Boolean);
    function CheckersHint: string;
    procedure SetUpFileManageView(const Value: TUpFileManageView);
    procedure CheckUpFile;
    procedure ShowPhaseHint;
  public
    constructor Create(AProjectData: TProjectData);
    destructor Destroy; override;

    procedure ResetAssistantView;
    procedure GeneratePhaseChooseList;
    procedure GenerateStageChooseList;

    function CreateNewPhase: Boolean;
    procedure CreateNewAudit;

    procedure RefreshColumnDisplay;

    function CheckCanReport: Boolean;

    procedure UnLockData;
    procedure ReLockData;

    function IsUped: Boolean;
    procedure ButtonControl_UpToWeb;
    procedure ButtonControl_NewPhase;
    procedure RepairAudits;
    function CheckFileAndCloudChekerList: Boolean;

    procedure LocateMeasureBills(AID: Integer);
    procedure LocateCompileBills(AID: Integer);
    procedure LocateZJJL(ABillsID: Integer);

    property ProjectData: TProjectData read FProjectData;

    property BillsCompileFrame: TBillsCompileFrame read FBillsCompileFrame;
    property BillsMeasureFrame: TBillsMeasureFrame read FBillsMeasureFrame;
    property BillsGatherFrame: TBillsGatherFrame read FBillsGatherFrame;
    property PriceMarginFrame: TPriceMarginFrame read FPriceMarginFrame;
    property OtherMeasureFrame: TOtherMeasureFrame read FOtherMeasureFrame;

    property CheckerFrame: TCheckerFrame read FCheckerFrame;
    property UpFileManageView: TUpFileManageView read FUpFileManageView write SetUpFileManageView;

    property DealPaymentFrame: TDealPaymentFrame read FDealPaymentFrame;
    property ZJJLFrame: TZJJLFrame read FZJJLFrame;
    property BGLFrame: TBGLFrame read FBGLFrame;
    property SearchFrame: TSearchFrame read FSearchFrame;
    property BookmarkFrame: TBookmarkFrame read FBookmarkFrame;
    property DealBillsFrame: TDealBillsFrame read FDealBillsFrame;
  end;

implementation

uses
  PhaseData, BGLDm, MainFrm, ZhAPI, SearchDm, PHPWebDm, ActiveX,
  ConstUnit, MD5Unit, sdIDTree, sdDB, mProgressFrm, ConditionalDefines,
  ProjectCommands, ProjectProperty, CheckerMemoFrm, BillsMeasureDm,
  ProgressHintFrm, mProgressProFrm, ReportManagerFrm, BillsCompileDm,
  ScFileArchiverConsts, Math, ZJJLDm;

{$R *.dfm}

{ TProjectFrame }

procedure TProjectFrame.AdjustFramesDisplay;
begin
  jpsAssistant.Width := 395;
  SetAssistantViewVisible(False);
end;

procedure TProjectFrame.ControlAssistantButtonsDown(ATag: Integer);
begin
  tobtnStandardBills.Down := ATag = tobtnStandardBills.Tag;
  tobtnDealPayment.Down := ATag = tobtnDealPayment.Tag;
  tobtnSearch.Down := ATag = tobtnSearch.Tag;
  tobtnZJJL.Down := ATag = tobtnZJJL.Tag;
  tobtnBGL.Down := ATag = tobtnBGL.Tag;
  tobtnShowChecker.Down := ATag = tobtnShowChecker.Tag;
  tobtnUpFile.Down := ATag = tobtnUpFile.Tag;
  tobtnBookmark.Down := ATag = tobtnBookmark.Tag;
end;

constructor TProjectFrame.Create(AProjectData: TProjectData);
begin
  inherited Create(nil);
  FProjectData := AProjectData;
  ResetAssistantView;
  AdjustFramesDisplay;
  CreateFrames;
  RefreshProjectState;
  GeneratePhaseChooseList;
  GenerateStageChooseList;
  dxsbViewControl.SelectedItem := dxsbViewControl.ActiveGroup.Items.Items[0];
  InitialForVersions;

  CreateUpFile;

  if G_IsCloud then
  begin
    pnlProjectCheckStatus.Visible := True;
    // 0号台帐无审核人，网络读取会出错。所以只有在有计量的情况下才创建审核人
    if (ProjectData.PhaseIndex > 0) then
    begin
      tobtnShowChecker.Visible := True;
      CreateCheckerFrame;
    end;
    ButtonControl_NewPhase;
    ButtonControl_UpToWeb;
    RepairAudits;

    if FProjectData.IsGuest then
      tobtnUpFile.Visible := False;
  end;
end;

destructor TProjectFrame.Destroy;
begin
  FBookmarkFrame.Free;
  FZJJLFrame.Free;
  FOtherMeasureFrame.Free;
  FBillsGatherFrame.Free;
  FDealPaymentFrame.Free;
  FBillsCompileFrame.Free;
  FBillsMeasureFrame.Free;
  FUpFileManageView.Free;
  SupportManager.ClearAssistantViewParent;
  inherited;
end;

procedure TProjectFrame.ResetAssistantView;
begin
  AlignControl(SupportManager.StandardLibsFrame, jpsAssistantStandardBills, alClient);
end;

procedure TProjectFrame.SetAssistantViewVisible(AVisible: Boolean);
begin
  jpsAssistant.Visible := AVisible;
  sprAssistant.Visible := AVisible;
end;

procedure TProjectFrame.SetImageOfsbtnExpend(AExpend: Boolean);
begin
  sbtnExpend.Glyph := nil;
  ilstExpend.GetBitmap(Integer(AExpend), sbtnExpend.Glyph);
end;

procedure TProjectFrame.tobtnStandardBillsClick(Sender: TObject);
begin
  with TToolButton(Sender) do
  begin
    if Down then
    begin
      jpsAssistant.ActivePageIndex := Tag;
      sbtnExpend.Tag := Tag;
      ControlAssistantButtonsDown(Tag);
      jpsMain.ActivePage.Tag := Tag;
    end;
    SetAssistantViewVisible(Down);
    SetImageOfsbtnExpend(Down);
  end;
end;

procedure TProjectFrame.GeneratePhaseChooseList;
var
  iIndex: Integer;
begin
  jcbPhase.Items.Clear;
  for iIndex := 1 to FProjectData.ProjProperties.PhaseCount do
    jcbPhase.Items.Add(Format(' 第 %d 期数据', [iIndex]));
  jcbPhase.ItemIndex := jcbPhase.Items.Count - 1;
  jcbPhase.Enabled := jcbPhase.Items.Count > 0;
  tobtnZJJL.Enabled := jcbPhase.Enabled;
  tobtnBGL.Enabled := jcbPhase.Enabled;
end;

procedure TProjectFrame.jcbPhaseChanged(Sender: TObject);
var
  cr: TCursor;
begin
  cr := Screen.Cursor;
  Screen.Cursor := crHourGlass;
  
  if ProjectData.PhaseIndex = jcbPhase.ItemIndex + 1 then Exit;

  FProjectData.PhaseIndex := jcbPhase.ItemIndex + 1;
  GenerateStageChooseList;
  RefreshProjectState;
  if Assigned(FZJJLFrame) then
  begin
    FZJJLFrame.DataReadOnly := FProjectData.PhaseData.StageDataReadOnly;
    FZJJLFrame.ResetFrameLink(FProjectData.PhaseData.ZJJLData);
  end;

  if G_IsCloud then
  begin
    if Assigned(FCheckerFrame) then
    begin
      FCheckerFrame.Init;
      RepairAudits;
    end;
    ButtonControl_UpToWeb;
    UpFileManageView.RefreshViews;
  end;
  jcbPhase.Invalidate;

  Screen.Cursor := cr;
end;

function TProjectFrame.CreateNewPhase: Boolean;
var
  iBef: Integer;
  vArr: array of string;
begin
  Result := False;
  if QuestMessage('请检查合同支付的初始值，新增一期计量将锁定当前全部的清单数据，是否继续？') then
  begin
    // 网络版创建第二期、第三期等跟第一期有所不同：
    // 创建前，先发送信号给服务器，服务器自动根据第一期生成第二期的审核人列表。
    // 有了这个列表程序才能正常接下来的业务。
    if G_IsCloud then
    begin
      iBef := FProjectData.ProjProperties.PhaseCount;
      if iBef >= 1 then
      begin
        vArr := VarArrayOf(['msg']);
        if PHPWeb.Search(PHPWeb.MeasureURL + 'phaseno/userlist/create',
          ['tenderid', 'phaseno'], [IntToStr(FProjectData.WebID),
          IntToStr(iBef + 1)], vArr) <> 1 then
        begin
          Application.MessageBox(Pchar('云端自动创建本期审批人列表出错，请重新尝试！'), '警告', MB_OK + MB_ICONWARNING);
          Exit;
        end;
      end;
    end;

    FProjectData.CreateNewPhase;
    tobtnDealPayment.Enabled := True;
    tobtnZJJL.Enabled := True;
    tobtnBGL.Enabled := True;
    jcbPhase.Enabled := True;
    jcbAudit.Enabled := True;
    jcbPhase.Items.Add(Format(' 第 %d 期数据', [jcbPhase.Items.Count + 1]));
    jcbPhase.ItemIndex := jcbPhase.Items.Count - 1;
    FProjectData.CopyPreData;
    RefreshProjectState;

    if G_IsCloud then
    begin
      if Assigned(CheckerFrame) then
        CheckerFrame.Free;
      CreateCheckerFrame;
      tobtnShowChecker.Visible := True;
      tobtnShowChecker.Enabled := True;

      ButtonControl_NewPhase;
      ButtonControl_UpToWeb;
    end;

    Result := True;
  end;
end;

procedure TProjectFrame.sbtnExpendClick(Sender: TObject);
var
  bExpend: Boolean;
begin
  bExpend := not jpsAssistant.Visible;
  jpsAssistant.ActivePageIndex := TSpeedButton(Sender).Tag;
  SetAssistantViewVisible(bExpend);
  SetImageOfsbtnExpend(bExpend);
  if bExpend then
  begin
    ControlAssistantButtonsDown(jpsAssistant.ActivePageIndex);
    jpsMain.ActivePage.Tag := jpsAssistant.ActivePageIndex;
  end
  else
  begin
    ControlAssistantButtonsDown(-1);
    jpsMain.ActivePage.Tag := -1;
  end;
  if G_IsCloud then
    CheckUpFile;
end;

procedure TProjectFrame.CreateNewAudit;
begin
  FProjectData.PhaseData.CreateNewAuditData;
  jcbAudit.Items.Add(Format(' %d 审', [FProjectData.PhaseData.StageCount - 1]));
  if jcbAudit.ItemIndex <> jcbAudit.Items.Count - 1 then
    jcbAudit.ItemIndex := jcbAudit.Items.Count - 1
  else
    FProjectData.ResetPhaseDataLink;
end;

procedure TProjectFrame.GenerateStageChooseList;
var
  iIndex: Integer;
begin
  jcbAudit.Items.Clear;
  if not FProjectData.PhaseData.Active then Exit;
  for iIndex := 0 to FProjectData.PhaseData.AuditCount do
  begin
    if iIndex = 0 then
      jcbAudit.Items.Add(' 原报')
    else
      jcbAudit.Items.Add(Format(' %d 审', [iIndex]));
  end;
  if jcbAudit.ItemIndex <> jcbAudit.Items.Count - 1 then
    jcbAudit.ItemIndex := jcbAudit.Items.Count - 1
  else
    FProjectData.ResetPhaseDataLink;
  jcbAudit.Enabled := jcbAudit.Items.Count > 0;
end;

procedure TProjectFrame.jcbAuditChanged(Sender: TObject);
begin
  if FProjectData.PhaseData.StageIndex = jcbAudit.ItemIndex then Exit;
  FProjectData.StageIndex := jcbAudit.ItemIndex;
  RefreshProjectState;
end;

procedure TProjectFrame.dxsbViewControlItemClick(Sender: TObject;
  Item: TdxSideBarItem);

  procedure BeforeChangeView;
  begin
    if G_IsCloud then
    begin
      tobtnShowChecker.Visible := ProjectData.PhaseIndex > 0;
      tobtnShowChecker.Enabled := (Item.Tag = xbiBillsMeasure.Tag);

      ButtonControl_NewPhase;

      if Item.Tag = xbiBillsCompile.Tag then
      begin
        if tobtnShowChecker.Down then
        begin
          tobtnShowChecker.Down := False;
          tobtnShowChecker.Click;
          tobtnStandardBills.Down := True;
          tobtnStandardBills.Click;
          tobtnStandardBills.Down := False;
          tobtnStandardBills.Click;
        end;
      end;
    end;
    // 记录台账分解、计量台账等的右侧展开情况
    if jpsAssistant.Visible then
      jpsMain.ActivePage.Tag := jpsAssistant.ActivePageIndex
    else
      jpsMain.ActivePage.Tag := -1;
  end;

  procedure AfterChangeView;
  begin
    // 仅计量台账界面可以选择计量期
    pnlPhaseSelect.Visible := Item.Tag = xbiBillsMeasure.Tag;
    // 台账分解、计量台账、审核比较 可使用"显示至"功能
    tbExpand.Visible := (Item.Tag = xbiBillsCompile.Tag)
                     or (Item.Tag = xbiBillsMeasure.Tag)
                     or (Item.Tag = xbiStageCompare.Tag);
    // 右侧按钮是否显示
    tbToolsButton.Visible := (Item.Tag = xbiBillsCompile.Tag)
                          or (Item.Tag = xbiBillsMeasure.Tag);
    tobtnBGL.Visible := Item.Tag = xbiBillsMeasure.Tag;
    tobtnZJJL.Visible := Item.Tag = xbiBillsMeasure.Tag;
    // 控制整个按钮工具栏显示，
    pnlToolBar.Visible := pnlPhaseSelect.Visible or tbExpand.Visible or tbToolsButton.Visible;
    // 根据当前View控制右侧按钮是否按下，右侧工具窗是否弹开
    jpsAssistant.ActivePageIndex := jpsMain.ActivePage.Tag;
    sbtnExpend.Tag := jpsMain.ActivePage.Tag;
    ControlAssistantButtonsDown(jpsMain.ActivePage.Tag);
    SetAssistantViewVisible(jpsMain.ActivePage.Tag <> -1);
    SetImageOfsbtnExpend(jpsMain.ActivePage.Tag <> -1);
    // 0号台账与计量台账的书签不同
    if Item.Tag = xbiBillsCompile.Tag then
      FBookmarkFrame.BMType := bmtCompile
    else if Item.Tag = xbiBillsMeasure.Tag then
      FBookmarkFrame.BMType := bmtMeasure;
    // 0号台账与计量台账的查找定位不同
    if Item.Tag = xbiBillsCompile.Tag then
      FSearchFrame.LocateType := ltCompile
    else if Item.Tag = xbiBillsMeasure.Tag then
      FSearchFrame.LocateType := ltMeasure;
    // 切换至清单汇总，须重新汇总
    if Item.Tag = xbiBillsGather.Tag then
      BillsGatherFrame.RefreshBills;
    // 切换至材料调差，须重新汇总展示调差清单
    if Item.Tag = xbiPriceMargin.Tag then
      PriceMarginFrame.RefreshBills;

    if G_IsCloud then
    begin
      if (Item.Tag = xbiBillsCompile.Tag) or (Item.Tag = xbiBillsMeasure.Tag) then
        CheckUpFile;

      tobtnUpFile.Visible := (Item.Tag = xbiBillsMeasure.Tag) and (not ProjectData.IsGuest);
      if (tobtnUpFile.Visible = False) and (jpsAssistant.ActivePage = jpsAssistantUpFile) then
        jpsAssistant.ActivePage := jpsAssistantStandardBills;
    end;
  end;

  (*
  procedure ChangeView;
  begin
    BeforeChangeView;
    case Item.Tag of
      0, 2: jpsMain.ActivePageIndex := Item.Tag;
      1, 3, 5: if CheckMeasureEdition then jpsMain.ActivePageIndex := Item.Tag;
    end;
    AfterChangeView;
  end;
  *)
  procedure ClearOldReports(AReportsPath: string);
  var
    SRec: TSearchRec;
    iRetval, iPos: Integer;
    vHead7: TScFile7Head;
    sProp, sFile, sPath: string;
    vFS: TFileStream;
  begin
    iRetval := FindFirst(AReportsPath + '*.srt', faAnyFile, sRec);
    try
      while iRetval = 0 do
      begin
        if (SRec.Attr and faDirectory) = 0 then
        begin
          sFile := AReportsPath + SRec.Name;
          vFS := TFileStream.Create(sFile, fmOpenRead);
          try
            vFS.Read(vHead7, SizeOf(vHead7));
          finally
            vFS.Free;
          end;

          SetString(sProp, vHead7.ReportProperties, 256);
          iPos := Pos('报表ID=', sProp);
          if iPos <= 0 then
            DeleteFile(PChar(sFile));
        end;
        iRetval := FindNext(SRec);
      end;
    finally
      SysUtils.FindClose(SRec);
    end;
  end;

  procedure DisplayReports;
  var vRMForm: TReportManagerForm;
    sPath: string;
  begin
    if G_IsCloud then
    begin
      sPath := ExtractFilePath(ParamStr(0)) + 'ReportTemplates\';
      ClearOldReports(sPath);
      if FileCount(sPath, '.srt') = 0 then
      begin
        Screen.Cursor := crHourGlass;
        vRMForm := TReportManagerForm.Create(nil);
        try
          vRMForm.ShowModal;
        finally
          vRMForm.Free;
          Screen.Cursor := crDefault;
        end;
      end;
    end;
    // 准备数据
    if Item.Tag = xbiReport.Tag then
      FProjectData.CopyPhaseData;
    // 显示报表界面
    DisplayReportsForm(FProjectData);
    dxsbViewControl.SelectedItem := dxsbViewControl.ActiveGroup.Items[jpsMain.ActivePageIndex];
  end;

  procedure DisplayCompare;
  begin
    if FProjectData.ProjProperties.PhaseCount = 0 then
    begin
      ErrorMessage('当前项目未开始计量，暂无审批比较数据！');
      dxsbViewControl.SelectedItem := dxsbViewControl.ActiveGroup.Items[jpsMain.ActivePageIndex];
      Abort;
    end;

    ShowProgressHint('正在准备审批比较数据，请稍候...');
    Screen.Cursor := crHourGlass;
    try
      BeforeChangeView;
      if CheckMeasureEdition then
      begin
        OpenCompare;
        jpsMain.ActivePageIndex := Item.Tag;
      end;
      AfterChangeView;
    finally
      Screen.Cursor := crDefault;
      CloseProgressHint;
    end;
  end;

  procedure DisplayPriceMargin;
  var
    vPM_Node: TsdIDTreeNode;
  begin
    vPM_Node := FProjectData.BillsCompileData.BillsCompileTree.FindNode(iPriceMarginID);
    {if not Assigned(vPM_Node) then
    begin
      ErrorMessage('台账中无预定义价差节点，不可使用价差功能。');
      dxsbViewControl.SelectedItem := dxsbViewControl.ActiveGroup.Items[jpsMain.ActivePageIndex];
      Abort;
    end
    else }if ProjectData.ProjProperties.PhaseCount = 0 then
    begin
      TipMessage('未计量前不可进行材料调差。');
      dxsbViewControl.SelectedItem := dxsbViewControl.ActiveGroup.Items[jpsMain.ActivePageIndex];
      Abort;
    end;
    ChangeView(Item.Tag);
  end;

var
  bCloseCompare: Boolean;
begin
  if Item.Tag = jpsMain.ActivePageIndex then Exit;

  bCloseCompare := (Item.Tag in [0..3, 5]) and (jpsMain.ActivePageIndex = 4);

  case Item.Tag of
    0..2, 5: ChangeView(Item.Tag);
    3: DisplayPriceMargin;
    4: DisplayCompare;
    6: DisplayReports;
  end;

  if bCloseCompare then
    CloseCompare;
end;

procedure TProjectFrame.CreateBillsFrame;
begin
  FBillsCompileFrame := TBillsCompileFrame.Create(Self, FProjectData.BillsCompileData);
  FBillsCompileFrame.ShowDesignQuantity := FProjectData.ProjProperties.ShowDesignQuantity;
  FBillsCompileFrame.ShowAlias := FProjectData.ProjProperties.ShowAlias;
  FBillsCompileFrame.ShowApprovalCode := FProjectData.ProjProperties.ShowApprovalCode;
  FBillsCompileFrame.OnAfterSetBookmark := ExpandBookmarkFrame;
  AlignControl(FBillsCompileFrame, jpsMainBillsCompile, alClient);
  UpdateSysProgress(65, '正在解析数据');

  FBillsMeasureFrame := TBillsMeasureFrame.Create(Self, FProjectData.BillsMeasureData);
  FBillsMeasureFrame.OnAfterSetBookmark := ExpandBookmarkFrame;
  FBillsMeasureFrame.OnLocateZJJL := LocateZJJL;
  FBillsMeasureFrame.ShowPriceChange := FProjectData.ProjProperties.ShowPriceChange;
  FBillsMeasureFrame.ShowBGLCode := FProjectData.ProjProperties.ShowBGLCode;
  FBillsMeasureFrame.ShowDesignQuantity := FProjectData.ProjProperties.ShowDesignQuantity;
  FBillsMeasureFrame.ShowAlias := FProjectData.ProjProperties.ShowAlias;
  FBillsMeasureFrame.ShowApprovalCode := FProjectData.ProjProperties.ShowApprovalCode; 
  FBillsMeasureFrame.ShowIsGather := True;
  AlignControl(FBillsMeasureFrame, jpsMainBillsMeasure, alClient);
end;

procedure TProjectFrame.CreateDealPaymentFrame;
begin
  FDealPaymentFrame := TDealPaymentFrame.Create(Self, FProjectData.DealPaymentData);
  AlignControl(FDealPaymentFrame, jpsAssistantDealPayment, alClient);
end;

procedure TProjectFrame.CreateBillsGatherFrame;
begin
  FBillsGatherFrame := TBillsGatherFrame.Create(Self, FProjectData.BillsGatherData);
  AlignControl(FBillsGatherFrame, jpsMainBillsGather, alClient);
  FBillsGatherFrame.ShowPriceChange := FProjectData.ProjProperties.ShowPriceChange;
  FBillsGatherFrame.ShowPhaseData := FProjectData.ProjProperties.PhaseCount > 0;
  FBillsGatherFrame.OnLocateMeasureBills := LocateMeasureBills;
  FBillsGatherFrame.OnLocateCompileBills := LocateCompileBills;
end;

procedure TProjectFrame.dxpmExpandBillsPopup(Sender: TObject);
begin
  dxpmExpandBills.ItemLinks.Items[8].Visible := _IsDebugView;
  dxpmExpandBills.ItemLinks.Items[7].Visible := jpsMain.ActivePageIndex in [0, 1, 4];
  dxpmExpandBills.ItemLinks.Items[6].Visible := jpsMain.ActivePageIndex in [1, 4];
  SetDxBtnAction(actnFirstLevel, MainForm.dxbtnFirstLevel);
  SetDxBtnAction(actnSecondLevel, MainForm.dxbtnSecondLevel);
  SetDxBtnAction(actnThirdLevel, MainForm.dxbtnThirdLevel);
  SetDxBtnAction(actnFourthLevel, MainForm.dxbtnFourthLevel);
  SetDxBtnAction(actnFifthLevel, MainForm.dxbtnFifthLevel);
  SetDxBtnAction(actnAllLevel, MainForm.dxbtnAllLevel);
  SetDxBtnAction(actnCurPhase, MainForm.dxbtnCurPhase);
  SetDxBtnAction(actnAllXmj, MainForm.dxbtnAllXmj);
  SetDxBtnAction(actnAllPeg, MainForm.dxbtnAllPeg);
end;

procedure TProjectFrame.actnFirstLevelExecute(Sender: TObject);
begin
  ExpandNodeTo(TAction(Sender).Tag);
end;

procedure TProjectFrame.tbExpandClick(Sender: TObject);
var
  P: TPoint;
begin
  P := pnlToolBar.ClientToScreen(Point(tbExpand.Left, tbExpand.Top + tbExpand.Height));
  dxpmExpandBills.Popup(P.X, P.Y);
end;

procedure TProjectFrame.actnAllXmjExecute(Sender: TObject);
begin
  ExpandAllXmj;
end;

procedure TProjectFrame.ExpandNodeTo(ALevel: Integer);
begin
  Screen.Cursor := crHourGlass;
  case ALevel of
    0..4: UpdateSysProgress(0, Format('正在显示至第%d层', [ALevel + 1]));
    else UpdateSysProgress(0, '正在显示至最底层');
  end;
  try
    case jpsMain.ActivePageIndex of
      0: FBillsCompileFrame.ExpandNodeTo(ALevel);
      1: FBillsMeasureFrame.ExpandNodeTo(ALevel);
      4: FPhaseCompareFrame.ExpandNodeTo(ALevel);
    end;
  finally
    UpdateSysProgress(0, '就绪');
    Screen.Cursor := crDefault;
  end;
end;

procedure TProjectFrame.ExpandAllXmj;
begin
  Screen.Cursor := crHourGlass;
  UpdateSysProgress(0, '正在显示至项目节');
  try
    case jpsMain.ActivePageIndex of
      0: FBillsCompileFrame.ExpandXmjNode;
      1: FBillsMeasureFrame.ExpandXmjNode;
      4: FPhaseCompareFrame.ExpandXmjNode;
    end;
  finally
    UpdateSysProgress(0, '就绪');
    Screen.Cursor := crDefault;
  end;
end;

procedure TProjectFrame.UnLockData;

  procedure DoUnLockData;
  begin
    FProjectData.CanUnlockInfo := True;
    FBillsCompileFrame.stdBillsCompile.Column('LockedInfo').ReadOnly := False;
    //FProjectData.BillsData.UnLockedBaseData;
  end;

begin
  if FProjectData.CheckPassword then
    DoUnLockData;
end;

procedure TProjectFrame.CreateCheckerFrame;
begin
  FCheckerFrame :=  TCheckerFrame.Create(Self);
  FCheckerFrame.Owner := Self;
  FCheckerFrame.ProjectData := FProjectData;
  AlignControl(FCheckerFrame, jpsAssistantChecker, alClient);
  FCheckerFrame.Init;
end;

procedure TProjectFrame.btnSubmitClick(Sender: TObject);
begin
  if not CheckCanReport then Exit;

  Screen.Cursor := crHourGlass;
  try
    UpToWeb(True);
  finally
    Screen.Cursor := crDefault;
  end;
end;

procedure TProjectFrame.btnPassClick(Sender: TObject);
begin
  btnSubmitClick(Sender);
end;

function TProjectFrame.IsUped: Boolean;  // 是否上传过
begin
  Result := False;

  // 只有０号台帐那肯定没上传过
  if ProjectData.PhaseIndex = 0 then Exit;

  // 当前期是旧期
  if ProjectData.IsHistoryPhase then
    Result := True
  // 当前显示的期是最新期，分两种情况判断，如果第一审核人已有状态，则上传过了
  else
  begin
    // 当用户点击新增一期计量后，会调用该方法，此时，有一期数据，却为上传过
    if not Assigned(CheckerFrame) then
      Result := False
    else if not CheckerFrame.HasChecker then
      Result := False
    else if CheckerFrame.FirstChecker.CheckStatus = csNotBegin then
      Result := False
    else
      Result := True;
  end;
end;

procedure TProjectFrame.ButtonControl_UpToWeb;
begin
  if ProjectData.CurUserIsAuthor then
  begin
    btnSubmit.Visible := True;
    // 有计量（非0号台账状态），且当前计量期尚未上报过
    btnSubmit.Enabled := (ProjectData.PhaseIndex > 0) and (not IsUped);
    btnPass.Visible := False;
    btnNotPass.Visible := btnPass.Visible;
    btnSubmit.Left := jcbAudit.Left + jcbAudit.Width + 5;
  end
  else if ProjectData.CurUserIsOwner or ProjectData.CurUserIsChecker then
  begin
    btnSubmit.Visible := False;
    btnPass.Visible := True;
    btnNotPass.Visible := btnPass.Visible;
    // 在本期我是审核人，切换到历史期有可能我没参与。 所以当CheckerFrame.Me为空时，有可能我是编制人，有可能历史期我没参与。
    // 历史期，管你那么多，直接按钮不见。
    if ProjectData.PhaseIndex < ProjectData.ProjProperties.PhaseCount then
      btnPass.Enabled := False
    else
    begin
      if CheckerFrame.Me <> nil then
        btnPass.Enabled := CheckerFrame.Me.IsChecking
      else         // 游客，关注人身份
        btnPass.Enabled := False;
    end;

    btnNotPass.Enabled := btnPass.Enabled;
    btnPass.Left := jcbAudit.Left + jcbAudit.Width + 5;
    btnNotPass.Left := btnPass.Left + btnPass.Width + 1;
  end;
  ShowPhaseHint;

  if Assigned(FCheckerFrame) then
    FCheckerFrame.RepairDelete(btnSubmit.Visible and btnSubmit.Enabled);
end;

procedure TProjectFrame.UpToWeb(ACheckPassed: Boolean);
var sURL, sAppFile, sJsonFile_Bills, sJsonFile_Common, sAppFile_UnLock,
  sZipFile, sResult, sMD5_JL, sPassedHint1, sPassedHint2,
  sNoPassedHint1, sNoPassedHint2, sCheckerMemo: string;
  vA, vArr: array of string;
  vRec: TsdDataRecord;
  bSubmit: Boolean;
  vExportor: TTenderExport;
  vCF: TCheckerMemoForm;
  bNeedFreeEarlier: Boolean;

  // 1 审核； 2 批复。
  function SaveAndExport(AType: Integer): Boolean;

    function InnerSubmit(AType: Integer): Boolean;
    begin
      if AType = 1 then
        Result := ProjectData.SubmitProject(sAppFile)
      else if AType = 2 then
        Result := ProjectData.ReplyProject(sAppFile);
    end;
  begin
    Result := False;
    ProgressProCreate(100, '本地数据文件上传到云端');
    ProgressProRun('保存本地数据...', 0);
    ProjectData.SaveAndCheck;
    ProgressProRun('保存本地数据。OK', 10, pmtEdit);

    ProgressProRun('导出并检验文件...', 0);
    if not InnerSubmit(AType) then
      if not InnerSubmit(AType) then
      begin
        bNeedFreeEarlier := True;
        Application.MessageBox('Sorry！本地文件连续2次导出检验失败！如果重试后仍不能解决该问题，请联系纵横客服。', '提示', MB_OK + MB_ICONWARNING);
        Exit;
      end;
    Result := True;
    ProgressProRun('导出并检验文件。OK', 10, pmtEdit);
  end;
begin
  bSubmit := False;
  bNeedFreeEarlier := False;
  sAppFile := PHPWeb.UserPath + 'ProjectFile.rmf';
  // 只有编制人才真正需要该文件存在
//  sAppFile_UnLock := PHPWeb.UserPath + 'ProjectFile_UnLock';

  sPassedHint1 :=
    '【审批通过】后，计量数据将自动交付给下一审批人进行审批，操作后将不可更改，是否通过审批？';
  sPassedHint2 :=
    '(终审)审批通过后本期计量审批将标记为审批完成，操作后将不可更改，是否通过审批？';
  sNoPassedHint1 :=
    '【审批不通过】后，本次审批将结束，后续的审批人也将不会审批本次计量，' +
    '本期数据也将直接打回给上报人进行重新计量报审。' + #10#13 +
    '点击【确定】进入操作确认。';
  sNoPassedHint2 := PHPWeb.RealName +
    '，请确认本期计量审批不通过。' + #10#13 + '点击【确定】本期计量审批' +
    '不通过，计量将不可再更改。';

  vCF := TCheckerMemoForm.Create(nil);
  try
    if ProjectData.CurUserIsAuthor then
    begin
      bSubmit := True;
      if not CheckerFrame.HasNormalChecker then
      begin
        Application.MessageBox('上报审批前请先配置审批人！', '提示', MB_OK + MB_ICONWARNING);
        tobtnShowChecker.Down := True;
        tobtnShowChecker.Click;
        Exit;
      end;

      // 保存一次缓存数据，以保证提示信息能读取正确的值
      ProjectData.SaveLastestPhaseMainData;
      if Application.MessageBox(PChar(CheckersHint), '询问', MB_YESNO + MB_ICONQUESTION) = ID_No then
        Exit;

      if not SaveAndExport(1) then Exit;
    end
    else if ProjectData.CurUserIsChecker then
    begin
      if ACheckPassed then
      begin
        vCF.Init(sPassedHint1, 1);
        if vCF.ShowModal = mrCancel then
          Exit
        else
          sCheckerMemo := vCF.Memo;
      end
      else
      begin
        vCF.Init(sNoPassedHint1, 0);
        if vCF.ShowModal = mrCancel then
          Exit
        else
          sCheckerMemo := vCF.Memo;

        if Application.MessageBox(PChar(sNoPassedHint2), '询问', MB_OKCANCEL + MB_ICONQUESTION) = ID_CANCEL then
          Exit;
      end;

      if not SaveAndExport(1) then Exit;
    end
    else if ProjectData.CurUserIsOwner then
    begin
      if ACheckPassed then
      begin
        vCF.Init(sPassedHint2, 1);
        if vCF.ShowModal = mrCancel then
          Exit
        else
          sCheckerMemo := vCF.Memo;
      end
      else
      begin
        vCF.Init(sNoPassedHint1, 0);
        if vCF.ShowModal = mrCancel then
          Exit
        else
          sCheckerMemo := vCF.Memo;

        if not QuestMessage(sNoPassedHint2) then
          Exit;
      end;

      if not SaveAndExport(2) then Exit;
    end;
  finally
    vCF.Free;
    if bNeedFreeEarlier then
      ProgressProFree;
  end;

  try
    ProgressProRun('生成汇总数据...', 0);
    sJsonFile_Bills := ExtractFilePath(sAppFile) + 'JsonFile_Bills.json';
    sJsonFile_Common := ExtractFilePath(sAppFile) + 'JsonFile_Common.json';
    sMD5_JL := MD5_File(sAppFile);
    // 上传清单，每期都传，可覆盖旧的。
    ProjectData.ExportJson_Bills(sJsonFile_Bills);
    ProjectData.ExportJson_Common(sJsonFile_Common);
    ProgressProRun('生成汇总数据。OK', 10, pmtEdit);

    ProgressProRun('生成并检验up数据包文件...', 0);

    sZipFile := PHPWeb.zip([sAppFile, sJsonFile_Bills, sJsonFile_Common]);

    if not PHPWeb.CheckZip(sZipFile, 3) then
    begin
      WarningMessage('up数据包无法正确解压检验，请重试！如果重试后仍不能解决该问题，请联系纵横客服。', ProgressProHandle);
      Exit;
    end;
    ProgressProRun('校验数据包。OK', 10, pmtEdit);
    
    try
      ProgressProRun('上传数据包到云端...(温馨提示：请不要乱点哦，Windows容易死机)', 0);
      if PHPWeb.UpDataFile(PHPWeb.UserID, ProjectData.WebID, ProjectData.PhaseIndex,
        sZipFile, sMD5_JL, bSubmit, sResult, ACheckPassed, sCheckerMemo) then
      begin
        DeleteFile(sAppFile);
        ProgressProRun('上传数据包到云端。OK', 100, pmtEdit, pptSet);
        if ProjectData.CurUserIsChecker then
          ProjectData.Checkers.FindByID(PHPWeb.UserID).Memo := sCheckerMemo;

        if ProjectData.PhaseIndex = 0 then   // 0号台账，现已废弃
        begin
          MainForm.ProjectManagerFrame.ShowProjectInfoTop(0);
        end
        else
        Begin
          vRec := MainForm.ProjectManagerFrame.Rec(ProjectData.ProjectID);
          vRec.BeginUpdate;
          vRec.ValueByName('WebMD5').AsString := sMD5_JL;
          vRec.EndUpdate;
          MainForm.ProjectManagerFrame.ShowProjectInfoTop;

          if ProjectData.CurUserIsAuthor then
          begin
            CheckerFrame.FirstChecker.CheckStatus := csChecking;
            CheckerFrame.AddFrame.Visible := False;
          end
          else
          begin
            if ACheckPassed then
            begin
              CheckerFrame.Me.CheckStatus := csFinished;
              if ProjectData.CurUserIsChecker then
                CheckerFrame.NextChecker.CheckStatus := csChecking;
            end
            else
              CheckerFrame.Me.CheckStatus := csNotPass;

            CheckerFrame.Me.CheckerMemo := sCheckerMemo;
            CheckerFrame.Me.CheckedTime := Format('[%s][线下审批]',[DateToStr(Date)]);
          end;
        end;

        btnSubmit.Enabled := False;
        FCheckerFrame.RepairDelete(False);
        btnPass.Enabled := False;
        btnNotPass.Enabled := btnPass.Enabled;
        ShowPhaseHint;
        ProgressProHide;
        TipMessage('^_^ 恭喜！数据已成功上传到云端服务器。', ProgressProHandle);
      end
      else
      begin
        ProgressProHide;
        WarningMessage('数据无法上传：' + sResult, ProgressProHandle);
        if Pos('审批完毕', sResult) > 0 then
        begin
          btnSubmit.Enabled := False;
          btnPass.Enabled := False;
          btnNotPass.Enabled := btnPass.Enabled;
        end;
      end;

    except
      ProgressProHide;
      WarningMessage('与服务器断开连接，请稍后重试。' + sResult, ProgressProHandle);
    end;
  finally
    ProgressProFree;
  end;
end;

procedure TProjectFrame.btnNotPassClick(Sender: TObject);
begin
  Screen.Cursor := crHourGlass;
  try
    UpToWeb(False);
  finally
    Screen.Cursor := crDefault;
  end;
end;

function TProjectFrame.CheckersHint: string;
var vSL: TStringList;
  i: Integer;
  sChecker, sChar: string;
  Rec: TsdDataRecord;
begin
  vSL := TStringList.Create;
  try
    CheckerFrame.CheckerNameList(vSL);
    for i := 0 to vSL.Count - 1 do
    begin
      if i = 0 then
        sChar := ''
      else
        sChar := ' > ';
      sChecker := sChecker + sChar + vSL[i];
    end;

    while Length(sChecker) < 38 do     // 保证提示框的大小达到最佳效果
      sChecker := sChecker + ' ';

    Rec := ProjectData.MainListData.GetPhaseMainRecord(FProjectData.PhaseIndex);
    Result := Format('本期计量：%m元。%s审批流程：%s%s上报后将不可更改，确定要上报吗？',
      [Rec.ValueByName('GatherTotalPrice').AsFloat, #10#13#10#13, sChecker, #10#13#10#13]);
  finally
    vSL.Free;
  end;
end;

procedure TProjectFrame.btnNewPhaseClick(Sender: TObject);
begin
  if not CreateNewPhase then Exit;
  dxsbViewControl.SelectedItem := dxsbViewControl.Groups[0].Items[1];
  dxsbViewControl.OnItemClick(Sender, dxsbViewControl.Groups[0].Items[1]);
end;

procedure TProjectFrame.ButtonControl_NewPhase;
var b1, b2, b3: Boolean;
begin
  // “新建一期计量”按钮的显示隐藏
  // 计量界面，且是原报才显示
  b1 := (dxsbViewControl.SelectedItem.Index = 0) and ProjectData.CurUserIsAuthor;
  // ①尚无审核人列表  ②当前期已审核完成
  b2 := (not Assigned(CheckerFrame)) or (Assigned(CheckerFrame) and CheckerFrame.OwnerFrame.IsFinished);
  // 当前查看的是最新期。查看历史期不显示。
  b3 := (FProjectData.ProjProperties.PhaseCount = FProjectData.PhaseIndex);

  pnlNewPhase.Visible := b1 and b2 and b3;
end;

procedure TProjectFrame.actnCurPhaseExecute(Sender: TObject);
begin
  ExpandCurPhase;
end;

procedure TProjectFrame.RepairAudits;
var i, iSel: Integer;
  UserArr: array of string;
  sURL: string;
begin
  jcbAudit.ItemHeight := 20;
  jcbAudit.Font.Name := '微软雅黑';
  jcbAudit.Font.Size := 10;
  jcbAudit.DropDownBox.Height := jcbAudit.Items.Count * jcbAudit.ItemHeight + 35;

  iSel := jcbAudit.ItemIndex;
  for i := 0 to jcbAudit.Items.Count - 1 do
  begin
    if i = 0 then
    begin
      // 原报：编制人。没有跟审核人一个表，另外查询。个人觉得这里设计得不好。
      // 打开软件时自动扫描，杰哥那头返回不了编制人的项目，也是这个原因。
      // 说服不了特工，先这样吧。
      sURL := Format('%suser/get/%d/info', [PHPWeb.MeasureURL, FProjectData.WebAuthorID]);
      UserArr := VarArrayOf(['avatar', 'name', 'jobs', 'company']);
      if PHPWeb.Search(sURL, [], [], UserArr) = 1 then
        jcbAudit.Items[i] := jcbAudit.Items[i] + ' ' + UserArr[1] + '－' + UserArr[2];
    end
    else
    begin
      // 某种漏洞的操作下，文件中记载的审核人数和审核人列表中的审核人数不一致，
      // 匹配时会溢出。这里要加判断。
      if i > CheckerFrame.List.Count then Break;
      if TOrderCheckerFrame(CheckerFrame.List[i - 1]) = FCheckerFrame.OwnerFrame then
      begin
        jcbAudit.Items[i] := ' 终审 ' +
          TOrderCheckerFrame(CheckerFrame.List[i - 1]).UserName + '－' +
          TOrderCheckerFrame(CheckerFrame.List[i - 1]).UserRole
      end
      else
      begin
        jcbAudit.Items[i] := jcbAudit.Items[i] + ' ' +
          TOrderCheckerFrame(CheckerFrame.List[i - 1]).UserName + '－' +
          TOrderCheckerFrame(CheckerFrame.List[i - 1]).UserRole;
      end;
    end;
  end;
  jcbAudit.ItemIndex := iSel;
end;

procedure TProjectFrame.CreateFrames;
begin
  UpdateSysProgress(10, '正在解析数据');
  CreateBillsFrame;
  UpdateSysProgress(130, '正在解析数据');
  CreateDealPaymentFrame;
  UpdateSysProgress(135, '正在解析数据');
  CreateBillsGatherFrame;
  UpdateSysProgress(140, '正在解析数据');
  CreatePriceMarginFrame;                
  UpdateSysProgress(145, '正在解析数据');

  FOtherMeasureFrame := TOtherMeasureFrame.Create(FProjectData);
  AlignControl(FOtherMeasureFrame, jpsMainOtherMeasure, alClient);
  UpdateSysProgress(150, '正在解析数据');


  FZJJLFrame := TZJJLFrame.Create(Self, FProjectData.PhaseData.ZJJLData);
  FZJJLFrame.DataReadOnly := FProjectData.PhaseData.StageDataReadOnly;
  AlignControl(FZJJLFrame, jpsAssistantZJJL, alClient);
  UpdateSysProgress(160, '正在解析数据');

  FBGLFrame := TBGLFrame.Create(Self, FProjectData.BGLData);
  AlignControl(FBGLFrame, jpsAssistantBGL, alClient);
  UpdateSysProgress(170, '正在解析数据');

  FSearchFrame := TSearchFrame.Create(Self, FProjectData.SearchData);
  AlignControl(FSearchFrame, jpsAssistantSearch, alClient);
  UpdateSysProgress(180, '正在解析数据');

  FBookmarkFrame := TBookmarkFrame.Create(Self, FProjectData);
  AlignControl(FBookmarkFrame, jpsAssistantBookmark, alClient);
  UpdateSysProgress(190, '正在解析数据');

  FDealBillsFrame := TDealBillsFrame.Create(Self, FProjectData.DealBillsData);
  AlignControl(FDealBillsFrame, jpsAssistantDealBills, alClient);
  UpdateSysProgress(200, '就绪');
end;

procedure TProjectFrame.InitialForVersions;
begin
  if _ModuleType = mtCompile then
  begin
    // 去掉审核比较
    dxsbViewControl.Groups.Items[0].Items.Delete(3);
    // 去掉计量台账
    dxsbViewControl.Groups.Items[0].Items.Delete(1);
  end;
end;

procedure TProjectFrame.ExpandBookmarkFrame(AExpandFrame: Boolean);
begin
  // 展开书签
  if AExpandFrame then
  begin
    jpsAssistant.ActivePageIndex := tobtnBookmark.Tag;
    sbtnExpend.Tag := tobtnBookmark.Tag;
    ControlAssistantButtonsDown(tobtnBookmark.Tag);
    jpsMain.ActivePage.Tag := tobtnBookmark.Tag;
    SetAssistantViewVisible(True);
    SetImageOfsbtnExpend(True);
  end;
  // 刷新书签批注
  FBookmarkFrame.RefreshMarkMemo;
end;



{
    在意外情况下，文件中记录的审核人与云端记录的审核人不一致，文件中的审核表有时
    被多创建，有时少创建。这时不允许继续操作，需强制关闭：

    1、如果第x个人为审核中，则：
       ①当前登录用户，如果非工作中，无论编制人、审核人还是业主，审核表个数应为x。
       ②当前登录用户，如果工作中，必是审核人或业主，审核表个数应为x + 1。

    2、如果找不到审核中，找到了第x个人为审核不通过，则：
       ①当前登录用户为编制人：
         a.重新开始：审核表个数应为1。
         b.仅查看不通过项目：审核表个数应为x + 1。
       ②当前登录用户为审核人或业主：一定是非工作中（编制人工作中），审核表个数应为x + 1。

    3、如果找不到审核中，也找不到审核不通过，如果最后一个人是审核完成，则：
       ①当前登录用户为编制人，此时编制人尚末开始新的一期，下拉还是上一期的，审核表个数亦为x+1。
       ②当前登录用户为审核人或业主，审核表个数为x+1。

    4、如果找不到审核中，也找不到审核不通过，如果第一个人是末审核，则：
       ①当前登录用户为编制人，审核表个数应为1。                               }
function TProjectFrame.CheckFileAndCloudChekerList: Boolean;
var iNo, iC: Integer;
begin
  Result := False;
  iC := jcbAudit.Items.Count;

  if not Assigned(FCheckerFrame) then  // 0号台帐阶段还没有审核人业务
  begin
    Result := True;
    Exit;
  end;

  iNo := FCheckerFrame.CheckNo(csChecking);
  if iNo <> -1 then    // 审核中
  begin
    // FCheckerFrame.Me = nil :编制 （这里体现出编制人不在审核人列表中极不合理！）
    if (FCheckerFrame.Me <> nil) and FCheckerFrame.Me.IsChecking then
      Result := (iC = iNo + 1)
    else
      Result := (iC = iNo);
  end
  else    // 三种情况：①原报阶段，一个状态都没有 ②审核完成 ③审核不通过
  begin
    iNo := FCheckerFrame.CheckNo(csNotPass);
    if iNo <> -1 then      // 情况③，审核不通过
    begin
      if ProjectData.CurUserIsAuthor then
        Result := ((iC = 1) or (iC = iNo + 1))
//      else if FCheckerFrame.InCheckerList(PHPWeb.UserID) then      // 这个条件会漏掉关注人
      else
        Result := (iC = iNo + 1);
    end
    else
    begin
      // 情况②，审核完成
      if FCheckerFrame.LastChecker.CheckStatus = csFinished then    // 最后一个人是审核完成
        Result := (iC = FCheckerFrame.List.Count + 1)
      else
      // 情况①，原报阶段，一个状态都没有
      begin
        if ProjectData.CurUserIsAuthor then   // 如果是原报，则只有一张表
          Result := (iC = 1)
        else
        // 其它人时，原报尚末上传，表的数量是上一期的。
        // 如果是打回，上一期的数量也是不固定的(中途打回)。反正这里只看不改，不限制。
          Result := True;
      end;
    end;
  end;
end;

procedure TProjectFrame.tobtnUpFileClick(Sender: TObject);
begin
  with TToolButton(Sender) do
  begin
    if Down then
    begin
      jpsAssistant.ActivePageIndex := Tag;
      sbtnExpend.Tag := Tag;
      ControlAssistantButtonsDown(Tag);
      jpsMain.ActivePage.Tag := Tag;
    end;
    SetAssistantViewVisible(Down);
    SetImageOfsbtnExpend(Down);
  end;
  CheckUpFile;
end;

procedure TProjectFrame.CreateUpFile;
begin
  FUpFileManageView := TUpFileManageView.Create(nil);
  FUpFileManageView.Owner := Self;
  
  FUpFileManageView.ProjectData := FProjectData;
  FUpFileManageView.Datas := FProjectData.AttachmentData;
  FUpFileManageView.Parent := jpsAssistantUpFile;
  FUpFileManageView.Align := alClient;
end;

procedure TProjectFrame.SetUpFileManageView(
  const Value: TUpFileManageView);
begin
  FUpFileManageView := Value;
end;

procedure TProjectFrame.jpsAssistantActivePageChanged(Sender: TObject);
begin
  if G_IsCloud then
    CheckUpFile;
end;

procedure TProjectFrame.CheckUpFile;
var vRec: TsdDataRecord;
begin  
  if jpsAssistant.Visible and (jpsAssistant.ActivePage = jpsAssistantUpFile) then
  begin
    if jpsMain.ActivePage = jpsMainBillsCompile then
    begin
      vRec := FBillsCompileFrame.BillsCompileData.sdvBillsCompile.Current;
      if vRec = nil then
        vRec := FBillsCompileFrame.stdBillsCompile.IDTree.Items[0].Rec;
    end
    else if jpsMain.ActivePage = jpsMainBillsMeasure then
    begin
      vRec := FBillsMeasureFrame.BillsMeasureData.sdvBillsMeasure.Current;
      if vRec = nil then
        vRec := FBillsMeasureFrame.stdBillsMeasure.IDTree.Items[0].Rec;
    end;
    FUpFileManageView.DoOnBillChange(vRec);
  end;
end;

procedure TProjectFrame.SaveLog(AStr: string);
var
  sFileName: string;
  F: TextFile;
begin
  sFileName := GetAppFilePath + 'TimeLog.txt';
  AssignFile(F, sFileName);
  if FileExists(sFileName) then
    Append(F)
  else
    Rewrite(F);
  Writeln(F, AStr);
  CloseFile(F);
end;

procedure TProjectFrame.ReLockData;
begin
  FProjectData.CanUnlockInfo := False;
  FBillsCompileFrame.stdBillsCompile.Column('LockedInfo').ReadOnly := True;
end;

procedure TProjectFrame.CloseCompare;
begin  
  FPhaseCompareFrame.Free;
  FProjectData.PhaseCompareData.Close;
  FProjectData.PhaseData.StageCompareData.Close;
end;

procedure TProjectFrame.OpenCompare;
begin
  FProjectData.PhaseData.Save;
  FProjectData.PhaseData.StageCompareData.Open;
  FProjectData.PhaseCompareData.Open;
  FPhaseCompareFrame := TPhaseCompareFrame.Create(Self, FProjectData.PhaseCompareData);
  AlignControl(FPhaseCompareFrame, jpsMainStageCompare, alClient);
end;

procedure TProjectFrame.RefreshColumnDisplay;
begin
  BillsCompileFrame.ShowDesignQuantity := FProjectData.ProjProperties.ShowDesignQuantity;
  BillsCompileFrame.ShowAlias := FProjectData.ProjProperties.ShowAlias;
  BillsCompileFrame.ShowApprovalCode := FProjectData.ProjProperties.ShowApprovalCode;
  BillsMeasureFrame.ShowPriceChange := FProjectData.ProjProperties.ShowPriceChange;
  BillsMeasureFrame.ShowBGLCode := FProjectData.ProjProperties.ShowBGLCode;
  BillsMeasureFrame.ShowDesignQuantity := FProjectData.ProjProperties.ShowDesignQuantity;
  BillsMeasureFrame.ShowAlias := FProjectData.ProjProperties.ShowAlias;
  BillsMeasureFrame.ShowApprovalCode := FProjectData.ProjProperties.ShowApprovalCode;
  BillsGatherFrame.ShowPriceChange := FProjectData.ProjProperties.ShowPriceChange;
  BillsGatherFrame.zgGclBills.Invalidate; 
end;

procedure TProjectFrame.RefreshProjectState;
begin
  FBillsCompileFrame.RefreshPhase_Stage;
  FBillsMeasureFrame.RefreshPhase_Stage;
  FDealPaymentFrame.RefreshPhase_Stage;
  FPriceMarginFrame.ResetViewControl;
  FOtherMeasureFrame.ResetViewControl;
end;

procedure TProjectFrame.ExpandCurPhase;
begin
  Screen.Cursor := crHourGlass;
  UpdateSysProgress(0, '正在显示至项目节');
  try
    case jpsMain.ActivePageIndex of
      1: FBillsMeasureFrame.ExpandCurPhase;
      4: FPhaseCompareFrame.ExpandCurPhase;
    end;
  finally
    UpdateSysProgress(0, '就绪');
    Screen.Cursor := crDefault;
  end;
end;

function TProjectFrame.CheckCanReport: Boolean;
begin
  Result := QuestMessageYesNo('请确定已生成中间计量数据？');
  // 使用控件点击进行定位，重新定义方法太复杂
  if not Result then
  begin
    // 先定位至计量台账界面
    dxsbViewControl.SelectedItem := dxsbViewControl.ActiveGroup.Items[1];
    dxsbViewControlItemClick(dxsbViewControl, dxsbViewControl.ActiveGroup.Items[1]);
    // 再定位至中间计量界面
    tobtnZJJL.Down := True;
    tobtnZJJL.Click;
  end;
end;

procedure TProjectFrame.actnAllPegExecute(Sender: TObject);
begin
  Screen.Cursor := crHourGlass;
  UpdateSysProgress(0, '正在显示至桩号(项目节)');
  try
    case jpsMain.ActivePageIndex of
      0: FBillsCompileFrame.ExpandPegXmjNode;
    end;
  finally
    UpdateSysProgress(0, '就绪');
    Screen.Cursor := crDefault;
  end;
end;

procedure TProjectFrame.CreatePriceMarginFrame;
begin
  FPriceMarginFrame := TPriceMarginFrame.Create(FProjectData);
  AlignControl(FPriceMarginFrame, jpsMainPriceMargin, alClient);
end;

procedure TProjectFrame.ShowPhaseHint;
begin
  pnlProjectCheckStatus.Caption := '';

  if Assigned(CheckerFrame) then
  begin
    if CheckerFrame.FirstChecker.CheckStatus = csNotBegin then
    begin
      // 对于原报，要区分新建项目和打回重新开始两种情况。前者不能显示。
      // 为了区分需要去服务器查询，势必影响速度。简单点，原报干脆不显示。
      if not FProjectData.CurUserIsAuthor then
      begin
        pnlProjectCheckStatus.Caption := '本期重新开始';
        pnlProjectCheckStatus.Font.Color := clRed;
      end;
    end
    else if CheckerFrame.OwnerFrame.CheckStatus = csFinished then
    begin
      pnlProjectCheckStatus.Caption := '本期已完成';
      pnlProjectCheckStatus.Font.Color := clGreen;
    end;
  end;

  pnlProjectCheckStatus.Update;
end;

procedure TProjectFrame.LocateMeasureBills(AID: Integer);
var
  vNode: TsdIDTreeNode;
begin
  dxsbViewControl.SelectedItem := dxsbViewControl.Groups[0].Items[xbiBillsMeasure.Tag];
  ChangeView(xbiBillsMeasure.Tag);
  with FProjectData.BillsMeasureData do
  begin
    vNode := BillsMeasureTree.FindNode(AID);
    if Assigned(vNode) then
      sdvBillsMeasure.LocateInControl(vNode.Rec);
  end;
end;

procedure TProjectFrame.ChangeView(APageIndex: Integer);
begin
  BeforeChangeView(APageIndex);
  case APageIndex of
    0, 2: jpsMain.ActivePageIndex := APageIndex;
    1, 3, 5: if CheckMeasureEdition then jpsMain.ActivePageIndex := APageIndex;
  end;
  AfterChangeView(APageIndex);
end;

procedure TProjectFrame.AfterChangeView(APageIndex: Integer);
begin
  // 仅计量台账界面可以选择计量期
  pnlPhaseSelect.Visible := APageIndex = xbiBillsMeasure.Tag;
  // 台账分解、计量台账、审核比较 可使用"显示至"功能
  tbExpand.Visible := (APageIndex = xbiBillsCompile.Tag)
                   or (APageIndex = xbiBillsMeasure.Tag)
                   or (APageIndex = xbiStageCompare.Tag);
  // 右侧按钮是否显示
  tbToolsButton.Visible := (APageIndex = xbiBillsCompile.Tag)
                        or (APageIndex = xbiBillsMeasure.Tag);
  tobtnBGL.Visible := APageIndex = xbiBillsMeasure.Tag;
  tobtnZJJL.Visible := APageIndex = xbiBillsMeasure.Tag;
  // 控制整个按钮工具栏显示，
  pnlToolBar.Visible := pnlPhaseSelect.Visible or tbExpand.Visible or tbToolsButton.Visible;
  // 根据当前View控制右侧按钮是否按下，右侧工具窗是否弹开
  jpsAssistant.ActivePageIndex := jpsMain.ActivePage.Tag;
  sbtnExpend.Tag := jpsMain.ActivePage.Tag;
  ControlAssistantButtonsDown(jpsMain.ActivePage.Tag);
  SetAssistantViewVisible(jpsMain.ActivePage.Tag <> -1);
  SetImageOfsbtnExpend(jpsMain.ActivePage.Tag <> -1);
  // 0号台账与计量台账的书签不同
  if APageIndex = xbiBillsCompile.Tag then
    FBookmarkFrame.BMType := bmtCompile
  else if APageIndex = xbiBillsMeasure.Tag then
    FBookmarkFrame.BMType := bmtMeasure;
  // 0号台账与计量台账的查找定位不同
  if APageIndex = xbiBillsCompile.Tag then
    FSearchFrame.LocateType := ltCompile
  else if APageIndex = xbiBillsMeasure.Tag then
    FSearchFrame.LocateType := ltMeasure;
  // 切换至清单汇总，须重新汇总
  if APageIndex = xbiBillsGather.Tag then
    BillsGatherFrame.RefreshBills;
  // 切换至材料调差，须重新汇总展示调差清单
  if APageIndex = xbiPriceMargin.Tag then
    PriceMarginFrame.RefreshBills;

  if G_IsCloud then
  begin
    if (APageIndex = xbiBillsCompile.Tag) or (APageIndex = xbiBillsMeasure.Tag) then
      CheckUpFile;

    tobtnUpFile.Visible := (APageIndex = xbiBillsMeasure.Tag) and (not ProjectData.IsGuest);
    if (tobtnUpFile.Visible = False) and (jpsAssistant.ActivePage = jpsAssistantUpFile) then
      jpsAssistant.ActivePage := jpsAssistantStandardBills;
  end;
end;

procedure TProjectFrame.BeforeChangeView(APageIndex: Integer);
begin
  if G_IsCloud then
  begin
    tobtnShowChecker.Visible := ProjectData.PhaseIndex > 0;
    tobtnShowChecker.Enabled := (APageIndex = xbiBillsMeasure.Tag);

    ButtonControl_NewPhase;

    if APageIndex = xbiBillsCompile.Tag then
    begin
      if tobtnShowChecker.Down then
      begin
        tobtnShowChecker.Down := False;
        tobtnShowChecker.Click;
        tobtnStandardBills.Down := True;
        tobtnStandardBills.Click;
        tobtnStandardBills.Down := False;
        tobtnStandardBills.Click;
      end;
    end;
  end;
  // 记录台账分解、计量台账等的右侧展开情况
  if jpsAssistant.Visible then
    jpsMain.ActivePage.Tag := jpsAssistant.ActivePageIndex
  else
    jpsMain.ActivePage.Tag := -1;
end;

procedure TProjectFrame.LocateZJJL(ABillsID: Integer);
var
  Rec: TsdDataRecord;
begin
  if not tobtnZJJL.Down then
  begin
    tobtnZJJL.Down := True;
    tobtnZJJL.Click;
  end;
  Rec := FProjectData.PhaseData.ZJJLData.FindZJJLRecord(ABillsID);
  FProjectData.PhaseData.ZJJLData.sdvZJJL.LocateInControl(Rec);
end;

procedure TProjectFrame.LocateCompileBills(AID: Integer);
var
  vNode: TsdIDTreeNode;
begin
  dxsbViewControl.SelectedItem := dxsbViewControl.Groups[0].Items[xbiBillsCompile.Tag];
  ChangeView(xbiBillsCompile.Tag);
  with FProjectData.BillsCompileData do
  begin
    vNode := BillsCompileTree.FindNode(AID);
    if Assigned(vNode) then
      sdvBillsCompile.LocateInControl(vNode.Rec);
  end;
end;

end.
