-- MySQL数据库初始化脚本
-- 适用于智能办公管理系统
-- 版本: 1.0
-- 作者: 数据库迁移团队

-- 创建数据库
CREATE DATABASE IF NOT EXISTS smart_office_auth CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE DATABASE IF NOT EXISTS smart_office_attendance CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE DATABASE IF NOT EXISTS smart_office_approval CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 创建用户并授权（根据实际情况调整）
-- CREATE USER 'smartoffice'@'%' IDENTIFIED BY 'SmartOffice123';
-- GRANT ALL PRIVILEGES ON smart_office_auth.* TO 'smartoffice'@'%';
-- GRANT ALL PRIVILEGES ON smart_office_attendance.* TO 'smartoffice'@'%';
-- GRANT ALL PRIVILEGES ON smart_office_approval.* TO 'smartoffice'@'%';
-- FLUSH PRIVILEGES;

-- 使用认证数据库
USE smart_office_auth;

-- 用户表 (sys_user)
CREATE TABLE IF NOT EXISTS sys_user (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(200) NOT NULL,
    email VARCHAR(100),
    phone VARCHAR(20),
    nickname VARCHAR(50),
    real_name VARCHAR(50),
    avatar VARCHAR(500),
    gender INT DEFAULT 0,
    birthday DATETIME,
    dept_id BIGINT,
    position VARCHAR(100),
    status INT DEFAULT 1,
    last_login_time DATETIME,
    last_login_ip VARCHAR(50),
    login_count INT DEFAULT 0,
    failed_login_count INT DEFAULT 0,
    lock_time DATETIME,
    password_reset_time DATETIME,
    is_super_admin TINYINT(1) DEFAULT FALSE,
    remark VARCHAR(500),
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    create_by BIGINT,
    update_by BIGINT,
    deleted TINYINT(1) DEFAULT FALSE
);

CREATE INDEX idx_username ON sys_user(username);
CREATE INDEX idx_email ON sys_user(email);
CREATE INDEX idx_phone ON sys_user(phone);
CREATE INDEX idx_dept_id ON sys_user(dept_id);

-- 角色表 (sys_role)
CREATE TABLE IF NOT EXISTS sys_role (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    role_code VARCHAR(50) NOT NULL UNIQUE,
    role_name VARCHAR(50) NOT NULL,
    description VARCHAR(200),
    data_scope INT DEFAULT 1,
    status INT DEFAULT 1,
    sort INT DEFAULT 0,
    is_system TINYINT(1) DEFAULT FALSE,
    remark VARCHAR(500),
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    create_by BIGINT,
    update_by BIGINT,
    deleted TINYINT(1) DEFAULT FALSE
);

CREATE INDEX idx_role_code ON sys_role(role_code);
CREATE INDEX idx_role_name ON sys_role(role_name);

-- 权限表 (sys_permission)
CREATE TABLE IF NOT EXISTS sys_permission (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    permission_code VARCHAR(100) NOT NULL UNIQUE,
    permission_name VARCHAR(50) NOT NULL,
    permission_type INT NOT NULL,
    parent_id BIGINT DEFAULT 0,
    path VARCHAR(200),
    component VARCHAR(200),
    icon VARCHAR(100),
    sort INT DEFAULT 0,
    status INT DEFAULT 1,
    is_visible TINYINT(1) DEFAULT TRUE,
    is_cache TINYINT(1) DEFAULT FALSE,
    is_external TINYINT(1) DEFAULT FALSE,
    external_url VARCHAR(500),
    request_method VARCHAR(20),
    api_path VARCHAR(500),
    remark VARCHAR(500),
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    create_by BIGINT,
    update_by BIGINT,
    deleted TINYINT(1) DEFAULT FALSE
);

CREATE INDEX idx_permission_code ON sys_permission(permission_code);
CREATE INDEX idx_parent_id ON sys_permission(parent_id);
CREATE INDEX idx_sort ON sys_permission(sort);

-- 用户角色关联表
CREATE TABLE IF NOT EXISTS sys_user_role (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT NOT NULL,
    role_id BIGINT NOT NULL,
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uk_user_role (user_id, role_id)
);

-- 角色权限关联表
CREATE TABLE IF NOT EXISTS sys_role_permission (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    role_id BIGINT NOT NULL,
    permission_id BIGINT NOT NULL,
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uk_role_permission (role_id, permission_id)
);

-- 部门表 (sys_department)
CREATE TABLE IF NOT EXISTS sys_department (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    dept_code VARCHAR(50) NOT NULL UNIQUE,
    dept_name VARCHAR(100) NOT NULL,
    parent_id BIGINT DEFAULT 0,
    ancestors VARCHAR(500),
    leader_id BIGINT,
    sort INT DEFAULT 0,
    status INT DEFAULT 1,
    phone VARCHAR(20),
    email VARCHAR(100),
    address VARCHAR(200),
    remark VARCHAR(500),
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    create_by BIGINT,
    update_by BIGINT,
    deleted TINYINT(1) DEFAULT FALSE
);

CREATE INDEX idx_dept_code ON sys_department(dept_code);
CREATE INDEX idx_parent_id ON sys_department(parent_id);

-- 操作日志表 (sys_operation_log)
CREATE TABLE IF NOT EXISTS sys_operation_log (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT,
    username VARCHAR(50),
    real_name VARCHAR(50),
    operation_type VARCHAR(50),
    operation_module VARCHAR(100),
    operation_description VARCHAR(500),
    request_method VARCHAR(10),
    request_url VARCHAR(500),
    request_params TEXT,
    request_ip VARCHAR(50),
    request_location VARCHAR(100),
    user_agent VARCHAR(500),
    execute_time BIGINT,
    status INT DEFAULT 1,
    error_message TEXT,
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_user_time ON sys_operation_log(user_id, create_time);
CREATE INDEX idx_module_time ON sys_operation_log(operation_module, create_time);

-- 使用考勤数据库
USE smart_office_attendance;

-- 考勤记录表 (attendance_record)
CREATE TABLE IF NOT EXISTS attendance_record (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT NOT NULL,
    dept_id BIGINT,
    attendance_date DATE NOT NULL,
    check_in_time DATETIME,
    check_out_time DATETIME,
    work_hours DECIMAL(5,2),
    late_minutes INT DEFAULT 0,
    early_minutes INT DEFAULT 0,
    overtime_hours DECIMAL(5,2) DEFAULT 0,
    attendance_status INT DEFAULT 0,
    location VARCHAR(200),
    latitude DECIMAL(10,8),
    longitude DECIMAL(11,8),
    device_info VARCHAR(200),
    ip_address VARCHAR(50),
    remark VARCHAR(500),
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

CREATE INDEX idx_user_date ON attendance_record(user_id, attendance_date);
CREATE INDEX idx_dept_date ON attendance_record(dept_id, attendance_date);

-- 请假申请表 (leave_request)
CREATE TABLE IF NOT EXISTS leave_request (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT NOT NULL,
    leave_type INT NOT NULL,
    start_time DATETIME NOT NULL,
    end_time DATETIME NOT NULL,
    duration_days DECIMAL(5,2),
    reason VARCHAR(500),
    attachment_url VARCHAR(500),
    status INT DEFAULT 0,
    approval_flow_id BIGINT,
    current_approver_id BIGINT,
    remark VARCHAR(500),
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

CREATE INDEX idx_user_status ON leave_request(user_id, status);
CREATE INDEX idx_approval_flow ON leave_request(approval_flow_id);

-- 加班申请表 (overtime_request)
CREATE TABLE IF NOT EXISTS overtime_request (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT NOT NULL,
    overtime_date DATE NOT NULL,
    start_time DATETIME NOT NULL,
    end_time DATETIME NOT NULL,
    duration_hours DECIMAL(5,2),
    reason VARCHAR(500),
    compensation_type INT DEFAULT 1,
    status INT DEFAULT 0,
    approval_flow_id BIGINT,
    current_approver_id BIGINT,
    remark VARCHAR(500),
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

CREATE INDEX idx_user_status_ot ON overtime_request(user_id, status);
CREATE INDEX idx_overtime_date ON overtime_request(overtime_date);

-- 使用审批数据库
USE smart_office_approval;

-- 工作流定义表 (workflow_definition)
CREATE TABLE IF NOT EXISTS workflow_definition (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    workflow_code VARCHAR(50) NOT NULL UNIQUE,
    workflow_name VARCHAR(100) NOT NULL,
    workflow_type INT NOT NULL,
    description VARCHAR(500),
    version INT DEFAULT 1,
    status INT DEFAULT 1,
    form_schema JSON,
    process_definition JSON,
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    create_by BIGINT,
    update_by BIGINT
);

-- 工作流实例表 (workflow_instance)
CREATE TABLE IF NOT EXISTS workflow_instance (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    workflow_definition_id BIGINT NOT NULL,
    business_key VARCHAR(100),
    business_type VARCHAR(50),
    business_data JSON,
    initiator_id BIGINT NOT NULL,
    current_node_id BIGINT,
    current_assignee_id BIGINT,
    status INT DEFAULT 0,
    start_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    end_time DATETIME,
    duration_days INT,
    remark VARCHAR(500),
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

CREATE INDEX idx_business_key ON workflow_instance(business_key);
CREATE INDEX idx_initiator_status ON workflow_instance(initiator_id, status);

-- 审批节点表 (approval_node)
CREATE TABLE IF NOT EXISTS approval_node (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    workflow_instance_id BIGINT NOT NULL,
    node_code VARCHAR(50) NOT NULL,
    node_name VARCHAR(100) NOT NULL,
    node_type INT NOT NULL,
    assignee_type INT NOT NULL,
    assignee_ids JSON,
    status INT DEFAULT 0,
    start_time DATETIME,
    end_time DATETIME,
    duration_hours DECIMAL(5,2),
    comment VARCHAR(500),
    attachment_url VARCHAR(500),
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- 插入初始数据（可选）
-- 插入超级管理员角色
USE smart_office_auth;
INSERT IGNORE INTO sys_role (role_code, role_name, description, data_scope, status, sort, is_system, remark) 
VALUES ('SUPER_ADMIN', '超级管理员', '系统超级管理员', 1, 1, 0, TRUE, '系统内置角色');

-- 插入默认权限（示例）
INSERT IGNORE INTO sys_permission (permission_code, permission_name, permission_type, parent_id, path, component, icon, sort, status, is_visible, is_cache, is_external, external_url, request_method, api_path, remark) 
VALUES ('SYSTEM_MANAGE', '系统管理', 0, 0, '/system', 'Layout', 'system', 0, 1, TRUE, FALSE, FALSE, NULL, NULL, NULL, '系统管理目录');

-- 插入默认用户（密码为加密后的"admin123"）
INSERT IGNORE INTO sys_user (username, password, email, phone, nickname, real_name, avatar, gender, dept_id, position, status, is_super_admin, remark) 
VALUES ('admin', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', 'admin@smartoffice.com', '13800138000', '管理员', '系统管理员', '', 1, NULL, '系统管理员', 1, TRUE, '默认超级管理员');

-- 关联用户角色
INSERT IGNORE INTO sys_user_role (user_id, role_id) 
SELECT u.id, r.id FROM sys_user u, sys_role r WHERE u.username = 'admin' AND r.role_code = 'SUPER_ADMIN';

-- 完成
SELECT 'MySQL数据库初始化完成' AS message;