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

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.AvailabilitySet;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

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

/**
 * @author weiwei
 */
@Component("availabilitySetRepository")
public class AvailabilitySetRepository extends BasicGenericDao<AvailabilitySet, Long> {

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

    public int count(List<Param> params) throws Exception {
        String sql = "select count(1) from availability_set 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 b on a.resource_group_id = b.id "
                + " where a.is_deleted = 0";
        sql = QueryBuilder.buildRaw(sql, params, null, "a");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        return this.countQuery(sql, paramMap).intValue();
    }

    public List<AvailabilitySet> list(int page, int rows, List<Param> params, Map<String, String> sorter)
            throws Exception {
        String sql = "select a.*,v.name vendor_name,v.type vendor_type,t.name tenant_name, p.name project_name, r.name region_name,b.name resource_group_name from availability_set 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 b on a.resource_group_id = b.id "
                + " where a.is_deleted = 0";
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        return this.list(AvailabilitySet.class, sql, paramMap);
    }

    public int count(List<Param> params, Long tenantId, List<Long> projectIds, Long userId) {
        String sql = " select count(a.id) from availability_set 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 b on a.resource_group_id = b.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, params, null, "a");
        return this.countQuery(sql, paramMap).intValue();
    }

    public List<AvailabilitySet> 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,b.name resource_group_name from availability_set 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 b on a.resource_group_id = b.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(AvailabilitySet.class, sql, paramMap);
    }


    public List<SimpleBean> list(List<Param> params, Map<String, String> sorter) throws Exception {
        String sql = "select a.id,a.name from availability_set a where a.is_deleted = 0";
        sql = QueryBuilder.build(sql, new Pager(1, Integer.MAX_VALUE, params, sorter), "a");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        List<AvailabilitySet> objects = this.list(AvailabilitySet.class, sql, paramMap);
        List<SimpleBean> beans = new ArrayList<SimpleBean>();
        for (AvailabilitySet object : objects) {
            beans.add(new SimpleBean(object.getId(), object.getName()));
        }
        return beans;
    }


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

    public AvailabilitySet query(Long id) throws Exception {
        String sql = "select a.*,v.name vendor_name,v.type vendor_type,t.name tenant_name, p.name project_name, r.name region_name,b.name resource_group_name from availability_set 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 b on a.resource_group_id = b.id "
                + " where a.is_deleted = 0 and a.id = :id";
        Map<String, Object> param = MapTools.simpleMap(Common.ID, id);
        List<AvailabilitySet> list = this.list(AvailabilitySet.class, sql, param);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public boolean removeByVendor(Long vendorId, Long userId) throws Exception {
        String sql = "update availability_set 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", userId);
        params.put("gmtModify", new Date());
        return this.execute(sql, params) > 0;
    }

    public boolean removeByVid(Long vendorId, String regionId, Long userId) throws BoCloudDBException {
        String sql = "update availability_set 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 AvailabilitySet getByName(Long vendorId, Long resourceGroupId, String name) throws BoCloudDBException {
        String sql = "select a.* from availability_set 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<AvailabilitySet> list = this.list(AvailabilitySet.class, sql, paramMap);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public AvailabilitySet queryUuid(String uuid, Long vendorId) throws Exception {
        String sql = "select a.* from availability_set a where a.is_deleted = 0 and a.uuid = :uuid and a.vendor_id = :vendorId";
        Map<String, Object> params = MapTools.simpleMap(Common.UUID, uuid);
        params.put(Common.VENDORID, vendorId);
        List<AvailabilitySet> list = this.list(AvailabilitySet.class, sql, params);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public List<AvailabilitySet> listByVendorId(long vendorId, String regionId) throws BoCloudDBException {
        String sql = "select * from availability_set 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(AvailabilitySet.class, sql, params);
    }

    public List<AvailabilitySet> list(Long vendorId, String regionId) {
        String sql = "select * from availability_set where vendor_id = :vendorId and is_deleted = 0";
        Map<String, Object> params = MapTools.simpleMap("vendorId", vendorId);
        if (!StringUtils.isEmpty(regionId)) {
            sql += " and region_id = :regionId ";
            params.put(Common.REGIONID, regionId);
        }
        return this.list(AvailabilitySet.class, sql, params);
    }

    public boolean removeByGroupId(Long vendorId, Long userId, Long resourceGroupId) throws BoCloudDBException {
        String sql = "update availability_set 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 availability_set 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;
    }

}
