SET @current_db := DATABASE();

SET @column_exists := (
  SELECT COUNT(1)
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = @current_db
    AND TABLE_NAME = 'asr_bas_station_path_profile'
    AND COLUMN_NAME = 'is_default'
);

SET @add_column_sql := IF(
  @column_exists = 0,
  'ALTER TABLE asr_bas_station_path_profile ADD COLUMN is_default TINYINT NOT NULL DEFAULT 0 COMMENT ''默认模板 1是 0否'' AFTER status',
  'SELECT ''column is_default already exists'' '
);
PREPARE stmt_add_column FROM @add_column_sql;
EXECUTE stmt_add_column;
DEALLOCATE PREPARE stmt_add_column;

SET @default_profile_code := (
  SELECT COALESCE(MAX(TRIM(`value`)), 'default')
  FROM `sys_config`
  WHERE `code` = 'stationPathDefaultProfileCode'
);

UPDATE `asr_bas_station_path_profile`
SET `is_default` = 0;

UPDATE `asr_bas_station_path_profile`
SET `is_default` = 1
WHERE `profile_code` = @default_profile_code
  AND `status` = 1;

UPDATE `asr_bas_station_path_profile`
SET `is_default` = 1
WHERE `profile_code` = 'default'
  AND `status` = 1
  AND NOT EXISTS (
    SELECT 1
    FROM (
      SELECT `id`
      FROM `asr_bas_station_path_profile`
      WHERE `is_default` = 1
    ) t
  );

UPDATE `asr_bas_station_path_profile`
SET `is_default` = 1
WHERE `id` = (
  SELECT `id`
  FROM (
    SELECT `id`
    FROM `asr_bas_station_path_profile`
    WHERE `status` = 1
    ORDER BY `priority` ASC, `id` ASC
    LIMIT 1
  ) t
)
AND NOT EXISTS (
  SELECT 1
  FROM (
    SELECT `id`
    FROM `asr_bas_station_path_profile`
    WHERE `is_default` = 1
  ) t
);

DELETE FROM `sys_config`
WHERE `code` = 'stationPathDefaultProfileCode';
