;;; ============================================================================
;;; Lệnh       : DA2
;;; Mô tả      : Tạo Dimension Aligned từ 2 điểm p1, p2, đặt tại trung điểm,
;;;              giá trị text mặc định và đổi 2 mũi tên sang kiểu Right Angle.
;;; Tác giả    : AutoLISP thật là đơn giản - autolisp.vn
;;; ============================================================================

(vl-load-com)

(defun c:DA2 (/ *error* doc oldCmd p1 p2 mid lastEnt newEnt dimObj arrowType)
  ;; Hàm xử lý lỗi cục bộ để khôi phục biến hệ thống và đóng Undo Mark
  (defun *error* (msg)
    (if oldCmd (setvar "CMDECHO" oldCmd))
    (if doc (vla-EndUndoMark doc))
    (if (and msg (not (wcmatch (strcase msg) "*BREAK,*CANCEL*,*EXIT*")))
      (princ (strcat "\nLỗi: " msg))
    )
    (princ)
  )

  (setq doc    (vla-get-ActiveDocument (vlax-get-acad-object))
        oldCmd (getvar "CMDECHO")
  )

  ;; Cho người dùng pick 2 điểm p1 và p2
  (setq p1 (getpoint "\nChọn điểm thứ nhất (p1): "))
  (if p1
    (setq p2 (getpoint p1 "\nChọn điểm thứ hai (p2): "))
  )

  (cond
    ((or (null p1) (null p2))
     (princ "\nĐã hủy lệnh DA2.")
    )
    ((equal p1 p2 1e-8)
     (princ "\nHai điểm p1 và p2 trùng nhau, không thể tạo Dimension.")
    )
    (t
     ;; Tính trung điểm giữa p1 và p2 làm điểm đặt dim
     (setq mid (mapcar '(lambda (a b) (/ (+ a b) 2.0)) p1 p2))

     (vla-StartUndoMark doc)
     (setvar "CMDECHO" 0)

     (setq lastEnt (entlast))

     ;; Tạo Dimension Aligned mới dựa trên p1, p2, đặt tại trung điểm (text mặc định)
     (command "_.DIMALIGNED" "_non" p1 "_non" p2 "_non" mid)

     (setq newEnt (entlast))
     (if (and newEnt (not (eq newEnt lastEnt)))
       (progn
         (setq dimObj    (vlax-ename->vla-object newEnt)
               arrowType (if (boundp 'acArrowOpen90) acArrowOpen90 11)
         )
         ;; Đổi 2 mũi tên thành kiểu Right Angle (_OPEN90)
         (vla-put-Arrowhead1Type dimObj arrowType)
         (vla-put-Arrowhead2Type dimObj arrowType)
         (princ "\nĐã tạo Dimension (Right Angle) thành công.")
       )
       (princ "\nKhông thể tạo Dimension mới.")
     )

     (setvar "CMDECHO" oldCmd)
     (vla-EndUndoMark doc)
    )
  )

  (princ)
)

(princ "\nĐã tải lệnh DA2 - AutoLISP thật là đơn giản - autolisp.vn")
(princ)