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

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.blob.Blob;
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.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * azure blob存储数据访问
 *
 * @author wangyu
 * @version 5.0.0-SNAPSHOT
 * @since 2021/2/2
 */
@Repository
public class BlobRepository extends BasicGenericDao<Blob, Long> {

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

    public int count(List<Param> params, Long userId, List<Long> projectIds, Long storageAccountId) throws BoCloudDBException {
        StringBuilder builder = new StringBuilder("select count(a.id) from azure_blob a left join container b on b.id = a.container_id where a.is_deleted = 0");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        if (!ListTool.isEmpty(projectIds)) {
            builder.append(" and a.project_id in (:projectIds)");
            paramMap.put("projectIds", projectIds);
        }
        if (null != userId && 0L != userId) {
            builder.append(" and a.user_id = :userId");
            paramMap.put("userId", userId);
        }
        if (null != storageAccountId && 0L != storageAccountId) {
            builder.append(" and b.storage_account_id = :storageAccountId");
            paramMap.put("storageAccountId", storageAccountId);
        }
        String sql = QueryBuilder.buildRaw(builder.toString(), params, null, "a");
        return this.countQuery(sql, paramMap).intValue();
    }

    public List<Blob> list(int page, int rows, List<Param> params, Map<String, String> sorter, Long userId, List<Long> projectIds, Long storageAccountId) throws BoCloudDBException {
        StringBuilder builder = new StringBuilder("select a.*,b.name vendor_name,c.name tenant_name,d.name project_name,e.name container_name from azure_blob a left join cloud_vendor b on b.id = a.vendor_id left join tenant c on c.id = a.tenant_id left join project d on d.id = a.project_id left join container e on e.id = a.container_id where a.is_deleted = 0");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        if (!ListTool.isEmpty(projectIds)) {
            builder.append(" and a.project_id in (:projectIds)");
            paramMap.put("projectIds", projectIds);
        }
        if (null != userId && 0L != userId) {
            builder.append(" and a.user_id = :userId");
            paramMap.put("userId", userId);
        }
        if (null != storageAccountId && 0L != storageAccountId) {
            builder.append(" and e.storage_account_id = :storageAccountId");
            paramMap.put("storageAccountId", storageAccountId);
        }
        String sql = QueryBuilder.buildRaw(builder.toString(), new Pager(page, rows, params, sorter), "a");
        return this.list(Blob.class, sql, paramMap);
    }

    public List<SimpleBean> list(List<Param> params, Map<String, String> sorter, Long userId, List<Long> projectIds, Long storageAccountId) throws BoCloudDBException {
        String sql = "select a.id,a.name from azure_blob a left join container b on b.id = a.container_id where a.is_deleted = 0";
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        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);
        }
        if (null != storageAccountId && 0L != storageAccountId) {
            sql += " and b.storage_account_id = :storageAccountId";
            paramMap.put("storageAccountId", storageAccountId);
        }
        sql = QueryBuilder.build(sql, new Pager(1, Integer.MAX_VALUE, params, sorter), "a");
        List<Blob> objects = this.list(Blob.class, sql, paramMap);
        return objects.stream().map(object -> new SimpleBean(object.getId(), object.getName())).collect(Collectors.toList());
    }

    public Blob query(Long id) throws Exception {
        String sql = "select a.*,b.name vendor_name,c.name tenant_name,d.name project_name,e.name container_name from azure_blob a left join cloud_vendor b on b.id = a.vendor_id left join tenant c on c.id = a.tenant_id left join project d on d.id = a.project_id left join container e on e.id = a.container_id where a.is_deleted = 0 and a.id = :id";
        Map<String, Object> param = MapTools.simpleMap(Common.ID, id);
        List<Blob> list = this.list(Blob.class, sql, param);
        return list.isEmpty() ? null : list.get(0);
    }

    public Blob getByName(String name, Long containerId, Long vendorId, Boolean snapshot) throws BoCloudDBException {
        String sql = "select a.* from azure_blob a where a.is_deleted = 0 and a.vendor_id = :vendorId and a.name = :name and a.container_id = :containerId ";
        Map<String, Object> paramMap = MapTools.simpleMap(Common.VENDORID, vendorId);
        paramMap.put(Common.NAME, name);
        paramMap.put("containerId", containerId);
        if (null != snapshot) {
            sql += " and is_snapshot = :snapshot";
            paramMap.put("snapshot", snapshot);
        }
        List<Blob> list = this.list(Blob.class, sql, paramMap);
        return list.isEmpty() ? null : list.get(0);
    }

    public List<Blob> listByCondition(Long vendorId, Long containerId, Boolean snapshot) throws BoCloudDBException {
        String sql = "select * from azure_blob where is_deleted = 0 and vendor_id = :vendorId ";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        if (null != containerId && 0L != containerId) {
            sql += " and container_id = :containerId";
            params.put("containerId", containerId);
        }
        if (null != snapshot) {
            sql += " and is_snapshot = :snapshot";
            params.put("snapshot", snapshot);
        }
        return this.list(Blob.class, sql, params);
    }

    public boolean removeByContainerId(Long containerId, Long managerId) throws BoCloudDBException {
        String sql = "update azure_blob set is_deleted = true , gmt_modify = :gmtModify ,mender_id = :menderId where is_deleted = 0 and container_id = :containerId";
        Map<String, Object> params = MapTools.simpleMap("containerId", containerId);
        params.put("menderId", managerId);
        params.put("gmtModify", new Date());
        return this.execute(sql, params) > 0;
    }

    public boolean removeByContainerId(Long containerId, Boolean snapshot, Long managerId) throws BoCloudDBException {
        String sql = "update azure_blob set is_deleted = true , gmt_modify = :gmtModify ,mender_id = :menderId where is_deleted = 0 and container_id = :containerId";
        Map<String, Object> params = MapTools.simpleMap("containerId", containerId);
        params.put("menderId", managerId);
        params.put("gmtModify", new Date());
        if (null != snapshot) {
            sql += " and is_snapshot=:snapshot";
            params.put("snapshot", snapshot);
        }
        return this.execute(sql, params) > 0;
    }

    public boolean removeByVendorId(Long vendorId, Long managerId) throws BoCloudDBException {
        String sql = "update azure_blob set is_deleted = true , gmt_modify = :gmtModify ,mender_id = :menderId where is_deleted = 0 and vendor_id = :vendorId";
        Map<String, Object> params = MapTools.simpleMap("vendorId", vendorId);
        params.put("menderId", managerId);
        params.put("gmtModify", new Date());
        return this.execute(sql, params) > 0;
    }

    public boolean removeSnapshot(String name, Long containerId, Long managerId) throws BoCloudDBException {
        String sql = "update azure_blob set is_deleted = true , gmt_modify = :gmtModify ,mender_id = :menderId where is_deleted = 0 and container_id = :containerId and name = :name and is_snapshot = 1";
        Map<String, Object> params = MapTools.simpleMap("containerId", containerId);
        params.put("menderId", managerId);
        params.put("gmtModify", new Date());
        params.put("name", name);
        return this.execute(sql, params) > 0;
    }

    public boolean remove(Long id, Long managerId) throws BoCloudDBException {
        String sql = "update azure_blob 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("menderId", managerId);
        params.put("gmtModify", new Date());
        return this.execute(sql, params) > 0;
    }

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