package com.bocloud.ims.service.upgrade.migration.from50to55;

import com.bocloud.ims.service.upgrade.UpgradeVersion;
import com.bocloud.ims.service.upgrade.migration.SimpleDataMigrationTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.*;

/**
 * role_permission数据导入任务
 * 1. 维持超级管理员角色的权限不变（拥有所有权限）
 * 2. 删掉其他角色中已授予的但是5.5中删除了的权限
 * @author luyanchao
 * @date 2021-06-09
 */
@Component("5.0-5.5-RolePermissionTask")
public class RolePermissionTask extends SimpleDataMigrationTask {

    /**
     * 构造方法
     *
     * @param context spring上下文
     */
    @Autowired
    public RolePermissionTask(ApplicationContext context, SmsRoleTask smsRoleTask) {
        super(context);
        this.dependOn(smsRoleTask);
    }

    @Override
    public String[] getTables() {
        return new String[]{"role_permission"};
    }

    @Override
    public void run() {
        Assert.notNull(this.fromDataSource, "fromDataSource can't be null");
        NamedParameterJdbcTemplate targetJdbcTemplate = this.getContext().getBean(NamedParameterJdbcTemplate.class);
        // 查询5.5中超级管理员角色id
        String sqlQuery = "select id from role where name = '超级管理员'";
        List<Map<String, Object>> role = targetJdbcTemplate.queryForList(sqlQuery, new HashMap<>());
        Assert.isTrue(role.size() == 1, "Can't find admin role ");
        Long roleId = Long.parseLong(role.get(0).get("id").toString());
        // 查询5.5中超级管理员角色拥有的权限id列表
        String sqlSelect = "select permission_id from role_permission a where role_id = :roleId";
        List<Map<String, Object>> permissions = targetJdbcTemplate.queryForList(sqlSelect, Collections.singletonMap("roleId", roleId));
        // 清空5.5中role_permission数据
        String sqlTruncate = "truncate role_permission ";
        targetJdbcTemplate.update(sqlTruncate, new HashMap<>());
        // 从5.0导入role_permission数据到5.5
        super.run();
        // 删掉导入后5.5中超级管理员角色拥有的权限id列表并重新插入
        String sqlDelete = "delete a from role_permission a join role b on a.role_id = b.id where b.name = '超级管理员' ";
        targetJdbcTemplate.update(sqlDelete, new HashMap<>());
        String sqlInsert = "insert into role_permission (role_id, permission_id) values (:roleId, :permissionId) ";
        for (Map<String, Object> permission : permissions) {
            Long permissionId = Long.parseLong(permission.get("permission_id").toString());
            Map<String, Object> sqlParams = new HashMap<>();
            sqlParams.put("roleId", roleId);
            sqlParams.put("permissionId", permissionId);
            targetJdbcTemplate.update(sqlInsert, sqlParams);
        }
        // 删掉角色中已授予的，但是5.5中删除了的权限
        String sqlClear = "delete from role_permission where permission_id not in (select id from permission) ";
        targetJdbcTemplate.update(sqlClear, new HashMap<>());
    }

    @Override
    public UpgradeVersion getUpgradeVersion() {
        return UpgradeVersion.from50to55;
    }
}
