-- ========================
-- 数据库结构增强脚本（MySQL）
-- ========================

-- 1. 会计期间有效性校验
ALTER TABLE financial_accounting_periods
    ADD COLUMN status ENUM('active', 'closed', 'locked') DEFAULT 'active' COMMENT '期间状态',
ADD COLUMN validation_date DATE COMMENT '最后验证日期';

-- 2. 预算表（支持多版本）
CREATE TABLE financial_budgets (
                                   budget_id INT AUTO_INCREMENT PRIMARY KEY COMMENT '预算ID',
                                   company_id INT NOT NULL COMMENT '公司ID',
                                   period_id INT NOT NULL COMMENT '会计期间ID',
                                   account_id INT NOT NULL COMMENT '科目ID',
                                   budget_version INT DEFAULT 1 COMMENT '版本号',
                                   planned_amount DECIMAL(18,2) COMMENT '计划金额',
                                   approved_date DATE COMMENT '审批日期',
                                   FOREIGN KEY (company_id) REFERENCES financial_companies(company_id),
                                   FOREIGN KEY (period_id) REFERENCES financial_accounting_periods(period_id),
                                   FOREIGN KEY (account_id) REFERENCES financial_chart_of_accounts(account_id)
) COMMENT='财务预算表';

-- 3. 科目层级管理增强
ALTER TABLE financial_chart_of_accounts
    ADD COLUMN path VARCHAR(255) COMMENT '层级路径（如0/1001/）',
ADD COLUMN level INT COMMENT '层级深度';

-- 4. 数据血缘追踪表
CREATE TABLE financial_data_trace (
                                      trace_id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '追踪记录ID',
                                      source_table VARCHAR(50) NOT NULL COMMENT '源表名',
                                      source_id BIGINT NOT NULL COMMENT '源记录ID',
                                      target_table VARCHAR(50) NOT NULL COMMENT '目标表名',
                                      target_id BIGINT NOT NULL COMMENT '目标记录ID',
                                      operation_type ENUM('insert','update','delete') NOT NULL COMMENT '操作类型',
                                      operator VARCHAR(50) COMMENT '操作人',
                                      operation_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间'
) COMMENT='数据操作追踪表';

-- 5. 会计期间重叠检查触发器
DELIMITER //
CREATE TRIGGER trg_check_period_overlap
    BEFORE INSERT ON financial_accounting_periods
    FOR EACH ROW
BEGIN
    IF EXISTS (
        SELECT 1 FROM financial_accounting_periods
        WHERE company_id = NEW.company_id
          AND period_id != NEW.period_id
          AND (
              (NEW.start_date BETWEEN start_date AND end_date)
              OR (NEW.end_date BETWEEN start_date AND end_date)
              OR (start_date BETWEEN NEW.start_date AND NEW.end_date)
          )
    ) THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = '会计期间时间重叠';
END IF;
END//
DELIMITER ;

-- 6. 初始化会计期间状态
UPDATE financial_accounting_periods
SET status = CASE
                 WHEN end_date >= CURDATE() THEN 'active'
                 WHEN end_date < CURDATE() AND start_date > CURDATE() THEN 'locked'
                 ELSE 'closed'
    END;

-- 7. 创建科目层级维护存储过程
DELIMITER //
CREATE PROCEDURE sp_refresh_account_hierarchy()
BEGIN
UPDATE financial_chart_of_accounts c
    LEFT JOIN (
    SELECT
    a.account_id,
    CONCAT(
    IFNULL((SELECT CONCAT(path, parent_id, '/') FROM financial_chart_of_accounts
    WHERE account_id = a.parent_id), '0/'),
    a.account_id, '/'
    ) AS new_path,
    (LENGTH(IFNULL((SELECT path FROM financial_chart_of_accounts
    WHERE account_id = a.parent_id), '0/')) - LENGTH(REPLACE(IFNULL(
    (SELECT path FROM financial_chart_of_accounts
    WHERE account_id = a.parent_id), '0/'), '/', ''))) + 1
    AS new_level
    FROM financial_chart_of_accounts a
    ) AS sub ON c.account_id = sub.account_id
    SET
        c.path = sub.new_path,
        c.level = sub.new_level
WHERE c.is_active = TRUE;
END//
DELIMITER ;