-- 创建日结结算单表
CREATE TABLE IF NOT EXISTS medication_day_end_settlement (
    id BIGSERIAL PRIMARY KEY,
    settlement_no VARCHAR(64) NOT NULL,
    settlement_date DATE NOT NULL,
    settlement_type VARCHAR(20) DEFAULT 'daily',
    total_amount DECIMAL(15,2) DEFAULT 0.00,
    status CHAR(1) DEFAULT '0',
    remark VARCHAR(500),
    create_by VARCHAR(64) DEFAULT '',
    create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    update_by VARCHAR(64) DEFAULT '',
    update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 添加注释
COMMENT ON TABLE medication_day_end_settlement IS '日结结算单表';
COMMENT ON COLUMN medication_day_end_settlement.settlement_no IS '结算单号';
COMMENT ON COLUMN medication_day_end_settlement.settlement_date IS '结算日期';
COMMENT ON COLUMN medication_day_end_settlement.settlement_type IS '结算类型 (daily, weekly, monthly)';
COMMENT ON COLUMN medication_day_end_settlement.total_amount IS '总金额';
COMMENT ON COLUMN medication_day_end_settlement.status IS '状态 (0正常 1停用)';
COMMENT ON COLUMN medication_day_end_settlement.remark IS '备注';
COMMENT ON COLUMN medication_day_end_settlement.create_by IS '创建者';
COMMENT ON COLUMN medication_day_end_settlement.create_time IS '创建时间';
COMMENT ON COLUMN medication_day_end_settlement.update_by IS '更新者';
COMMENT ON COLUMN medication_day_end_settlement.update_time IS '更新时间';

-- 添加索引
CREATE INDEX IF NOT EXISTS idx_settlement_date ON medication_day_end_settlement(settlement_date);
CREATE INDEX IF NOT EXISTS idx_settlement_no ON medication_day_end_settlement(settlement_no);

-- 创建更新时间触发器函数
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.update_time = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ language 'plpgsql';

-- 创建更新时间触发器
DROP TRIGGER IF EXISTS update_medication_day_end_settlement_modtime ON medication_day_end_settlement;
CREATE TRIGGER update_medication_day_end_settlement_modtime
    BEFORE UPDATE ON medication_day_end_settlement
    FOR EACH ROW
    EXECUTE FUNCTION update_modified_column();

-- 插入初始数据
INSERT INTO medication_day_end_settlement (settlement_no, settlement_date, settlement_type, total_amount, status, remark, create_by) VALUES
('DS20250201001', '2025-02-01', 'daily', 15000.00, '0', '2025年2月1日日结', 'admin'),
('DS20250201002', '2025-02-01', 'daily', 8500.50, '0', '药房日结', 'admin');