unit U_ExpenseInput;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, cxGraphics, cxCustomData, cxStyles, cxTL, cxMaskEdit, DB, ADODB,
  cxInplaceContainer, cxDBTL, cxControls, cxTLData, ComCtrls, ToolWin, StdCtrls,
  cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, DBClient,
  cxGridCustomTableView, cxGridTableView, cxGridDBTableView, ExtCtrls,
  cxSplitter, cxGridLevel, cxClasses, cxGridCustomView, cxGrid,
  cxGridCustomPopupMenu, cxGridPopupMenu, RM_Dataset, RM_System, RM_Common,
  RM_Class, RM_GridReport, IdBaseComponent, IdComponent, IdTCPConnection,
  IdTCPClient, IdFTP, ShellAPI, IniFiles, cxCheckBox, cxCalendar, cxButtonEdit,
  cxTextEdit, cxDropDownEdit, BtnEdit, cxLookAndFeels, cxLookAndFeelPainters,
  cxNavigator, dxDateRanges, dxBarBuiltInMenu, U_BaseList, cxContainer,
  cxCurrencyEdit, dxSkinsCore, dxSkinsDefaultPainters, dxCore, cxDateUtils,
  dxScrollbarAnnotations, Vcl.Menus, Clipbrd, dxCoreGraphics, dxSkinWXI;

type
  TfrmExpenseInput = class(TForm)
    ToolBar1: TToolBar;
    TBClose: TToolButton;
    ADOQueryTemp: TADOQuery;
    ADOQueryCmd: TADOQuery;
    ADOQueryMain: TADOQuery;
    ToolButton3: TToolButton;
    ScrollBox1: TScrollBox;
    Label7: TLabel;
    FinanceNote: TMemo;
    ReimburseType: TcxButtonEdit;
    Label1: TLabel;
    Currency: TcxComboBox;
    Label2: TLabel;
    Label3: TLabel;
    OppBankCardNo: TcxTextEdit;
    Label5: TLabel;
    Amount: TcxTextEdit;
    Label6: TLabel;
    Label8: TLabel;
    Label10: TLabel;
    OurBankCardNo: TcxTextEdit;
    Label12: TLabel;
    OurBankName: TcxButtonEdit;
    OppBankName: TcxButtonEdit;
    Label4: TLabel;
    FFID: TcxTextEdit;
    Label9: TLabel;
    Use: TcxTextEdit;
    OppCoName: TcxButtonEdit;
    Label11: TLabel;
    PayMent: TcxButtonEdit;
    PayTime: TcxDateEdit;
    Label13: TLabel;
    Label14: TLabel;
    BankSlipNumber: TcxTextEdit;
    Panel1: TPanel;
    Tv1: TcxGridDBTableView;
    cxGrid1Level1: TcxGridLevel;
    cxGrid1: TcxGrid;
    DS_1: TDataSource;
    CDS_1: TClientDataSet;
    Tv1CoName: TcxGridDBColumn;
    Tv1BankName: TcxGridDBColumn;
    Tv1BankNo: TcxGridDBColumn;
    Tv1ShuiNo: TcxGridDBColumn;
    PM_1: TPopupMenu;
    GPM_1: TcxGridPopupMenu;
    N1: TMenuItem;
    Label15: TLabel;
    IVNo: TcxButtonEdit;
    oppShuiNo: TcxTextEdit;
    procedure FormDestroy(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure TBCloseClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure TBRafreshClick(Sender: TObject);
    procedure ToolButton3Click(Sender: TObject);
    procedure PayMentBtnDnClick(Sender: TObject);
    procedure PayMentBtnUpClick(Sender: TObject);
    procedure OppCoNameBtnUpClick(Sender: TObject);
    procedure ReimburseTypePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure OurBankNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure OppBankNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure OppCoNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure PayMentPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure AmountPropertiesEditValueChanged(Sender: TObject);
    procedure TaxNumberPropertiesChange(Sender: TObject);
    procedure Tv1DblClick(Sender: TObject);
    procedure ScrollBox1Click(Sender: TObject);
    procedure N1Click(Sender: TObject);
    procedure cxButtonEdit1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
  private
    { Private declarations }
    procedure InitGrid();
    function SaveData(): Boolean;
    procedure InitGrid2();
  public
    { Public declarations }
    FFFID: string;
    FoppShuiNoChange: string;
  end;

var
  frmExpenseInput: TfrmExpenseInput;

implementation

uses
  U_DataLink, U_RTFun, U_ZDYHelp, U_CompanySel, U_BankSel, U_FinTradePlanSel,
  U_FinTradeSalesContractSel, U_ZDYBankSel, U_InvoiceSel;

{$R *.dfm}

procedure TfrmExpenseInput.InitGrid();
var
  nAmount: Double;
begin
  try

    ADOQueryMain.DisableControls;
    with ADOQueryMain do
    begin
      Filtered := False;
      Close;
      SQL.Clear;
      sql.Add(' select * from Finance_Flow where FFID=''' + Trim(FFFID) + '''');
      Open;
    end;
    if not ADOQueryMain.IsEmpty then
    begin
      SCSHData(ADOQueryMain, ScrollBox1, 2);
      Self.IVNo.Properties.LookupItems.Text := ADOQueryMain.FieldByName('IVID').AsString;

      if ADOQueryMain.FieldByName('Amount').AsString <> '' then
      begin
        nAmount := ADOQueryMain.FieldByName('Amount').AsFloat;
        Amount.Text := FormatFloat('#,##0.00', nAmount);
      end;
    end
    else
    begin
//      FFTime.DateTime := SGetServerDateTime(ADOQueryTemp);
    end;

  finally
    ADOQueryMain.EnableControls;
  end;
end;

procedure TfrmExpenseInput.InitGrid2();
begin

  try
    ADOQueryCmd.DisableControls;
    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('select A.* from BS_Company A where 1=1 ');
      sql.Add(' and A.CoType=''供应商'' ');
      SQL.Add(' and ShuiNo like ''%' + oppShuiNo.Text + '%'' ');
      Open;
    end;

    SCreateCDS(ADOQueryCmd, CDS_1);
    SInitCDSData(ADOQueryCmd, CDS_1);
  finally
    ADOQueryCmd.EnableControls;
    TV1.DataController.Filter.Clear;
  end;
end;

procedure TfrmExpenseInput.N1Click(Sender: TObject);
begin
  Clipboard.SetTextBuf(PChar(Trim(CDS_1.fieldbyname(TV1.Controller.FocusedColumn.DataBinding.FilterFieldName).AsString)));
end;

procedure TfrmExpenseInput.OppBankNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
var
  fsj: string;
  FWZ: Integer;
begin
  fsj := Trim(TcxButtonEdit(Sender).Hint);
  FWZ := Pos('/', fsj); //先英文再中文
  try
    frmZDYBankSel := TfrmZDYBankSel.Create(Application);
    with frmZDYBankSel do
    begin
      MainType := '财务银行';
      flag := Copy(fsj, 1, FWZ - 1);
      flagname := Copy(fsj, FWZ + 1, Length(fsj) - FWZ);
      if ShowModal = 1 then
      begin
        OppBankName.Text := Trim(ClientDataSet1.fieldbyname('ZDYName').AsString);
        OppBankCardNo.Text := Trim(ClientDataSet1.fieldbyname('note').AsString);
      end;
    end;
  finally
    frmZDYBankSel.Free;
  end;
end;

procedure TfrmExpenseInput.OppCoNameBtnUpClick(Sender: TObject);
begin

  try
    frmZDYHelp := TfrmZDYHelp.Create(Application);
    with frmZDYHelp do
    begin
      flag := 'OppCoName';
      flagname := '对方单位';
      if ShowModal = 1 then
      begin
        TEdit(Sender).Text := Trim(ClientDataSet1.fieldbyname('ZDYName').AsString);
      end;
    end;
  finally
    frmZDYHelp.Free;
  end;
end;

procedure TfrmExpenseInput.OppCoNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmCompanySel := TfrmCompanySel.Create(Application);
    with frmCompanySel do
    begin
      FCoType := '供应商';
      if ShowModal = 1 then
      begin
        OppCoName.Text := Trim(frmCompanySel.CDS_1.fieldbyname('CoName').AsString);
        OppCoName.Properties.LookupItems.Text := Trim(frmCompanySel.CDS_1.fieldbyname('CoCode').AsString);
        oppShuiNo.Text := Trim(frmCompanySel.CDS_1.fieldbyname('ShuiNo').AsString);
        OppBankName.Text := Trim(frmCompanySel.CDS_1.fieldbyname('BankName').AsString);
        OppBankCardNo.Text := Trim(frmCompanySel.CDS_1.fieldbyname('BankNo').AsString);

      end;
    end;

    Panel1.Visible := False;
  finally
    frmCompanySel.Free;
  end;
end;

procedure TfrmExpenseInput.OurBankNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
var
  fsj: string;
  FWZ: Integer;
begin
  fsj := Trim(TcxButtonEdit(Sender).Hint);
  FWZ := Pos('/', fsj); //先英文再中文
  try
    frmZDYBankSel := TfrmZDYBankSel.Create(Application);
    with frmZDYBankSel do
    begin
      MainType := '财务银行';
      flag := Copy(fsj, 1, FWZ - 1);
      flagname := Copy(fsj, FWZ + 1, Length(fsj) - FWZ);
      if ShowModal = 1 then
      begin
        OurBankName.Text := Trim(ClientDataSet1.fieldbyname('ZDYName').AsString);
        OurBankCardNo.Text := Trim(ClientDataSet1.fieldbyname('note').AsString);
      end;
    end;
  finally
    frmZDYBankSel.Free;
  end;
end;

procedure TfrmExpenseInput.FormDestroy(Sender: TObject);
begin
  frmExpenseInput := nil;
end;

procedure TfrmExpenseInput.PayMentBtnDnClick(Sender: TObject);
begin
  TBtnEditC(Sender).Text := '';
  TBtnEditC(Sender).TxtCode := '';
end;

procedure TfrmExpenseInput.PayMentBtnUpClick(Sender: TObject);
var
  fsj: string;
  FWZ: Integer;
begin
  fsj := Trim(TEdit(Sender).Hint);
  FWZ := Pos('/', fsj);
  try
    frmZDYHelp := TfrmZDYHelp.Create(Application);
    with frmZDYHelp do
    begin
      MainType := '费用';
      flag := Copy(fsj, 1, FWZ - 1);
      flagname := Copy(fsj, FWZ + 1, Length(fsj) - FWZ);
      if ShowModal = 1 then
      begin
        TEdit(Sender).Text := Trim(ClientDataSet1.fieldbyname('ZDYName').AsString);
      end;
    end;
  finally
    frmZDYHelp.Free;
  end;
end;

procedure TfrmExpenseInput.PayMentPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
var
  fsj: string;
  FWZ: Integer;
begin
  fsj := Trim(TcxButtonEdit(Sender).Hint);
  FWZ := Pos('/', fsj); //先英文再中文
  try
    frmZDYHelp := TfrmZDYHelp.Create(Application);
    with frmZDYHelp do
    begin
      MainType := Copy(fsj, FWZ + 1, Length(fsj) - FWZ);
      flag := Copy(fsj, 1, FWZ - 1);
      flagname := Copy(fsj, FWZ + 1, Length(fsj) - FWZ);
      if ShowModal = 1 then
      begin
        TcxButtonEdit(Sender).Text := Trim(ClientDataSet1.fieldbyname('ZDYName').AsString);
      end;
    end;
  finally
    frmZDYHelp.Free;
  end;
end;

procedure TfrmExpenseInput.ReimburseTypePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
var
  fsj: string;
  FWZ: Integer;
begin
  fsj := Trim(TcxButtonEdit(Sender).Hint);
  FWZ := Pos('/', fsj); //先英文再中文
  try
    frmZDYHelp := TfrmZDYHelp.Create(Application);
    with frmZDYHelp do
    begin
      MainType := Copy(fsj, FWZ + 1, Length(fsj) - FWZ);
      flag := Copy(fsj, 1, FWZ - 1);
      flagname := Copy(fsj, FWZ + 1, Length(fsj) - FWZ);
      if ShowModal = 1 then
      begin
        TcxButtonEdit(Sender).Text := Trim(ClientDataSet1.fieldbyname('ZDYName').AsString);
      end;
    end;
  finally
    frmZDYHelp.Free;
  end;
end;

//procedure TfrmExpenseInput.AmountPropertiesEditValueChanged(Sender: TObject);
//var
//  n: Double;
//  CleanText: string;
//begin
//  // 移除千分位逗号
//  CleanText := StringReplace(Amount.Text, ',', '', [rfReplaceAll]);
//
//  if TryStrToFloat(CleanText, n) then
//  begin
//    // 格式化显示，但避免重复触发事件
//    Amount.Properties.OnEditValueChanged := nil;  // 暂时禁用事件
//    try
//      Amount.Text := FormatFloat('#,##0', n);
//    finally
//      Amount.Properties.OnEditValueChanged := AmountPropertiesEditValueChanged;
//    end;
//  end;
//end;

procedure TfrmExpenseInput.AmountPropertiesEditValueChanged(Sender: TObject);
var
  n: Double;
  CleanText: string;
  DecimalPos: Integer;
  DecimalDigits: Integer;
  FormatStr: string;
  CaretPos: Integer;
  TextBeforeCaret: string;
begin
  // 记住光标位置和光标前的文本
  CaretPos := Amount.SelStart;
  TextBeforeCaret := Copy(Amount.Text, 1, CaretPos);

  // 移除千分位逗号
  CleanText := StringReplace(Amount.Text, ',', '', [rfReplaceAll]);

  if TryStrToFloat(CleanText, n) then
  begin
    Amount.Properties.OnEditValueChanged := nil;
    try
      // 检测用户输入的小数位数
      DecimalPos := Pos('.', CleanText);
      if DecimalPos > 0 then
        DecimalDigits := Length(CleanText) - DecimalPos
      else
        DecimalDigits := 0;

      // 动态生成格式化字符串
      if DecimalDigits = 0 then
        FormatStr := '#,##0'
      else
        FormatStr := '#,##0.' + StringOfChar('0', DecimalDigits);

      // 应用格式化
      Amount.Text := FormatFloat(FormatStr, n);

      // 智能恢复光标位置
      if CaretPos > 0 then
      begin
        // 计算添加逗号后的光标位置偏移
        CaretPos := Length(TextBeforeCaret) + (StringReplace(Copy(Amount.Text, 1, Length(TextBeforeCaret)), ',', '', [rfReplaceAll]).Length - TextBeforeCaret.Length);
        if CaretPos <= Length(Amount.Text) then
          Amount.SelStart := CaretPos;
      end;
    finally
      Amount.Properties.OnEditValueChanged := AmountPropertiesEditValueChanged;
    end;
  end;
end;

procedure TfrmExpenseInput.cxButtonEdit1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
var
  CurrentAmount: Double;
  TaxAmount: Double;
begin
  try
    frmInvoiceSel := TfrmInvoiceSel.Create(Application);
    with frmInvoiceSel do
    begin
      if ShowModal = 1 then
      begin
        FoppShuiNoChange := '0';
        Self.IVNo.Text := '';

        Self.IVNo.Properties.LookupItems.Text := '';
        Self.Amount.Text := '0';
//        ftype := '进项';
        while CDS_Invoice.Locate('SSel', true, []) do
        begin

          with frmInvoiceSel.CDS_Invoice do
          begin
            CurrentAmount := StrToFloatDef(StringReplace(Self.Amount.Text, ',', '', [rfReplaceAll]), 0);
            TaxAmount := FieldByName('TaxAmount').AsFloat;
            if Self.IVNo.Text = '' then
            begin
              Self.IVNo.Text := frmInvoiceSel.CDS_Invoice.FieldByName('IVNo').AsString;
              Self.IVNo.Properties.LookupItems.Text := frmInvoiceSel.CDS_Invoice.FieldByName('IVID').AsString;

              Self.Amount.Text := FormatFloat('#,##0.00', TaxAmount);
//              Self.Amount.Text := frmInvoiceSel.CDS_Invoice.FieldByName('TaxAmount').AsString;
            end
            else
            begin
              Self.IVNo.Text := Trim(Self.IVNo.Text) + ',' + Trim(frmInvoiceSel.CDS_Invoice.FieldByName('IVNo').AsString);
              Self.IVNo.Properties.LookupItems.Text := trim(Self.IVNo.Properties.LookupItems.Text) + ',' + Trim(frmInvoiceSel.CDS_Invoice.FieldByName('IVID').AsString);
              Self.Amount.Text := FormatFloat('#,##0.00', CurrentAmount + TaxAmount);
//              Self.Amount.Text := FloatToStr(strtofloatdef(Self.Amount.Text, 0) + frmInvoiceSel.CDS_Invoice.FieldByName('TaxAmount').asfloat);
            end;

            Self.OppCoName.Text := frmInvoiceSel.CDS_Invoice.FieldByName('Supplier').AsString;
            Self.OppCoName.Properties.LookupItems.Text := frmInvoiceSel.CDS_Invoice.FieldByName('CoCode').AsString;
            Self.oppShuiNo.Text := trim(frmInvoiceSel.CDS_Invoice.FieldByName('SupplierShuiNo').AsString);

            Self.Currency.Text := frmInvoiceSel.CDS_Invoice.FieldByName('Currency').AsString;
            Self.OppBankName.text := frmInvoiceSel.CDS_Invoice.FieldByName('BankName').AsString;
            Self.OppBankCardNo.text := frmInvoiceSel.CDS_Invoice.FieldByName('BankNo').AsString;

            OurBankName.Text := Trim(frmInvoiceSel.CDS_Invoice.fieldbyname('BankDeposit').AsString);
            OurBankCardNo.Text := Trim(frmInvoiceSel.CDS_Invoice.fieldbyname('BankCardNo').AsString);

          end;
          CDS_Invoice.Delete;
        end;

        FoppShuiNoChange := '1';
      end;
    end;
  finally
    frmInvoiceSel.Free;
  end;
end;

procedure TfrmExpenseInput.FormClose(Sender: TObject; var Action: TCloseAction);
begin

  Action := caFree;
end;

procedure TfrmExpenseInput.TaxNumberPropertiesChange(Sender: TObject);
begin
  if FoppShuiNoChange <> '0' then
  begin
    InitGrid2();
    Panel1.Visible := True;
  end;

end;

procedure TfrmExpenseInput.TBCloseClick(Sender: TObject);
begin

  close;
end;

procedure TfrmExpenseInput.FormShow(Sender: TObject);
begin
  InitGrid();
  Panel1.Visible := False;
end;

procedure TfrmExpenseInput.TBRafreshClick(Sender: TObject);
begin
  InitGrid();
end;

function TfrmExpenseInput.SaveData(): Boolean;
var
  MaxId, MaxSubId, FCoCode, FCCID: string;
  CleanAmount: string;
begin
  try
    ADOQueryCmd.Connection.BeginTrans;
    if Trim(FFFID) = '' then
    begin
      if not GetLSNo(ADOQueryCmd, MaxId, 'FS', 'Finance_Flow', 4, 1) then
        raise Exception.Create('取最大号失败！');
    end
    else
    begin
      MaxId := Trim(FFFID);
    end;

    FFID.Text := MaxId;
    CleanAmount := StringReplace(Amount.Text, ',', '', [rfReplaceAll]);

    with ADOQueryCmd do
    begin
      Close;
      SQL.Clear;
      sql.Add('select * from Finance_Flow where FFID=''' + Trim(FFFID) + '''');
      Open;
    end;
    with ADOQueryCmd do
    begin
      if Trim(FFFID) = '' then
      begin
        Append;
        FieldByName('FillId').Value := Trim(DCode);
        FieldByName('Filler').Value := Trim(DName);
        FieldByName('Filltime').Value := SGetServerDateTime(ADOQueryTemp);
        FieldByName('FFTime').Value := SGetServerDateTime(ADOQueryTemp);
        FieldByName('FFFlag').Value := '费用';
        FieldByName('FFType').Value := '费用登记';
        FieldByName('Checkstatus').Value := '未审核';
        FieldByName('PayStatus').Value := '未付款';
        FieldByName('PrintStatus').Value := '未打印';
        FieldByName('FFQtyFlag').Value := 1;   //出入库标记
      end
      else
      begin
        Edit;
        FieldByName('EditId').Value := Trim(DCode);
        FieldByName('Editer').Value := Trim(DName);
        FieldByName('Edittime').Value := SGetServerDateTime(ADOQueryTemp);
      end;
//      FieldByName('OppCoNo').Value := Trim(OppCoName.TxtCode);
//      FieldByName('OurCoNo').Value := Trim(OurCoName.TxtCode);
//      FieldByName('OurBankID').Value := Trim(OurBankName.TxtCode);
//      FieldByName('FFID').Value := Trim(MaxId);
      FieldByName('OppCoNo').Value := trim(OppCoName.Properties.LookupItems.Text);
      FieldByName('IVID').Value := trim(IVNO.Properties.LookupItems.Text);
      if CleanAmount <> '' then
        FieldByName('Amount').AsFloat := StrToFloatDef(CleanAmount, 0);

      RTSetsavedata(ADOQueryCmd, 'Finance_Flow', ScrollBox1, 2);
      Post;
    end;

    ADOQueryCmd.Connection.CommitTrans;
    FCCID := Trim(MaxSubId);
    Result := True;
  except
    Result := false;
    ADOQueryCmd.Connection.RollbackTrans;
    application.MessageBox(PChar(Exception(ExceptObject).Message), '提示信息', 0);
  end;
end;

procedure TfrmExpenseInput.ScrollBox1Click(Sender: TObject);
begin
  Panel1.Visible := False;
end;

procedure TfrmExpenseInput.ToolButton3Click(Sender: TObject);
begin
  ToolBar1.SetFocus;
  if Trim(OppCoName.Text) = '' then
  begin
    Application.MessageBox('对方单位不能为空!', '提示', 0);
    Exit;
  end;

  if Trim(Currency.Text) = '' then
  begin
    Application.MessageBox('币种不能为空!', '提示', 0);
    Exit;
  end;
  if SaveData() then
  begin
    Application.MessageBox('保存成功!', '提示', 0);
    ModalResult := 1;
  end;
end;

procedure TfrmExpenseInput.Tv1DblClick(Sender: TObject);
begin
  OppCoName.Text := Trim(CDS_1.fieldbyname('CoName').AsString);
  OppCoName.Properties.LookupItems.Text := Trim(CDS_1.fieldbyname('CoCode').AsString);
  oppShuiNo.Text := Trim(CDS_1.fieldbyname('ShuiNo').AsString);
  OppBankName.Text := Trim(CDS_1.fieldbyname('BankName').AsString);
  OppBankCardNo.Text := Trim(CDS_1.fieldbyname('BankNo').AsString);

  Panel1.Visible := false;
end;

end.

