package com.bocloud.ims.repository.resource.azure.db;

import com.bocloud.common.exception.BoCloudDBException;
import com.bocloud.common.model.Pager;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.SimpleBean;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.ListTool;
import com.bocloud.common.utils.MapTools;
import com.bocloud.database.core.intf.impl.BasicGenericDao;
import com.bocloud.database.utils.QueryBuilder;
import com.bocloud.ims.entity.resource.azure.db.AzureDatabaseServer;
import com.google.common.collect.Lists;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Company: 博云 www.bocloud.com
 * @ClassName: AzureDatabaseRepository
 * @Description:
 * @author: zhenpingLi/李振平
 * @date: 2020/12/18 15:28
 */
@Repository("cloudDatabaseServerRepository")
public class CloudDatabaseServerRepository extends BasicGenericDao<AzureDatabaseServer, Long> {

    public CloudDatabaseServerRepository(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) {
        super(jdbcTemplate, npJdbcTemplate);
    }


    public int count(List<Param> params, Long tenantId, List<Long> projectIds, Long userId) {
        String sql = " select count(a.id) from azure_database_server a where a.is_deleted = 0 ";
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        if (null != tenantId && 0L != tenantId) {
            sql += " and a.tenant_id = :tenantId";
            paramMap.put("tenantId", tenantId);
        }
        if (!ListTool.isEmpty(projectIds)) {
            sql += " and a.project_id in (:projectIds) ";
            paramMap.put("projectIds", projectIds);
        }
        if (null != userId && 0L != userId) {
            sql += " and a.user_id = :userId";
            paramMap.put("userId", userId);
        }
        sql = QueryBuilder.buildRaw(sql, params, null, "a");
        return this.countQuery(sql, paramMap).intValue();
    }

    public List<AzureDatabaseServer> list(int page, int rows, List<Param> params, Map<String, String> sorter, Long tenantId,
                                          List<Long> projectIds, Long userId) {
        String sql = "select a.*,v.name vendor_name,v.type vendor_type,t.name tenant_name, p.name project_name, r.name region_name, rg.name resource_group_name "
                + " from azure_database_server a "
                + " left join tenant t on a.tenant_id = t.id "
                + " left join project p on a.project_id = p.id "
                + " left join cloud_vendor v on a.vendor_id = v.id "
                + " left join region r on a.region_id = r.region_id and r.vendor_id = v.id "
                + " left join resource_group rg on a.resource_group_id = rg.id "
                + " where a.is_deleted = 0 ";
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        if (null != tenantId && 0L != tenantId) {
            sql += " and a.tenant_id = :tenantId";
            paramMap.put("tenantId", tenantId);
        }
        if (!ListTool.isEmpty(projectIds)) {
            sql += " and a.project_id in (:projectIds) ";
            paramMap.put("projectIds", projectIds);
        }
        if (null != userId && 0L != userId) {
            sql += " and a.user_id = :userId";
            paramMap.put("userId", userId);
        }

        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
        return this.list(AzureDatabaseServer.class, sql, paramMap);
    }


    public List<AzureDatabaseServer> list(int page, int rows, List<Param> params, Map<String, String> sorter) throws BoCloudDBException {
        String sql = "select a.*,v.name vendor_name,v.type vendor_type,t.name tenant_name, p.name project_name, r.name region_name, rg.name resource_group_name "
                + " from azure_database_server a "
                + " left join tenant t on a.tenant_id = t.id "
                + " left join project p on a.project_id = p.id "
                + " left join cloud_vendor v on a.vendor_id = v.id "
                + " left join region r on a.region_id = r.region_id and r.vendor_id = v.id "
                + " left join resource_group rg on a.resource_group_id = rg.id "
                + " where a.is_deleted = 0 ";
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
        return this.list(AzureDatabaseServer.class, sql);
    }

    public int count(List<Param> params) throws BoCloudDBException {
        String sql = "select count(1) "
                + " from azure_database_server a "
                + " left join tenant t on a.tenant_id = t.id "
                + " left join project p on a.project_id = p.id "
                + " left join cloud_vendor v on a.vendor_id = v.id "
                + " left join region r on a.region_id = r.region_id and r.vendor_id = v.id "
                + " left join resource_group rg on a.resource_group_id = rg.id "
                + " where a.is_deleted = 0 ";
        sql = QueryBuilder.buildRaw(sql, params, null, "a");
        Map<String, Object> param = QueryBuilder.getParam(params);
        return this.countQuery(sql, param).intValue();
    }

    public boolean remove(long id, Long userId) throws BoCloudDBException {
        String sql = "update azure_database_server set is_deleted = true,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and id = :id";
        Map<String, Object> params = MapTools.simpleMap(Common.ID, id);
        params.put(Common.MENDER_ID, userId);
        params.put("gmtModify", new Date());
        return this.execute(sql, params) > 0;
    }

    public boolean removeByVid(Long vendorId, Long userId) throws BoCloudDBException {
        String sql = "update azure_database_server set is_deleted = 1, gmt_modify = :gmtModify, mender_id = :menderId where vendor_id = :vendorId";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        params.put("gmtModify", new Date());
        params.put(Common.MENDER_ID, userId);
        return this.execute(sql, params) > 0;
    }

    public boolean removeByVid(Long vendorId, String regionId, Long userId) throws BoCloudDBException {
        String sql = "update azure_database_server set is_deleted = 1, gmt_modify = :gmtModify, mender_id = :menderId where vendor_id = :vendorId and region_id = :regionId ";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        params.put(Common.REGIONID, regionId);
        params.put("gmtModify", new Date());
        params.put(Common.MENDER_ID, userId);
        return this.execute(sql, params) > 0;
    }

    public List<AzureDatabaseServer> listByVendorId(long vendorId) throws BoCloudDBException {
        String sql = "select * from azure_database_server where is_deleted = 0 and vendor_id = :vendorId";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        return this.list(AzureDatabaseServer.class, sql, params);
    }

    public List<AzureDatabaseServer> listByVendorId(long vendorId, String regionId) throws BoCloudDBException {
        String sql = "select * from azure_database_server where is_deleted = 0 and vendor_id = :vendorId and region_id = :regionId";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        params.put(Common.REGIONID, regionId);
        return this.list(AzureDatabaseServer.class, sql, params);
    }

    public AzureDatabaseServer query(long id) throws BoCloudDBException {
        String sql = "select a.*,v.name vendor_name,v.type vendor_type,t.name tenant_name, p.name project_name, r.name region_name, rg.name resource_group_name "
                + " from azure_database_server a "
                + " left join tenant t on a.tenant_id = t.id "
                + " left join project p on a.project_id = p.id "
                + " left join cloud_vendor v on a.vendor_id = v.id "
                + " left join region r on a.region_id = r.region_id and r.vendor_id = v.id "
                + " left join resource_group rg on a.resource_group_id = rg.id "
                + " where a.is_deleted = 0 and a.id = :id";
        Map<String, Object> params = MapTools.simpleMap(Common.ID, id);
        List<AzureDatabaseServer> list = this.list(AzureDatabaseServer.class, sql, params);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public AzureDatabaseServer getByUuid(String uuid) throws BoCloudDBException {
        String sql = "select a.* from azure_database_server a where a.uuid = :uuid ";
        Map<String, Object> params = new HashMap<>();
        params.put(Common.UUID, uuid);
        List<AzureDatabaseServer> list = this.list(AzureDatabaseServer.class, sql, params);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public void remove(long id) throws BoCloudDBException {
        String sql = "update azure_database_server set is_deleted = 1 where id = :id ";
        Map<String, Object> params = new HashMap<>();
        params.put(Common.ID, id);
        execute(sql, params);
    }

    public List<SimpleBean> list(List<Param> params, Map<String, String> sorter) throws BoCloudDBException {
        String sql = "select a.id,a.uuid,a.name from azure_database_server a where a.is_deleted = 0";
        sql = QueryBuilder.buildRaw(sql, new Pager(1, Integer.MAX_VALUE, params, sorter), "a");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        List<AzureDatabaseServer> list = this.list(AzureDatabaseServer.class, sql, paramMap);
        List<SimpleBean> beans = Lists.newArrayList();
        for (AzureDatabaseServer entity : list) {
            beans.add(new SimpleBean(entity.getId(), entity.getDatabaseServerUuid(), entity.getName()));
        }
        return beans;
    }

    public AzureDatabaseServer getByName(Long vendorId, Long resourceGroupId, String name) throws BoCloudDBException {
        String sql = "select a.* from azure_database_server a where a.is_deleted = 0 and a.vendor_id = :vendorId and a.name = :name and a.resource_group_id = :resourceGroupId ";
        Map<String, Object> paramMap = MapTools.simpleMap(Common.VENDORID, vendorId);
        paramMap.put(Common.NAME, name);
        paramMap.put("resourceGroupId", resourceGroupId);
        List<AzureDatabaseServer> list = this.list(AzureDatabaseServer.class, sql, paramMap);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public boolean removeByGroupId(Long vendorId, Long userId, Long resourceGroupId) throws BoCloudDBException {
        String sql = "update azure_database_server set is_deleted = 1, gmt_modify = :gmtModify, mender_id = :menderId where vendor_id = :vendorId and resource_group_id = :resourceGroupId";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        params.put("resourceGroupId", resourceGroupId);
        params.put("gmtModify", new Date());
        params.put(Common.MENDER_ID, userId);
        return this.execute(sql, params) > 0;
    }

    public boolean hasBuilding(Long vendorId) {
        String sql = "select count(1) from azure_database_server a where a.is_deleted = 0 and a.status = 'BUILDING' and a.vendor_id = :vendorId";
        Map<String, Object> paramMap = MapTools.simpleMap(Common.VENDORID, vendorId);
        return this.countQuery(sql, paramMap) > 0;
    }
}