unit U_MachTaskList;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics,
  cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinWXI,
  cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator,
  dxDateRanges, dxScrollbarAnnotations, Data.DB, cxDBData, cxGridLevel,
  cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses,
  cxGridCustomView, cxGrid, Vcl.ComCtrls, Vcl.ToolWin, Data.Win.ADODB,
  Vcl.ExtCtrls, cxContainer, cxTextEdit, Vcl.StdCtrls, cxMaskEdit, cxButtonEdit,
  Vcl.Menus, cxButtons, dxSkinsDefaultPainters, Datasnap.DBClient, cxTimeEdit,
  cxCalendar, dxBarBuiltInMenu, cxGridCustomPopupMenu, cxGridPopupMenu;

type
  TfrmMachTaskList = class(TForm)
    cxGrid1: TcxGrid;
    Tv1: TcxGridDBTableView;
    Tv1pcid: TcxGridDBColumn;
    Tv1MCNO: TcxGridDBColumn;
    Tv1OrderNo: TcxGridDBColumn;
    Tv1C_name: TcxGridDBColumn;
    Tv1c_color: TcxGridDBColumn;
    Tv1taskDate: TcxGridDBColumn;
    Tv1taskRollNum: TcxGridDBColumn;
    Tv1taskQty: TcxGridDBColumn;
    cxGrid1Level1: TcxGridLevel;
    ToolBar3: TToolBar;
    Trefresh: TToolButton;
    Tconfirm: TToolButton;
    Tclose: TToolButton;
    DS_1: TDataSource;
    ADOQueryList: TADOQuery;
    Panel1: TPanel;
    Label1: TLabel;
    pcid: TcxTextEdit;
    Label2: TLabel;
    C_Name: TcxTextEdit;
    ADOQueryTmp: TADOQuery;
    ADOQueryCmd: TADOQuery;
    ADOQueryCard: TADOQuery;
    ADOQueryMach: TADOQuery;
    TBDel: TToolButton;
    Tv1BegTime: TcxGridDBColumn;
    ToolButton1: TToolButton;
    ToolButton2: TToolButton;
    CDS_1: TClientDataSet;
    TbSave: TToolButton;
    Tv1MCName: TcxGridDBColumn;
    Tv2: TcxGridDBTableView;
    cxGrid2Level1: TcxGridLevel;
    cxGrid2: TcxGrid;
    Tv2OrderNo: TcxGridDBColumn;
    Tv2PCID: TcxGridDBColumn;
    Tv2GlideName: TcxGridDBColumn;
    Tv2C_Name: TcxGridDBColumn;
    CDS_2: TClientDataSet;
    DS_2: TDataSource;
    TbEditSave: TToolButton;
    Tv1GlideID: TcxGridDBColumn;
    Splitter1: TSplitter;
    Tv1GlideNo: TcxGridDBColumn;
    Tv2GlideNo: TcxGridDBColumn;
    Tv2PSType: TcxGridDBColumn;
    Tv1PSType: TcxGridDBColumn;
    Tv1PSID: TcxGridDBColumn;
    Tv2All_zhuji: TcxGridDBColumn;
    Tv2ALL_temperature6: TcxGridDBColumn;
    cxGridPopupMenu1: TcxGridPopupMenu;
    cxGridPopupMenu2: TcxGridPopupMenu;
    Tv2GlideID: TcxGridDBColumn;
    Tv2PC_FLAG: TcxGridDBColumn;
    Panel2: TPanel;
    Panel3: TPanel;
    Panel4: TPanel;
    Panel5: TPanel;
    Tv2isComplete: TcxGridDBColumn;
    Tv2All_rate: TcxGridDBColumn;
    ToolButton3: TToolButton;
    ToolButton4: TToolButton;
    procedure TcloseClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure TconfirmClick(Sender: TObject);
    procedure TrefreshClick(Sender: TObject);
    procedure pcidKeyPress(Sender: TObject; var Key: Char);
    procedure TBDelClick(Sender: TObject);

    procedure ToolButton1Click(Sender: TObject);
    procedure ToolButton2Click(Sender: TObject);
    procedure tv1CarNoPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure TbSaveClick(Sender: TObject);
    procedure Tv2CellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
    procedure TbEditSaveClick(Sender: TObject);
    procedure tv1BegTimePropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
    procedure Tv2GlideNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure Tv1c_colorPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure Tv2CustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
    procedure ToolButton3Click(Sender: TObject);
    procedure ToolButton4Click(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);

  private
    procedure initGrid();
    procedure initSubGrid();
    function SaveData(): boolean;
    function GetLastLine(const AText: string): string;
    function CheckDate: Boolean;

  public
    fcurMachId: string;
    fBegTime, fMCNO, fMCName, fText: string;
  end;

var
  frmMachTaskList: TfrmMachTaskList;

implementation

uses
  U_dataLink, U_rtFun, U_globalVar, U_BS_MachineSel, U_DyeProcessDefin;
{$R *.dfm}

procedure TfrmMachTaskList.FormCreate(Sender: TObject);
begin
  cxgrid1.Align := alClient;
end;

procedure TfrmMachTaskList.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_ESCAPE then  // VK_ESCAPE 是 ESC 键的常量
  begin
    Key := 0;  // 清除按键，防止继续传递
    Close;     // 或者 ModalResult := mrCancel;
  end;
end;

procedure TfrmMachTaskList.TBDelClick(Sender: TObject);
begin
  if MessageDlg('确定删除？此操作无法撤销！', mtWarning, [mbOK, mbCancel], 0) = mrOK then
  begin
  // 开始事务
    ADOQueryCmd.Connection.BeginTrans;

    try
    // 第一个更新操作
      with ADOQueryCmd do
      begin
        Close;
        SQL.Clear;
        SQL.Add('UPDATE PCAboutTime SET ');
        SQL.Add(fMCName + ' = null WHERE ');
        SQL.Add(fMCName + ' = ' + QuotedStr(Trim(fText)));
//        showMessage(sql.Text);
        ExecSQL;
      end;

    // 第二个更新操作
      with ADOQueryCmd do
      begin
        Close;
        SQL.Clear;
        SQL.Add(' update Dye_Plan_Glide set PC_FLAG = 0,endTime = null,begTime = null where GlideID = ' + QuotedStr(Trim(CDS_1.FieldByName('GlideID').asString)));
        ExecSQL;
      end;

    // 两个操作都成功，提交事务
      ADOQueryCmd.Connection.CommitTrans;

      Application.MessageBox('保存成功！', '提示', 0);
      Close;

    except
      on E: Exception do
      begin
      // 发生异常，回滚事务
        ADOQueryCmd.Connection.RollbackTrans;
        ShowMessage('操作失败：' + E.Message);
      end;
    end;
  end;
end;
//begin
//  try
//    with ADOQueryCmd do
//    begin
//      close;
//      sql.Clear;
//      sql.Add('exec p_delete_machTask');
//      sql.Add('@ids=' + quotedstr(Trim(ADOQueryList.FieldByName('taskid').AsString)));
//      sql.Add(',@user=' + quotedstr(gUserId));
//      ExecSql;
//    end;
//  except
//    application.MessageBox('删除记录失败!', '提示信息', 0);
//  end;
//  initSubGrid();
//end;

procedure TfrmMachTaskList.TcloseClick(Sender: TObject);
begin
  close;
end;

procedure TfrmMachTaskList.TconfirmClick(Sender: TObject);
begin
  WriteCxGrid(trim(self.Caption) + 'Tv1', Tv1, '机台扫描排缸');
  WriteCxGrid(trim(self.Caption) + 'Tv2', Tv2, '机台扫描排缸');
end;

procedure TfrmMachTaskList.ToolButton1Click(Sender: TObject);
var
  FTaskID: string;
begin
  if ADOQueryList.IsEmpty then
    Exit;

  FTaskID := ADOQueryList.FieldByName('taskid').AsString;

  try
    with ADOQueryCmd do
    begin
      close;
      SQL.Clear;
      sql.Add('exec P_UpDown_MD_Machine_Task ');
      sql.Add('@ids=' + quotedstr(Trim(ADOQueryList.FieldByName('taskid').AsString)));
      sql.Add(',@flag=0 ');
      ExecSQL;
    end;
  except
    application.MessageBox('操作失败!', '提示信息', 0);
  end;
  initSubGrid();

  ADOQueryList.Locate('taskid', FTaskID, []);
end;

procedure TfrmMachTaskList.ToolButton2Click(Sender: TObject);
var
  FTaskID: string;
begin
  if ADOQueryList.IsEmpty then
    Exit;

  FTaskID := ADOQueryList.FieldByName('taskid').AsString;

  try
    with ADOQueryCmd do
    begin
      close;
      SQL.Clear;
      sql.Add('exec P_UpDown_MD_Machine_Task ');
      sql.Add('@ids=' + quotedstr(Trim(ADOQueryList.FieldByName('taskid').AsString)));
      sql.Add(',@flag=1 ');
      ExecSQL;
    end;
  except
    application.MessageBox('操作失败!', '提示信息', 0);
  end;
  initSubGrid();

  ADOQueryList.Locate('taskid', FTaskID, []);
end;

procedure TfrmMachTaskList.ToolButton3Click(Sender: TObject);
begin
  ShowMessage(CDS_1.FieldByName('BegTime').AsString);
end;

procedure TfrmMachTaskList.ToolButton4Click(Sender: TObject);
begin
  ShowMessage(CDS_1.FieldByName('MCName').asString);
end;

procedure TfrmMachTaskList.TbEditSaveClick(Sender: TObject);
begin
  C_Name.SetFocus;
  if not CheckDate then
    Exit;

  if MessageDlg('确定修改？此操作无法撤销！', mtWarning, [mbOK, mbCancel], 0) = mrOK then
  begin
    ADOQueryCmd.Connection.BeginTrans;
    try
      with ADOQueryCmd do
      begin
        Close;
        SQL.Clear;
        SQL.Add('UPDATE PCAboutTime SET ');
        SQL.Add(fMCName + ' = null WHERE ');
        SQL.Add(fMCName + ' = ' + QuotedStr(Trim(fText)));
        ExecSQL;
      end;

    // 如果还有其他数据库操作，可以继续在这里添加...

    // 所有操作成功后才提交事务
      ADOQueryCmd.Connection.CommitTrans;

    except
      on E: Exception do
      begin
        ADOQueryCmd.Connection.RollbackTrans;
        ShowMessage('更新失败：' + E.Message);
        Exit; // 重要：发生异常后退出过程
      end;
    end;

    if SaveData() then
    begin
      Application.MessageBox('保存成功！', '提示', 0);
    end;
    close;
  end;

end;

function TfrmMachTaskList.CheckDate: Boolean;
var
  Hour, Min, Sec, MSec: Word;
begin
  Result := False;

  ////////////////检查目标位置是否有覆盖
  if (CDS_1.FieldByName('BegTime').AsString <> fBegTime) or (CDS_1.FieldByName('MCName').AsString <> fMCName) then
  begin
    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      SQL.Add(' select ' + CDS_1.FieldByName('MCName').AsString + ' from PCAboutTime where Time = ' + QuotedStr(Trim(CDS_1.FieldByName('BegTime').AsString)));

//    ShowMessage(sql.Text);
      open;
      if (ADOQueryCmd.FieldByName(CDS_1.FieldByName('MCName').AsString).asString <> fText) and (ADOQueryCmd.FieldByName(CDS_1.FieldByName('MCName').AsString).asString <> null) and (ADOQueryCmd.FieldByName(CDS_1.FieldByName('MCName').AsString).asString <> '') then
      begin
        Application.MessageBox('目标时间段已有工序！', '提示信息', MB_OK);
        Exit;
      end;
    end;
  end;

  var i: Integer;
  if (fText = '') or (fText = null) then
  begin

  end;
  if CDS_1.FieldByName('time').Value = 0 then
  begin
    Application.MessageBox('任务时间不能为0', '提示信息', MB_OK);
    Exit;
  end;
//    ShowMessage(CDS_1.FieldByName('Begtime').AsString);
  DecodeTime(VarToDateTime(CDS_1.FieldByName('Begtime').Value), Hour, Min, Sec, MSec);

  if Sec <> 0 then
  begin
    Application.MessageBox('开始时间秒数必须为 0', '提示信息', MB_OK);
    Exit;
  end
  else if (Min mod 10) <> 0 then  // 添加分钟验证
  begin
    Application.MessageBox('开始时间分钟必须为 10 的倍数！', '提示信息', MB_OK);
    Exit;
  end;

//////////////排产顺序时间////////
  with ADOQueryCmd do
  begin
    Close;
    sql.Clear;
    SQL.Add(' select * from Dye_Plan_Glide where PCID = ' + QuotedStr(Trim(CDS_1.FieldByName('PCID').AsString)));
    SQL.Add(' and PC_FLAG = 1 and endTime >  ' + quotedStr(Trim(CDS_1.FieldByName('Begtime').AsString)));
    SQL.Add(' and GlideNo < ' + QuotedStr(Trim(CDS_1.FieldByName('GlideNo').AsString)));
//      ShowMessage(sql.Text);
    open;
    if not IsEmpty then
    begin
      if Application.MessageBox('工序时间段冲突！是否继续？', '提示信息', MB_OKCANCEL + MB_ICONQUESTION) = IDOK then
      begin

      end
      else
      begin
        Exit;
      end;
    end;
  end;

  with ADOQueryCmd do
  begin
    Close;
    sql.Clear;
    SQL.Add(' select * from Dye_Plan_Glide where PCID = ' + QuotedStr(Trim(CDS_1.FieldByName('PCID').AsString)));
    SQL.Add(' and PC_FLAG = 1 and BegTime <  DATEADD(MINUTE, ' + CDS_1.FieldByName('time').AsString + ', ' + QuotedStr(trim(CDS_1.FieldByName('BegTime').AsString)) + ')');
    SQL.Add(' and GlideNo > ' + QuotedStr(Trim(CDS_1.FieldByName('GlideNo').AsString)));
//    ShowMessage(sql.Text);
    open;
    if not IsEmpty then
    begin
      if Application.MessageBox('工序时间段冲突！是否继续？', '提示信息', MB_OKCANCEL + MB_ICONQUESTION) = IDOK then
      begin

      end
      else
      begin
        Exit;
      end;
    end;
  end;
  Result := True;
end;

procedure TfrmMachTaskList.TbSaveClick(Sender: TObject);
begin
//    if CDS_1.Locate('PSName', '', []) or CDS_1.Locate('PSName', null, []) then
//    begin
//      Application.MessageBox('请完善工序名称！', '提示信息', MB_OK);
//      Exit;
//    end;

  if not CheckDate then
    Exit;
  if SaveData() then
  begin
    Application.MessageBox('保存成功！', '提示', 0);
  end;
  close;
end;

function TfrmMachTaskList.SaveData(): boolean;
var
  mLoopNum: Integer;
  mMCName, mNewValue, mStartTime: string;
  mEndTime, mBegTime: string;
begin
  result := false;
  ADOQueryCmd.Connection.BeginTrans;
  try

    mLoopNum := StrToInt(CDS_1.FieldByName('Time').AsString) div 10;

    with CDS_1 do
    begin
      First;
      while not Eof do
      begin
        if (CDS_1.FieldByName('MCNO').AsString <> '') and (CDS_1.FieldByName('BegTime').AsString <> '') then
        begin
          with ADOQueryCmd do
          begin
            Close;
            SQL.Clear;
            SQL.Add(' update Dye_Plan_Glide set PC_FLAG = 1 , EndTime = DATEADD(MINUTE, ' + CDS_1.FieldByName('time').AsString + ', ' + QuotedStr(trim(CDS_1.FieldByName('BegTime').AsString)) + ')');
            SQL.Add(' , begTime = ' + QuotedStr(Trim(CDS_1.FieldByName('BegTime').AsString)));
            SQL.Add(' , MCNO = ' + QuotedStr(Trim(CDS_1.FieldByName('MCNO').AsString)));
            SQL.Add(' , MCName = ' + QuotedStr(Trim(CDS_1.FieldByName('MCName').AsString)));
            SQL.Add('  where GlideID = ' + QuotedStr(Trim(CDS_1.FieldByName('GlideID').asString)));
//            ShowMessage(sql.Text);
            ExecSQL;
          end;
          mMCName := CDS_1.FieldByName('MCName').AsString;
          mStartTime := CDS_1.FieldByName('BegTime').AsString;
//          mNewValue := '计划单:' + CDS_1.FieldByName('OrderNo').AsString + #13;
          mNewValue := mNewValue + CDS_1.FieldByName('C_Name').AsString + #13;
          mNewValue := mNewValue + '成品门幅：' + CDS_1.FieldByName('C_Width').AsString + #13;
          mNewValue := mNewValue + '工序 刮胶次数:' + CDS_1.FieldByName('GlideName').AsString;

          if CDS_1.FieldByName('PSType').AsString = '长车清洗' then
          begin
            mNewValue := mNewValue + '' + #13;
            mNewValue := mNewValue + '车速:' + CDS_1.FieldByName('ccqx_speed').AsString + #13;
            mNewValue := mNewValue + '温度6#:' + CDS_1.FieldByName('ccqx_temperature6').AsString + #13;

          end
          else if CDS_1.FieldByName('PSType').AsString = '干定型' then
          begin
            mNewValue := mNewValue + '' + #13;
            mNewValue := mNewValue + '车速:' + CDS_1.FieldByName('dx_speed').AsString + #13;
            mNewValue := mNewValue + '温度6#:' + CDS_1.FieldByName('dx_temperature6').AsString + #13;
          end
          else if CDS_1.FieldByName('PSType').AsString = '下水定型' then
          begin
            mNewValue := mNewValue + '' + #13;
            mNewValue := mNewValue + '车速:' + CDS_1.FieldByName('fs_speed').AsString + #13;
            mNewValue := mNewValue + '温度6#:' + CDS_1.FieldByName('fs_temperature6').AsString + #13;

          end
          else if CDS_1.FieldByName('PSType').AsString = '刮胶' then
          begin
            mNewValue := mNewValue + '' + CDS_1.FieldByName('gj_number').AsString + #13;
            mNewValue := mNewValue + '车速:' + CDS_1.FieldByName('gj_speed').AsString + #13;
            mNewValue := mNewValue + '温度6#:' + CDS_1.FieldByName('gj_temperature6').AsString + #13;
          end
          else if CDS_1.FieldByName('PSType').AsString = '发泡' then
          begin
            mNewValue := mNewValue + ' ' + CDS_1.FieldByName('fp_gjNumber').AsString + #13;
            mNewValue := mNewValue + '车速:' + CDS_1.FieldByName('fp_speed').AsString + #13;
            mNewValue := mNewValue + '温度6#:' + CDS_1.FieldByName('fp_temperature6').AsString + #13;
          end
          else
          begin
            mNewValue := mNewValue + '' + #13;
          end;
      //////////////////////显示助剂
          mNewValue := mNewValue + '助剂:' + CDS_1.FieldByName('All_zhuji').AsString + ' ' + CDS_1.FieldByName('All_rate').AsString + #13;

          mNewValue := mNewValue + CDS_1.FieldByName('PCID').AsString + #13;
          mNewValue := mNewValue + CDS_1.FieldByName('GlideID').AsString;

          with ADOQueryCmd do
          begin
            Close;
            SQL.Clear;
            SQL.Add('EXEC P_PC_UpdatePCAboutTime ' + '@MCName = :MCName, ' + '@NewValue = :NewValue, ' + '@StartTime = :StartTime, ' + '@LoopNum = :LoopNum');

            Parameters.ParamByName('MCName').Value := mMCName;
            Parameters.ParamByName('NewValue').Value := mNewValue;
            Parameters.ParamByName('StartTime').Value := mStartTime;
            Parameters.ParamByName('LoopNum').Value := mLoopNum;
            ExecSQL;
          end;

          with ADOQueryCmd do
          begin
            Close;
            SQL.Clear;
            SQL.Add('select * from PCAboutTime ');
            SQL.Add(' where time >= ' + quotedStr(Trim(mStartTime)));

            Open;
          end;
          ADOQueryCmd.First;
          mNewValue := ADOQueryCmd.FieldByName(mMCName).AsString;
          mBegTime := ADOQueryCmd.FieldByName('time').AsString;
          mEndTime := ADOQueryCmd.FieldByName('time').AsString;
          while not ADOQueryCmd.Eof do
          begin
            if (ADOQueryCmd.FieldByName(mMCName).AsString = null) or (ADOQueryCmd.FieldByName(mMCName).AsString = '') then
            begin
              mEndTime := ADOQueryCmd.FieldByName('time').AsString;
              with ADOQueryTmp do
              begin
                Close;
                sql.Clear;
                sql.Add('update Dye_Plan_Glide set BegTime = ' + QuotedStr(Trim(mBegTime)));
                sql.Add(' , EndTime = ' + QuotedStr(Trim(mEndTime)));
                SQL.Add(' where GlideID = ' + QuotedStr(Trim(GetLastLine(mNewValue))));
                ExecSQL;
              end;
              ADOQueryCmd.Connection.CommitTrans;
              result := true;
              Exit;
            end;

            if mNewValue <> ADOQueryCmd.FieldByName(mMCName).AsString then
            begin
              mEndTime := ADOQueryCmd.FieldByName('time').AsString;
              with ADOQueryTmp do
              begin
                Close;
                sql.Clear;
                sql.Add('update Dye_Plan_Glide set BegTime = ' + QuotedStr(Trim(mBegTime)));
                sql.Add(' , EndTime = ' + QuotedStr(Trim(mEndTime)));
                SQL.Add(' where GlideID = ' + QuotedStr(Trim(GetLastLine(mNewValue))));
                ExecSQL;
              end;
              mBegTime := ADOQueryCmd.FieldByName('time').AsString;
              mNewValue := ADOQueryCmd.FieldByName(mMCName).AsString;
            end;

            ADOQueryCmd.Next;
          end;

        end;
        Next;
      end;
    end;

    ADOQueryCmd.Connection.CommitTrans;
    result := true;
  except
    ADOQueryCmd.Connection.RollbackTrans;
    application.MessageBox(PChar(Exception(ExceptObject).Message), '提示信息', 0);
    result := false;
  end;
end;

procedure TfrmMachTaskList.TrefreshClick(Sender: TObject);
begin
  initSubGrid();
end;

procedure TfrmMachTaskList.tv1BegTimePropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
var
  Begtime: TDateTime;
  Hour, Min, Sec, MSec: Word;
begin
  try
    // 使用 DisplayValue 而不是 Sender.AsString
    if VarIsNull(DisplayValue) or (DisplayValue = '') then
      Exit;

    Begtime := VarToDateTime(DisplayValue);
    DecodeTime(Begtime, Hour, Min, Sec, MSec);

    if Sec <> 0 then
    begin
      ErrorText := '开始时间秒数必须为 0！';
      Error := True;  // 设置错误标志
    end
    else if (Min mod 10) <> 0 then  // 添加分钟验证
    begin
      ErrorText := '开始时间分钟必须为 10 的倍数！当前分钟为：' + IntToStr(Min);
      Error := True;
    end
    else
    begin
      Error := False; // 清除错误标志
    end;

  except
    on E: Exception do
    begin
      ErrorText := '时间格式错误：' + E.Message;
      Error := True;
    end;
  end;
end;

procedure TfrmMachTaskList.tv1CarNoPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmBS_MachineSel := TfrmBS_MachineSel.Create(Application);
    with frmBS_MachineSel do
    begin

      if ShowModal = 1 then
      begin
        Self.CDS_1.Edit;
        Self.CDS_1.FieldByName('MCNO').Value := frmBS_MachineSel.Order_Main.FieldByName('MCNO').Value;
        Self.CDS_1.FieldByName('MCName').Value := frmBS_MachineSel.Order_Main.FieldByName('MCName').Value;
        Self.CDS_1.Post;
//        ShowMessage(CDS_1.FieldByName('BegTime').AsString);
        Self.initSubGrid();
      end;
    end;
  finally
    frmBS_MachineSel.Free;
  end;
end;

procedure TfrmMachTaskList.Tv1c_colorPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmDyeProcessDefin := TfrmDyeProcessDefin.Create(Application);
    with frmDyeProcessDefin do
    begin
      FPSID := self.CDS_1.FieldByName('PSID').AsString;
      FPSType := self.CDS_1.FieldByName('PSType').AsString;
      BtnInt := 3;
      if ShowModal = 1 then
      begin

      end;
    end;

  finally
    frmDyeProcessDefin.Free;
  end;
end;

procedure TfrmMachTaskList.Tv2CellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
var
  glideIds: string;
begin
  try
    ADOQueryCmd.Connection.BeginTrans;
    with ADOQueryCard do
    begin
      close;
      sql.clear;
      sql.Add(' select * from V_Dye_Cloth_PaiGang where GlideID = ' + quotedStr(Trim(CDS_2.FieldByName('GlideID').AsString)));
      open;
    end;
    with CDS_1 do
    begin
      if CDS_1.RecordCount = 0 then
      begin
        append;
      end
      else
      begin
        Edit;
      end;

      FieldByName('GlideID').value := ADOQueryCard.FieldByName('GlideID').AsString;
      FieldByName('GlideNo').value := ADOQueryCard.FieldByName('GlideNo').AsString;
      FieldByName('OrderNo').value := ADOQueryCard.FieldByName('OrderNo').AsString;
      FieldByName('pcid').value := ADOQueryCard.FieldByName('pcid').AsString;
      FieldByName('C_name').value := ADOQueryCard.FieldByName('C_name').AsString;
      FieldByName('C_Width').value := ADOQueryCard.FieldByName('C_Width').AsString;
      FieldByName('GlideName').value := ADOQueryCard.FieldByName('GlideName').AsString;
      FieldByName('PCPiece').asString := ADOQueryCard.FieldByName('PCPiece').AsString;
      FieldByName('PCQty').asString := ADOQueryCard.FieldByName('PCQty').AsString;
      FieldByName('time').value := ADOQueryCard.FieldByName('time').AsString;
      FieldByName('PSType').value := ADOQueryCard.FieldByName('PSType').AsString;
      FieldByName('PSID').value := ADOQueryCard.FieldByName('PSID').AsString;

      FieldByName('ccqx_speed').value := ADOQueryCard.FieldByName('ccqx_speed').AsString;
      FieldByName('ccqx_temperature6').value := ADOQueryCard.FieldByName('ccqx_temperature6').AsString;
      FieldByName('dx_speed').value := ADOQueryCard.FieldByName('dx_speed').AsString;
      FieldByName('dx_temperature6').value := ADOQueryCard.FieldByName('dx_temperature6').AsString;
      FieldByName('fs_speed').value := ADOQueryCard.FieldByName('fs_speed').AsString;
      FieldByName('fs_temperature6').value := ADOQueryCard.FieldByName('fs_temperature6').AsString;
      FieldByName('gj_speed').value := ADOQueryCard.FieldByName('gj_speed').AsString;
      FieldByName('gj_temperature6').value := ADOQueryCard.FieldByName('gj_temperature6').AsString;
      FieldByName('fp_speed').value := ADOQueryCard.FieldByName('fp_speed').AsString;
      FieldByName('fp_temperature6').value := ADOQueryCard.FieldByName('fp_temperature6').AsString;
      FieldByName('All_zhuji').value := ADOQueryCard.FieldByName('All_zhuji').AsString;

      FieldByName('MCNO').value := fMCNO;
      FieldByName('BegTime').value := fBegTime;
      FieldByName('MCName').value := fMCName;
      Post;
    end;
    if ADOQueryCard.RecordCount = 0 then
    begin
      raise Exception.Create('未找到流程卡或流程卡未安排工序！');
    end;

    ADOQueryCmd.Connection.CommitTrans;
  except
    if ADOQueryCmd.Connection.InTransaction then
      ADOQueryCmd.Connection.RollbackTrans;
    application.MessageBox(PChar(Exception(ExceptObject).Message), '提示信息', 0);
//      showMessage('插入任务数据时发生错误!');
  end;
//  initSubGrid();
end;

procedure TfrmMachTaskList.Tv2CustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
var
  PC_FLAG, isComplete: Variant;
begin
  // 获取字段值
  PC_FLAG := AViewInfo.GridRecord.Values[TcxGridDBTableView(Sender).GetColumnByFieldName('PC_FLAG').Index];
  isComplete := AViewInfo.GridRecord.Values[TcxGridDBTableView(Sender).GetColumnByFieldName('isComplete').Index];

  // 设置不同状态的颜色和字体
  if VarIsNull(PC_FLAG) or (PC_FLAG = 0) then               // 未排入计划单
  begin
    ACanvas.Brush.Color := $00CCCCFF;  // 浅红色背景
    ACanvas.Font.Color := clRed;
    ACanvas.Font.Style := [fsBold];
  end
  else if (PC_FLAG = 1) and VarIsNull(isComplete) then      // 排入未报工
  begin
    ACanvas.Brush.Color := clWindow;     // 默认窗口背景色
    ACanvas.Font.Color := clWindowText;  // 默认窗口文本色
    ACanvas.Font.Style := [];
  end
  else if (PC_FLAG = 1) and (not VarIsNull(isComplete)) and (isComplete = 0) then // 生产一部分
  begin
    ACanvas.Brush.Color := $00E0E0E0;    // 浅灰色背景
    ACanvas.Font.Color := clGray;
    ACanvas.Font.Style := [fsBold];      //
  end
  else if (PC_FLAG = 1) and (not VarIsNull(isComplete)) and (isComplete = 1) then // 成品入库
  begin
    ACanvas.Brush.Color := $00E0FFE0;    // 浅绿色背景
    ACanvas.Font.Color := $00008000;
    ACanvas.Font.Style := [fsBold];
  end
  else  // 默认情况
  begin
    ACanvas.Brush.Color := clWindow;
    ACanvas.Font.Color := clWindowText;
    ACanvas.Font.Style := [];
  end;

  // 如果需要自定义绘制完成，取消下面的注释
  // ADone := True;
end;

procedure TfrmMachTaskList.Tv2GlideNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmDyeProcessDefin := TfrmDyeProcessDefin.Create(Application);
    with frmDyeProcessDefin do
    begin
      FPSID := self.CDS_2.FieldByName('PSID').AsString;
      FPSType := self.CDS_2.FieldByName('PSType').AsString;
      BtnInt := 3;
      if ShowModal = 1 then
      begin

      end;
    end;

  finally
    frmDyeProcessDefin.Free;
  end;
end;

////////////////////////////////////////////
///

function TfrmMachTaskList.GetLastLine(const AText: string): string;
var
  StringList: TStringList;
begin
  Result := '';
  StringList := TStringList.Create;
  try
    StringList.Text := AText; // 自动按回车分割
    if StringList.Count > 0 then
      Result := StringList[StringList.Count - 1]; // 获取最后一行
  finally
    StringList.Free;
  end;
end;

procedure TfrmMachTaskList.FormShow(Sender: TObject);
begin
  ReadCxGrid(trim(self.Caption) + 'Tv1', Tv1, '机台扫描排缸');
  ReadCxGrid(trim(self.Caption) + 'Tv2', Tv2, '机台扫描排缸');
  initSubGrid();
  initGrid();
//  ShowMessage(GetLastLine(fText));
  if CDS_1.RecordCount > 0 then
  begin
    TbSave.Visible := False;
    cxGrid2.Visible := False;
  end
  else
  begin
    TbEditSave.Visible := false;
    TbDel.Visible := False;
  end;

  KeyPreview := True;  // 确保表单可以预览按键
end;

procedure TfrmMachTaskList.initGrid();
begin
  try
    ADOQueryList.DisableControls;
    with ADOQueryTmp do
    begin
      Close;
      SQL.Clear;
      SQL.Add(' select * from BS_Machine where MCName = ' + QuotedStr(fMCName));
      open;
    end;
    fMCNO := ADOQueryTmp.FieldByName('MCNO').AsString;

    with ADOQueryList do
    begin
      close;
      sql.Clear;
      sql.Add('select * from V_Dye_Cloth_PaiGang where 1 = 2');
//      sql.Add('where not exists (');
//      sql.Add('    select 1 from PCAboutTime ');
//      sql.Add('    where PCAboutTime.GlideID = V_Dye_Cloth_PaiGang.GlideID');
//      sql.Add(')');
//      ShowMessage(SQL.Text);
//      a.taskDate,
      open;
    end;
    SCreateCDS(ADOQueryList, CDS_1);
    SInitCDSData(ADOQueryList, CDS_1);

    if (fText = '') or (fText = null) then
    begin

    end
    else
    begin
      TbEditSave.Visible := True;
      with ADOQueryList do
      begin
        close;
        sql.Clear;
        sql.Add('select * from V_Dye_Cloth_PaiGang where GlideID = ' + QuotedStr(Trim(GetLastLine(fText))));
        open;
      end;
      with CDS_1 do
      begin
        Append;
        FieldByName('GlideID').value := trim(ADOQueryList.FieldByName('GlideID').AsString);
        FieldByName('GlideNo').value := trim(ADOQueryList.FieldByName('GlideNo').AsString);
        FieldByName('OrderNo').value := trim(ADOQueryList.FieldByName('OrderNo').AsString);
        FieldByName('pcid').value := ADOQueryList.FieldByName('pcid').AsString;
        FieldByName('C_name').value := ADOQueryList.FieldByName('C_name').AsString;
        FieldByName('GlideName').value := ADOQueryList.FieldByName('GlideName').AsString;
        FieldByName('PCPiece').value := ADOQueryList.FieldByName('PCPiece').Asfloat;
        FieldByName('PCQty').value := ADOQueryList.FieldByName('PCQty').Asfloat;
        FieldByName('time').value := ADOQueryList.FieldByName('time').AsString;
        FieldByName('PSType').value := ADOQueryList.FieldByName('PSType').AsString;
        FieldByName('PSID').value := ADOQueryList.FieldByName('PSID').AsString;

        FieldByName('MCNO').value := fMCNO;
        FieldByName('BegTime').value := fBegTime;
        FieldByName('MCName').value := fMCName;
        Post;
      end;
    end;

  finally
    ADOQueryList.EnableControls;
//    tv1.ApplyBestFit();
  end;
end;

procedure TfrmMachTaskList.initSubGrid();
begin
  try
    ADOQueryList.DisableControls;
    with ADOQueryList do
    begin
      close;
      sql.Clear;
      SQL.Add(' select A.* from V_Dye_Cloth_PaiGang A where 1=1  ');
      sql.Add(' AND  A.KaZuState = 9 ');
      sql.Add(' and (SELECT COUNT(*) FROM Dye_Plan_Glide_OutPut X WHERE X.PCID = A.PCID AND X.GlideNo = A.GlideNo)<2 ');
//      sql.Add('where isComplete <> 1 OR isComplete IS NULL order by PCID ASC, GlideNo ASC');
//      ShowMessage(SQL.Text);
//      a.taskDate,
      open;
    end;
    SCreateCDS(ADOQueryList, CDS_2);
    SInitCDSData(ADOQueryList, CDS_2);
//    ShowMessage(CDS_2.FieldByName('PSID').AsString);
  finally
    ADOQueryList.EnableControls;
//    tv1.ApplyBestFit();
  end;
end;

procedure TfrmMachTaskList.pcidKeyPress(Sender: TObject; var Key: Char);
var
  glideIds: string;
begin
  if Key = #13 then
  begin
    try
      ADOQueryCmd.Connection.BeginTrans;
      with ADOQueryCard do
      begin
        close;
        sql.clear;
//        sql.add(' select top 1 A.OrderNo,A.workShop,A.PSC_StkPiece,A.PSC_StkQty,B.GlideId,B.GlideNo,B.GlideName ');
//        sql.add(' from Dye_Plan_Card A ');
//        sql.add(' left join Dye_Plan_Glide B on A.pcid=B.pcid ');
//        sql.add(' where A.pcid= ' + QuotedStr(Trim(pcid.Text)));
////        sql.add(' and B.Completeness < 100 ');
//        sql.add(' and not exists(select * from Dye_Plan_Glide_output e where e.glideno=b.glideno and e.pcid=a.pcid)');
//        sql.add(' order by B.GlideNo ');
        sql.Add(' select * from V_Dye_Cloth_PaiGang where PCID = ' + quotedStr(Trim(PCID.Text)));

        open;
      end;
      SCreateCDS(ADOQueryCard, CDS_1);
      SInitCDSData(ADOQueryCard, CDS_1);
      if ADOQueryCard.RecordCount = 0 then
      begin
        raise Exception.Create('未找到流程卡或流程卡未安排工序！');
      end;

//      with ADOQueryMach do
//      begin
//        close;
//        sql.clear;
//        sql.add(' select A.* from Bs_Machine A ');
//        sql.add(' where A.mcid= ' + QuotedStr(Trim(fcurMachId)));
//        open;
//      end;
//
//      if ADOQueryMach.RecordCount = 0 then
//      begin
//        raise Exception.Create('未找到机台！');
//      end;
//
//      with ADOQueryCmd do
//      begin
//        close;
//        sql.clear;
//        sql.add('select * from MD_Machine_Task ');
//        sql.add('where 1=2');
//        open;
//        append;
//
//        fieldByName('mcId').value := Trim(fcurMachId);
//        fieldByName('mcNo').value := Trim(ADOQueryMach.FieldByName('mcno').AsString);
//        fieldByName('taskDate').value := SGetServerDate(ADOQueryTmp);
//        fieldByName('orderNo').value := trim(ADOQueryCard.FieldByName('orderNo').AsString);
//        fieldByName('pcId').value := Trim(pcid.Text);
//        fieldByName('status').value := '0';
//        fieldByName('glideGroup').value := '';
//        fieldByName('machGroupNo').value := '';
//        fieldByName('workShop').value := trim(ADOQueryCard.FieldByName('workShop').AsString);
//        fieldByName('taskRollNum').value := ADOQueryCard.FieldByName('PSC_StkPiece').AsFloat;
//        fieldByName('taskQty').value := ADOQueryCard.FieldByName('PSC_StkQty').AsFloat;
//
//        fieldByName('taskType').value := '手动';
//        fieldByName('curGlideName').value := trim(ADOQueryCard.FieldByName('glideName').AsString);
//        fieldByName('curGlide').value := trim(ADOQueryCard.FieldByName('glideName').AsString);
//        fieldByName('GlideId').value := trim(ADOQueryCard.FieldByName('GlideId').AsString);
//        fieldByName('deleted').value := 0;
//        fieldByName('filler').value := gUserName;
//        post;
//      end;

//      with ADOQueryCmd do
//      begin
//        close;
//        sql.Clear;
//        sql.Add('update MD_Machine_Task set order_idx=isnull((select floor(max(order_idx)) from MD_Machine_Task X where X.mcNo=MD_Machine_Task.mcNo),0)+1');
//        sql.Add('where order_idx is null');
//        ExecSql;
//      end;
//
//      with ADOQueryCmd do
//      begin
//        close;
//        sql.Clear;
//        sql.Add('update dye_plan_glide set pc_flag=1');
//        sql.Add('where glideId =' + quotedstr(trim(ADOQueryCard.FieldByName('GlideId').AsString)));
//        ExecSql;
//      end;

      ADOQueryCmd.Connection.CommitTrans;
    except
      if ADOQueryCmd.Connection.InTransaction then
        ADOQueryCmd.Connection.RollbackTrans;
      application.MessageBox(PChar(Exception(ExceptObject).Message), '提示信息', 0);
//      showMessage('插入任务数据时发生错误!');
    end;
    initSubGrid();
  end;
end;

end.

