DROP PROCEDURE IF EXISTS add_tb_column;
DELIMITER $$
CREATE PROCEDURE add_tb_column()
BEGIN
		DECLARE  CurrentDatabase VARCHAR(100);
SELECT DATABASE() INTO CurrentDatabase;

-- fs_user_course_period 表添加 period_status 字段
IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS  WHERE TABLE_SCHEMA=CurrentDatabase
            AND TABLE_NAME='fs_user_course_period'
            AND COLUMN_NAME='period_status' )
		THEN
alter table fs_user_course_period add column period_status int COMMENT '营期状态，1-未开始，2-进行中，3-已结束';
END IF;




--  添加 fs_user_course_count 表的索引，字段为 user_id
IF NOT EXISTS ( SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = CurrentDatabase
                AND TABLE_NAME = 'fs_user_course_count'
                AND INDEX_NAME = 'user_id_unique' )
        THEN
alter table fs_user_course_count ADD INDEX user_id_unique ( `user_id` ASC );
END IF;

END;

CALL add_tb_column;

DROP PROCEDURE IF EXISTS add_tb_column;


-- ---------------------------- 新增表
DROP TABLE IF EXISTS `fs_user_company_user`;
CREATE TABLE `fs_user_company_user`  (
                                         `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
                                         `user_id` bigint NULL DEFAULT NULL COMMENT '用户id（关联fs_user表user_id）',
                                         `company_user_id` bigint NULL DEFAULT NULL COMMENT '销售id',
                                         `company_id` int NULL DEFAULT NULL COMMENT '公司ID',
                                         `is_repeat_fans` tinyint NULL DEFAULT 0 COMMENT '是否重粉，1-是；0-否',
                                         PRIMARY KEY (`id`) USING BTREE,
                                         INDEX `user_id_index`(`user_id` ASC) USING BTREE,
                                         INDEX `company_user_id_index`(`company_user_id` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 21 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '微信用户和销售关系表' ROW_FORMAT = Dynamic;

-- ---------------- 初始化数据
INSERT INTO fs_user_company_user ( user_id, company_user_id, company_id, is_repeat_fans ) (
    SELECT
        fs_user.user_id,
        company_user.user_id,
        company_user.company_id,
        0
    FROM
        fs_user
            LEFT JOIN company_user ON company_user.user_id = fs_user.company_user_id
)
