unit U_InvoiceOutSel;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComCtrls, ToolWin, cxStyles, cxCustomData, cxGraphics, cxFilter,
  cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxClasses,
  cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
  cxGridDBTableView, cxGrid, cxGridCustomPopupMenu, cxGridPopupMenu, ADODB,
  DBClient, ExtCtrls, StdCtrls, BtnEdit, cxButtonEdit, cxTextEdit,
  cxDropDownEdit, cxLookAndFeels, cxLookAndFeelPainters, cxNavigator, cxCalendar,
  dxDateRanges, dxBarBuiltInMenu, ComObj, dxSkinsCore, dxSkinsDefaultPainters,
  dxScrollbarAnnotations, cxPC, cxContainer, dxCore, cxDateUtils, cxCheckBox,
  cxMaskEdit, dxSkinWXI, cxCurrencyEdit;

type
  TfrmInvoiceOutSel = class(TForm)
    DataSource1: TDataSource;
    CDS_Invoice: TClientDataSet;
    GPM_1: TcxGridPopupMenu;
    ToolBar1: TToolBar;
    TSave: TToolButton;
    TBClose: TToolButton;
    cxGrid1: TcxGrid;
    Tv1: TcxGridDBTableView;
    Tv1Price: TcxGridDBColumn;
    cxGridLevel1: TcxGridLevel;
    ADOQueryTmp: TADOQuery;
    ADOQueryCmd: TADOQuery;
    Tv1TaxAmount: TcxGridDBColumn;
    Tv1TaxFee: TcxGridDBColumn;
    Tv1IVNo: TcxGridDBColumn;
    Tv1IVDate: TcxGridDBColumn;
    ToolButton1: TToolButton;
    ToolButton2: TToolButton;
    ToolButton3: TToolButton;
    Tv1Currency: TcxGridDBColumn;
    ToolButton4: TToolButton;
    CDS_LM: TClientDataSet;
    OpenDialog1: TOpenDialog;
    Tv1BGDNum: TcxGridDBColumn;
    Tv1SupplierShuiNo: TcxGridDBColumn;
    Tv1Supplier: TcxGridDBColumn;
    Tv1OurShuiNo: TcxGridDBColumn;
    Tv1OurCoName: TcxGridDBColumn;
    Tv1BillCycle: TcxGridDBColumn;
    ToolButton5: TToolButton;
    Tv1fromFlow: TcxGridDBColumn;
    Tbssel: TToolButton;
    cxTabControl1: TcxTabControl;
    Panel1: TPanel;
    Label1: TLabel;
    begdate: TcxDateEdit;
    Enddate: TcxDateEdit;
    ToolButton6: TToolButton;
    Label4: TLabel;
    Tv1Column1: TcxGridDBColumn;
    procedure TBCloseClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure TSaveClick(Sender: TObject);
    procedure v1P_CodeNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure v1P_SpecPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure v1QtyUnitPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure v1QtyPropertiesEditValueChanged(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure Tv1Column2PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure Tv1Column3PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure Tv1Column6PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure ToolButton1Click(Sender: TObject);
    procedure ToolButton2Click(Sender: TObject);
    procedure ToolButton3Click(Sender: TObject);
    procedure Tv1Column4PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure ToolButton4Click(Sender: TObject);
    procedure Tv1SupplierPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure ButtonEdit(Sender: TObject; AButtonIndex: Integer);
    procedure Tv1AmountPropertiesEditValueChanged(Sender: TObject);
    procedure ToolButton5Click(Sender: TObject);
    procedure TbsselClick(Sender: TObject);
    procedure Tv1DblClick(Sender: TObject);
    procedure cxTabControl1Change(Sender: TObject);
    procedure ToolButton6Click(Sender: TObject);
  private
    procedure initGrid();
    procedure SaveDate();
    procedure SaveFlowInvoice();
    { Private declarations }
  public
    FIVID: string;
    fInvoiceFlag: string;
    { Public declarations }
  end;

var
  frmInvoiceOutSel: TfrmInvoiceOutSel;

implementation

uses
  U_RTFun, U_ZDYHelp, U_CompanySel, U_dataLink, U_PayableSel;
{$R *.dfm}

//procedure TfrmInvoiceInInPut.SaveFlowInvoice();
//var
//  sl: TStringList;
//  i: Integer;
//begin
//  with CDS_Invoice do
//  begin
//    first;
//    while not eof do
//    begin
//      if fieldbyname('IVID').AsString <> '' then
//      begin
//        with ADOQueryCmd do
//        begin
//          close;
//          sql.Clear;
//          sql.add('delete from Finance_FlowInvoice where IVID=' + quotedstr(Trim(CDS_Invoice.fieldbyname('IVID').AsString)));
//          ExecSQL;
//        end;
//
//        with ADOQueryCmd do
//        begin
//          close;
//          sql.Clear;
//          sql.add('exec P_InsertFinanceFlowInvoice @IVID=' + quotedstr(Trim(CDS_Invoice.fieldbyname('IVID').AsString)));
//          sql.Add(' ,@fffIDs=' + quotedstr(Trim(CDS_Invoice.fieldbyname('fromFlow').AsString)) );
//          ExecSQL;
//        end;
//
//
//      end;
//      CDS_Invoice.Next;
//    end;
//  end;
//end;

procedure TfrmInvoiceOutSel.SaveFlowInvoice();
begin
  if CDS_Invoice.IsEmpty then
    Exit;

  // 开始事务（假设使用ADO事务）
  ADOQueryCmd.Connection.BeginTrans;
  try
    CDS_Invoice.DisableControls;
    CDS_Invoice.First;

    while not CDS_Invoice.Eof do
    begin
      if Trim(CDS_Invoice.FieldByName('IVID').AsString) <> '' then
      begin
        // 使用参数化查询
        with ADOQueryCmd do
        begin
          Close;
          SQL.Text := 'delete from Finance_FlowInvoice where IVID = :IVID';
          Parameters.ParamByName('IVID').Value := Trim(CDS_Invoice.FieldByName('IVID').AsString);
          ExecSQL;

          Close;
          SQL.Text := 'exec P_InsertFinanceFlowInvoice @IVID = :IVID, @fffIDs = :fffIDs';
          Parameters.ParamByName('IVID').Value := Trim(CDS_Invoice.FieldByName('IVID').AsString);
          Parameters.ParamByName('fffIDs').Value := Trim(CDS_Invoice.FieldByName('fromFlow').AsString);
//          ShowMessage(sql.Text);
          ExecSQL;
        end;
      end;

      CDS_Invoice.Next;  // 移动到下一条记录
    end;

    CDS_Invoice.EnableControls;
    ADOQueryCmd.Connection.CommitTrans;  // 提交事务
//    ShowMessage('保存成功！');
  except
    ADOQueryCmd.Connection.RollbackTrans;  // 出错回滚
    raise;  // 重新抛出异常

  end;
end;

procedure TfrmInvoiceOutSel.SaveDate();
var
  MaxNo: string;
begin
  ADOQueryCmd.Connection.BeginTrans;
  try
    with CDS_Invoice do
    begin
      first;
      while not eof do
      begin
        if fieldbyname('IVID').AsString = '' then
        begin
          if GetLSNo(ADOQueryTmp, MaxNo, 'IJ', 'Finance_Invoice', 4, 1) = False then
            raise Exception.Create('取最大号失败！');
        end
        else
          MaxNo := CDS_Invoice.fieldbyname('IVID').AsString;

        with ADOQueryCmd do
        begin
          close;
          sql.Clear;
          sql.add('select * from Finance_Invoice where IVID=' + quotedstr(Trim(MaxNo)));
          open;
        end;
        if ADOQueryCmd.IsEmpty then
        begin
          ADOQueryCmd.append;
          ADOQueryCmd.FieldByName('FillId').Value := Trim(DCode);
          ADOQueryCmd.FieldByName('Filler').Value := Trim(DName);
          ADOQueryCmd.FieldByName('status').Value := '0';
        end
        else
        begin
          ADOQueryCmd.edit;
          ADOQueryCmd.FieldByName('EditId').Value := Trim(DCode);
          ADOQueryCmd.FieldByName('Editer').Value := Trim(DName);
          ADOQueryCmd.FieldByName('Edittime').Value := SGetServerDateTime(ADOQueryTmp);
        end;
        RTSetSaveDataCDS(ADOQueryCmd, Tv1, CDS_Invoice, 'Finance_Invoice', 0);
        ADOQueryCmd.fieldbyname('IVID').Value := MaxNo;
        ADOQueryCmd.fieldbyname('IVFlag').Value := '进项';
//        ADOQueryCmd.fieldbyname('OppCoNo').Value := trim(CDS_Invoice.FieldByName('OppCoNo').AsString);
//        ADOQueryCmd.fieldbyname('OppParentCoNo').Value := trim(CDS_Invoice.FieldByName('OppParentCoNo').AsString);
        ADOQueryCmd.FieldByName('SupplierShuiNo').Value := Trim(CDS_Invoice.fieldbyname('SupplierShuiNo').AsString);
        ADOQueryCmd.fieldbyname('OurCoNo').Value := trim(CDS_Invoice.FieldByName('OurCoNo').AsString);
        ADOQueryCmd.fieldbyname('PayDate').Value := trim(CDS_Invoice.FieldByName('PayDate').AsString);

        ADOQueryCmd.Post;
        CDS_Invoice.Edit;
        CDS_Invoice.FieldByName('IVId').Value := MaxNo;
        CDS_Invoice.Post;
        next;
      end;
    end;
    ADOQueryCmd.Connection.CommitTrans;
    application.MessageBox('保存成功！', '提示');

  except
    ADOQueryCmd.Connection.RollbackTrans;
    application.MessageBox(PChar(Exception(ExceptObject).Message), '提示信息', 0);
  end;
end;

procedure TfrmInvoiceOutSel.initGrid();
begin
  with ADOQueryTmp do
  begin
    close;
    sql.Clear;
    sql.Add('select A.*,B.BankName,B.BankNo,B.CoCode,C.BankDeposit,C.BankCardNo  from Finance_Invoice A ');

    sql.add(' left join BS_Company B on  A.SupplierNo = B.CoCode ');
    SQL.Add(' LEFT JOIN (');
    SQL.Add('   SELECT *, ROW_NUMBER() OVER (PARTITION BY GSTT ORDER BY (SELECT NULL)) AS rn');
    SQL.Add('   FROM BS_Bank');
    SQL.Add(' ) C ON A.OurCoName = C.GSTT AND C.rn = 1');

    sql.add(' where isnull(A.Status,''0'')=''9'' ');

    if cxTabControl1.TabIndex = 1 then
    begin
      sql.Add(' and A.ivdate>=''' + FormatDateTime('yyyy-MM-dd', begdate.Date) + ''' ');
      sql.Add(' and A.ivdate<''' + FormatDateTime('yyyy-MM-dd', Enddate.Date + 1) + ''' ');
    end;
    if cxTabControl1.TabIndex = 0 then
    begin
      sql.add(' and not exists (select 1 from Finance_Flow X where X.IVID = A.IVID) ');
    end;
    if cxTabControl1.TabIndex = 1 then
    begin
      sql.add(' and  exists (select 1 from Finance_Flow X where X.IVID = A.IVID) ');
    end;

    sql.Add(' and IVFlag=''销项'' ');

    open;
  end;

  SCreateCDS(ADOQueryTmp, CDS_Invoice);
  SInitCDSData(ADOQueryTmp, CDS_Invoice);
end;

procedure TfrmInvoiceOutSel.TBCloseClick(Sender: TObject);
begin

  Close;
end;

procedure TfrmInvoiceOutSel.TbsselClick(Sender: TObject);
begin
  if cxTabControl1.TabIndex <> 0 then
  begin
    Exit;
  end;
  if CDS_Invoice.IsEmpty then
  begin
    Exit;
  end;
  ModalResult := 1;
end;

procedure TfrmInvoiceOutSel.FormShow(Sender: TObject);
begin
  ReadCxGrid(Self.Caption + 'TV1', Tv1, '财务管理');
  with CDS_LM do
  begin
    FieldDefs.Clear;
    FieldDefs.Add('LXH', ftInteger, 0);
    FieldDefs.Add('lCode', ftString, 40);
    FieldDefs.Add('LName', ftString, 40);
    close;
    CreateDataSet;
  end;
  Enddate.Date := SGetServerDate(ADOQueryTmp);
  begdate.Date := Enddate.Date - 30;
  Tbssel.Visible := (cxTabControl1.TabIndex = 0);
  initGrid();
end;

procedure TfrmInvoiceOutSel.TSaveClick(Sender: TObject);
begin

  if CDS_Invoice.Locate('IVNo', null, []) then
  begin
    application.MessageBox('发票号不能为空', '提示');
    exit;
  end;
  if CDS_Invoice.Locate('OurCoName', null, []) then
  begin
    application.MessageBox('我方单位不能为空', '提示');
    exit;
  end;
  if not CDS_Invoice.FieldByName('IVDate').isnull then
  begin
    if CDS_Invoice.FieldByName('BillCycle').asstring <> '' then
    begin
      CDS_Invoice.Edit;
      CDS_Invoice.FieldByName('PayDate').AsDateTime := CDS_Invoice.FieldByName('IVDate').AsDateTime + StrToIntDef(Trim(CDS_Invoice.FieldByName('BillCycle').AsString), 0);
      CDS_Invoice.Post;
    end
    else
    begin
      CDS_Invoice.Edit;
      CDS_Invoice.FieldByName('PayDate').Value := CDS_Invoice.FieldByName('IVDate').Value;
      CDS_Invoice.Post;
    end;
  end;

  SaveDate();
  SaveFlowInvoice();
  Modalresult := 1;
end;

procedure TfrmInvoiceOutSel.v1P_CodeNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmZDYHelp := TfrmZDYHelp.Create(Application);
    with frmZDYHelp do
    begin
      flag := 'MPRTCodeName';
      flagname := '产品名称';
      if ShowModal = 1 then
      begin
        Self.CDS_Invoice.Edit;
        Self.CDS_Invoice.FieldByName('P_CodeName').Value := Trim(ClientDataSet1.fieldbyname('ZDYName').AsString);
        Self.CDS_Invoice.FieldByName('P_Code').Value := Trim(ClientDataSet1.fieldbyname('ZDYNo').AsString);
      end;
    end;
  finally
    frmZDYHelp.Free;
  end;
  //self.tv1.Controller.EditingController.ShowEdit();
end;

procedure TfrmInvoiceOutSel.v1P_SpecPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmZDYHelp := TfrmZDYHelp.Create(Application);
    with frmZDYHelp do
    begin
      flag := 'P_Spec';
      flagname := '成品规格';
      if ShowModal = 1 then
      begin
        Self.CDS_Invoice.Edit;
        Self.CDS_Invoice.FieldByName('P_Spec').Value := Trim(ClientDataSet1.fieldbyname('ZDYName').AsString);
      end;
    end;
  finally
    frmZDYHelp.Free;
  end;
end;

procedure TfrmInvoiceOutSel.v1QtyUnitPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmZDYHelp := TfrmZDYHelp.Create(Application);
    with frmZDYHelp do
    begin
      flag := 'QtyUnit';
      flagname := '数量单位';
      if ShowModal = 1 then
      begin
        Self.CDS_Invoice.Edit;
        Self.CDS_Invoice.FieldByName('QtyUnit').Value := Trim(ClientDataSet1.fieldbyname('ZDYName').AsString);
      end;
    end;
  finally
    frmZDYHelp.Free;
  end;
end;

procedure TfrmInvoiceOutSel.v1QtyPropertiesEditValueChanged(Sender: TObject);
var
  mvalue, FFieldName: string;
  FQty, FPrice, FAmount, Ftax, FtaxAmount: double;
begin
//  FFieldName := Trim(Tv1.Controller.FocusedColumn.DataBinding.FilterFieldName);
//  mvalue := TcxTextEdit(Sender).EditingText;
//  if Trim(mvalue) = '' then
//  begin
//    mvalue := '0';
//  end;
//  with CDS_Invoice do
//  begin
//    Edit;
//    FieldByName(FFieldName).Value := Trim(mvalue);
//    Post;
//    FQty := FieldbyName('Qty').AsFloat;
//    FtaxAmount := FieldbyName('taxAmount').AsFloat;
//    Ftax := FieldbyName('tax').AsFloat;
//  end;
//  if FQty <> 0 then
//  begin
//    FAmount := strtofloat(format('%.2f', [FtaxAmount / (1 + Ftax / 100)]));
//    FPrice := strtofloat(format('%.2f', [FAmount / FQty]));
//  end
//  else
//  begin
//    FPrice := 0;
//    FAmount := strtofloat(format('%.2f', [FtaxAmount / (1 + Ftax / 100)]));
//  end;
//
//  with CDS_Invoice do
//  begin
//    Edit;
//    FieldByName('Price').Value := FPrice;
//    FieldByName('Amount').Value := FAmount;
//    FieldByName('TaxFee').Value := FtaxAmount - FAmount;
//    Post;
//  end;
//  tv1.Controller.EditingController.ShowEdit();

end;

procedure TfrmInvoiceOutSel.cxTabControl1Change(Sender: TObject);
begin
  if cxTabControl1.TabIndex = 0 then
  begin
    Tbssel.visible := True;
  end
  else
  begin
    Tbssel.visible := false;
  end;
  initGrid();
end;

procedure TfrmInvoiceOutSel.FormDestroy(Sender: TObject);
begin
  frmInvoiceOutSel := nil;
end;

procedure TfrmInvoiceOutSel.Tv1AmountPropertiesEditValueChanged(Sender: TObject);
var
  mvalue, FFieldName: string;
  mAmount, mTaxFee, mTaxAmount: Double;
begin
  mvalue := TcxTextEdit(Sender).EditingText;
  if Trim(mvalue) = '' then
  begin
    mvalue := '0';
  end;
  FFieldName := Trim(Tv1.Controller.FocusedColumn.DataBinding.FilterFieldName);

  with CDS_Invoice do
  begin
    Edit;
    FieldByName(FFieldName).Value := StrToFloat(Trim(mvalue));
    Post;
//    ShowMessage(Fieldbyname('TaxRate').AsString);
    if Fieldbyname('Amount').AsString <> '' then
    begin
      mAmount := Fieldbyname('Amount').AsFloat;
    end
    else
    begin
      mAmount := 0;
    end;

    if Fieldbyname('TaxFee').AsString <> '' then
    begin
      mTaxFee := Fieldbyname('TaxFee').AsFloat;
    end
    else
    begin
      mTaxFee := 0;
    end;

  end;

  mTaxAmount := RoundFloat(mAmount + mTaxFee, 2);

  with CDS_Invoice do
  begin
    Edit;
    FieldByName('Amount').Value := mAmount;
//    FieldByName('ConPrice').Value := FConPrice;
    FieldByName('TaxFee').Value := mTaxFee;
    FieldByName('TaxAmount').Value := mTaxAmount;
    Post;
  end;
  tv1.Controller.EditingController.ShowEdit();

end;

procedure TfrmInvoiceOutSel.Tv1Column2PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmCompanySel := TfrmCompanySel.Create(Application);
    with frmCompanySel do
    begin
      FCoType := '我司';
      if ShowModal = 1 then
      begin

        Self.CDS_Invoice.Edit;
        Self.CDS_Invoice.FieldByName('OurCoNo').Value := Trim(CDS_1.fieldbyname('CoCode').AsString);
        Self.CDS_Invoice.FieldByName('OurCoName').Value := Trim(CDS_1.fieldbyname('CoAbbrName').AsString);

      end;
    end;
  finally
    frmCompanySel.Free;
  end;
end;

procedure TfrmInvoiceOutSel.Tv1Column3PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmZDYHelp := TfrmZDYHelp.Create(Application);
    with frmZDYHelp do
    begin
      flag := 'InvoiceType';
      flagname := '发票类型';
      if ShowModal = 1 then
      begin
        Self.CDS_Invoice.Edit;
        Self.CDS_Invoice.FieldByName('IVType').Value := Trim(ClientDataSet1.fieldbyname('ZDYName').AsString);

      end;
    end;
  finally
    frmZDYHelp.Free;
  end;
end;

procedure TfrmInvoiceOutSel.Tv1Column4PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmCompanySel := TfrmCompanySel.Create(Application);
    with frmCompanySel do
    begin
      FCoType := '供应商';
      if ShowModal = 1 then
      begin
        Self.CDS_Invoice.Edit;
        Self.CDS_Invoice.FieldByName('OppCoNo').Value := Trim(CDS_1.fieldbyname('CoCode').AsString);
        Self.CDS_Invoice.FieldByName('OppCoName').Value := Trim(CDS_1.fieldbyname('CoAbbrName').AsString);
        Self.CDS_Invoice.FieldByName('OppParentCoNo').Value := Trim(CDS_1.fieldbyname('CoCode').AsString);
        Self.CDS_Invoice.FieldByName('OppParentCoName').Value := Trim(CDS_1.fieldbyname('CoAbbrName').AsString);
      end;
    end;
  finally
    frmCompanySel.Free;
  end;
end;

procedure TfrmInvoiceOutSel.Tv1Column6PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmCompanySel := TfrmCompanySel.Create(Application);
    with frmCompanySel do
    begin
      FCoType := '供应商';
      if ShowModal = 1 then
      begin
        Self.CDS_Invoice.Edit;
        Self.CDS_Invoice.FieldByName('OppParentCoNo').Value := Trim(CDS_1.fieldbyname('CoCode').AsString);
        Self.CDS_Invoice.FieldByName('OppParentCoName').Value := Trim(CDS_1.fieldbyname('CoAbbrName').AsString);
      end;
    end;
  finally
    frmCompanySel.Free;
  end;
end;

procedure TfrmInvoiceOutSel.Tv1DblClick(Sender: TObject);
begin
  if cxTabControl1.TabIndex <> 0 then
  begin
    Exit;
  end;
  ModalResult := 1;
end;

procedure TfrmInvoiceOutSel.ButtonEdit(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmCompanySel := TfrmCompanySel.Create(Application);
    with frmCompanySel do
    begin
      FCoType := '我司';
      if ShowModal = 1 then
      begin
        CDS_Invoice.Edit;
        CDS_Invoice.FieldByName('OurCoName').Value := Trim(CDS_1.fieldbyname('CoName').AsString);
        CDS_Invoice.FieldByName('OurShuiNo').Value := Trim(CDS_1.fieldbyname('ShuiNo').AsString);
        CDS_Invoice.FieldByName('OurCoNo').Value := Trim(CDS_1.fieldbyname('CoCode').AsString);
        CDS_Invoice.Post;
      end;
    end;
  finally
    frmCompanySel.Free;
  end;
end;

procedure TfrmInvoiceOutSel.Tv1SupplierPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmCompanySel := TfrmCompanySel.Create(Application);
    with frmCompanySel do
    begin
      FCoType := '供应商';
      if ShowModal = 1 then
      begin
        CDS_Invoice.Edit;
        CDS_Invoice.FieldByName('Supplier').Value := Trim(CDS_1.fieldbyname('CoName').AsString);
        CDS_Invoice.FieldByName('SupplierShuiNo').Value := Trim(CDS_1.fieldbyname('ShuiNo').AsString);
        CDS_Invoice.FieldByName('SupplierNo').Value := Trim(CDS_1.fieldbyname('CoCode').AsString);

        CDS_Invoice.FieldByName('BillCycle').Value := Trim(CDS_1.fieldbyname('BillCycle').AsString);
        CDS_Invoice.Post;
      end;
    end;
  finally
    frmCompanySel.Free;
  end;
end;

procedure TfrmInvoiceOutSel.ToolButton1Click(Sender: TObject);
begin
  CDS_Invoice.Append;
  CDS_Invoice.FieldByName('IVDate').Value := now();
  CDS_Invoice.FieldByName('IVType').Value := '进项发票';
  CDS_Invoice.FieldByName('QtyUnit').Value := 'Kg';
  CDS_Invoice.FieldByName('Amount').Value := 0;
  CDS_Invoice.FieldByName('Qty').Value := 0;
  CDS_Invoice.FieldByName('tax').Value := 0;
  CDS_Invoice.FieldByName('TaxFee').Value := 0;
  CDS_Invoice.FieldByName('taxAmount').Value := 0;
  CDS_Invoice.FieldByName('Price').Value := 0;
  CDS_Invoice.FieldByName('tax').Value := 13;
  CDS_Invoice.FieldByName('Currency').Value := 'CNY';
  CDS_Invoice.Post;

end;

procedure TfrmInvoiceOutSel.ToolButton2Click(Sender: TObject);
begin
  if CDS_Invoice.IsEmpty then
    exit;
  if application.MessageBox('确定要删除吗', '提示', 1) = 2 then
    exit;
  with ADOQueryTmp do
  begin
    close;
    sql.clear;
    sql.add('delete from Finance_Invoice where IvID=''' + trim(CDS_Invoice.fieldbyname('IvID').asstring) + ''' ');
    execsql;
  end;
  CDS_Invoice.delete;
end;

procedure TfrmInvoiceOutSel.ToolButton3Click(Sender: TObject);
begin
  WriteCxGrid(Self.Caption + 'TV1', Tv1, '财务管理');
end;

procedure TfrmInvoiceOutSel.ToolButton4Click(Sender: TObject);
var
  excelApp, WorkBook: Variant;
  i, j, k, LX, ExcelRowCount: integer;
  maxId, FCPID, FCPName, t1, t2, t3, FFID: string;
begin

  try
    excelApp := CreateOleObject('Excel.Application');
    openDialog1.Filter := '*.CSV;*.xls';
    if opendialog1.Execute then
    begin
      WorkBook := excelApp.WorkBooks.Open(OpenDialog1.FileName);
    end
    else
      exit;
    excelApp.Visible := false;
    ExcelRowCount := WorkBook.WorkSheets[1].UsedRange.Rows.Count;
  except
    application.MessageBox('加载EXCEL错误！', '错误信息', MB_ICONERROR);
    exit;
  end;

  CDS_LM.EmptyDataSet;

  for j := 0 to Tv1.ColumnCount - 1 do
  begin
    with CDS_LM do
    begin
      Append;
      FieldByName('LCode').Value := trim(Tv1.Columns[j].DataBinding.FieldName);
      FieldByName('LName').Value := trim(Tv1.Columns[j].Caption);
      Post;
    end;
  end;

  try
    for i := 1 to 50 do
    begin
      if trim(WorkBook.WorkSheets[1].Cells[1, i].value) = '' then
        continue;
      if CDS_LM.Locate('LName', trim(WorkBook.WorkSheets[1].Cells[1, i].value), []) then
      begin
        with CDS_LM do
        begin
          Edit;
          FieldByName('LXH').Value := i;
          Post;
        end;
      end;
    end;
  except
    application.MessageBox('加载数组错误！', '错误信息', MB_ICONERROR);
    exit;
  end;

  try
    for i := 2 to ExcelRowCount do
    begin
      with CDS_Invoice do
      begin
        Append;
        CDS_LM.First;
        while not CDS_LM.Eof do
        begin
          if CDS_LM.FieldByName('LXH').AsInteger > 0 then
            CDS_Invoice.fieldbyname(CDS_LM.FieldByName('LCode').AsString).Value := WorkBook.WorkSheets[1].Cells[i, CDS_LM.FieldByName('LXH').AsInteger].Value;
          CDS_LM.Next;
        end;
//        CDS_Invoice.fieldbyname('OurCoNo').Value := '91330602MA2JTEXX4B';
//        CDS_Invoice.fieldbyname('OurCoName').Value := '圆中圆';
//        CDS_Invoice.FieldByName('Currency').Value := 'CNY';
        Post;
      end;
    end;
    WorkBook.Close;
    excelApp.Quit;
    excelApp := Unassigned;
    WorkBook := Unassigned;
  except
    WorkBook.Close;
    excelApp.Quit;
    excelApp := Unassigned;
    WorkBook := Unassigned;
    exit;
  end;

end;

procedure TfrmInvoiceOutSel.ToolButton5Click(Sender: TObject);
begin
  try
    frmPayableSel := TfrmPayableSel.Create(Application);
    with frmPayableSel do
    begin
      if ShowModal = 1 then
      begin
//        frmPayableSel.CDS_1.first;
        CDS_1.Locate('ssel', True, []);
        with frmPayableSel.CDS_1 do
        begin
          self.CDS_Invoice.Append;

          Self.CDS_Invoice.FieldByName('Supplier').value := frmPayableSel.CDS_1.FieldByName('OppCoName').AsString;
          Self.CDS_Invoice.FieldByName('SupplierNo').value := frmPayableSel.CDS_1.FieldByName('OppCoNo').AsString;
          Self.CDS_Invoice.FieldByName('SupplierShuiNo').value := frmPayableSel.CDS_1.FieldByName('oppShuiNo').AsString;
          Self.CDS_Invoice.FieldByName('OurCoName').value := frmPayableSel.CDS_1.FieldByName('OurCoName').AsString;
          Self.CDS_Invoice.FieldByName('OurCoNo').value := frmPayableSel.CDS_1.FieldByName('OurCoNo').AsString;
          Self.CDS_Invoice.FieldByName('OurShuiNo').value := frmPayableSel.CDS_1.FieldByName('ourShuiNo').AsString;

          Self.CDS_Invoice.FieldByName('Currency').value := frmPayableSel.CDS_1.FieldByName('Currency').AsString;
          if frmPayableSel.CDS_1.FieldByName('NoTaxPrice').AsString <> '' then
          begin
            Self.CDS_Invoice.FieldByName('Price').value := frmPayableSel.CDS_1.FieldByName('NoTaxPrice').AsString;
          end
          else
          begin
            Self.CDS_Invoice.FieldByName('Price').value := 0;
          end;

          Self.CDS_Invoice.FieldByName('Amount').value := frmPayableSel.FNoTaxInclude;
          Self.CDS_Invoice.FieldByName('TaxFee').value := frmPayableSel.FTax;
          Self.CDS_Invoice.FieldByName('TaxAmount').value := frmPayableSel.FTaxInclude;
          self.CDS_Invoice.FieldByName('fromFlow').Value := frmPayableSel.FFFIDs;
          Self.CDS_Invoice.post;
        end;
      end;
    end;
  finally
    frmPayableSel.Free;
  end;
end;

procedure TfrmInvoiceOutSel.ToolButton6Click(Sender: TObject);
begin
  initGrid();
end;

end.

