package com.bocloud.ims.repository.resource;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

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.SecurityGroup;
import com.google.common.collect.Maps;

/**
 * 安全组Repository接口实现
 *
 * @author dongkai
 */
@Repository("securityGroupRepository")
public class SecurityGroupRepository extends BasicGenericDao<SecurityGroup, Long> {

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

    public List<SecurityGroup> 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, project.visibility project_visibility, reg.name region_name, vpc.`name` vpc_name from security_group a "
                + " left join project project on a.project_id = project.id "
                + " left join region reg on a.region_id = reg.region_id and a.vendor_id = reg.vendor_id "
                + " left join tenant t on a.tenant_id = t.id left join cloud_vendor v on a.vendor_id = v.id "
                + " left join vpc vpc on a.vpc_id = vpc.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(SecurityGroup.class, sql, paramMap);
    }

    public List<SecurityGroup> listByVendorId(Long vendorId) throws Exception {
        String sql =
            "select a.*,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.vendor_id = :vendorId";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        return this.list(SecurityGroup.class, sql, params);
    }

    public List<SecurityGroup> listByVendorId(Long vendorId, String regionId) throws Exception {
        String sql =
            "select a.*,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.vendor_id = :vendorId and a.region_id = :regionId";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        params.put("regionId", regionId);
        return this.list(SecurityGroup.class, sql, params);
    }

    public List<SecurityGroup> listByVendorId(String tenantUuid, Long vendorId, List<Long> projectIds)
        throws Exception {
        String sql =
            "select a.*,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.vendor_id = :vendorId";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        if (null != projectIds && projectIds.size() > 0) {
            sql += " and a.project_id in ( :projectIds ) ";
            params.put("projectIds", projectIds);
        }
        if (!StringUtils.isEmpty(tenantUuid)) {
            sql += " and a.tenant_uuid = :tenantUuid";
            params.put("tenantUuid", tenantUuid);
        }
        return this.list(SecurityGroup.class, sql, params);
    }

    public List<SecurityGroup> listByVpcId(Long vpcId, Long tenantId) throws Exception {
        String sql = " SELECT * FROM security_group s WHERE s.is_deleted = 0 and s.vpc_id = :vpcId ";
        Map<String, Object> params = MapTools.simpleMap("vpcId", vpcId);
        if (null != tenantId && tenantId > 0) {
            sql += " and tenant_id = :tenantId ";
            params.put("tenantId", tenantId);
        }
        return this.list(SecurityGroup.class, sql, params);
    }

    public int count(List<Param> params) throws Exception {
        String sql = "select count(1) from security_group a 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 boolean remove(Long id, Long userId) throws Exception {
        String sql =
            "update security_group 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 boolean removeByVpcId(Long vpcId, Long userId) throws Exception {
        String sql =
            "update security_group set is_deleted = true,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and vpc_id = :vpcId";
        Map<String, Object> params = MapTools.simpleMap("vpcId", vpcId);
        params.put("menderId", userId);
        params.put("gmtModify", new Date());
        return this.execute(sql, params) > 0;

    }

    public SecurityGroup query(Long id) throws Exception {
        String sql =
            "select a.*,t.name tenant_name,p.name project_name, p.visibility project_visibility,v.name vendor_name, reg.name region_name, vpc.`name` vpc_name from security_group a "
                + " left join region reg on a.region_id = reg.region_id and a.vendor_id = reg.vendor_id "
                + " left join cloud_vendor v on v.id = a.vendor_id left join tenant t on a.tenant_id = t.id "
                + " left join vpc vpc on a.vpc_id = vpc.id "
                + " left join project p on p.id = a.project_id where a.is_deleted = 0 and a.id = :id";
        Map<String, Object> params = MapTools.simpleMap(Common.ID, id);
        List<SecurityGroup> list = this.list(SecurityGroup.class, sql, params);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public List<SimpleBean> list(List<Param> params, Map<String, String> sorter) throws Exception {
        String sql = "select a.id,a.name,a.group_uuid from security_group 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<SecurityGroup> list = this.list(SecurityGroup.class, sql, paramMap);
        List<SimpleBean> beans = new ArrayList<>();
        for (SecurityGroup group : list) {
            beans.add(new SimpleBean(group.getId(), group.getName(), group.getGroupUuid()));
        }
        return beans;
    }

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

    public boolean isExists(String name, Long vendorId) throws Exception {
        String sql =
            "select a.*,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.name = :name and a.vendor_id = :vendorId";
        Map<String, Object> params = MapTools.simpleMap("name", name);
        params.put(Common.VENDORID, vendorId);
        List<SecurityGroup> list = this.list(SecurityGroup.class, sql, params);
        return !list.isEmpty();
    }

    public boolean isExists(String name, Long vendorId, String regionId) throws Exception {
        String sql =
            "select a.*,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.name = :name and a.vendor_id = :vendorId"
                + " and a.region_id = :regionId ";
        Map<String, Object> params = MapTools.simpleMap("name", name);
        params.put(Common.VENDORID, vendorId);
        List<SecurityGroup> list = this.list(SecurityGroup.class, sql, params);
        return !list.isEmpty();
    }

    public int count(List<Param> params, Long userId, Long tenantId, Long projectId) throws Exception {
        String sql = null;
        if (null != userId && null != tenantId) {
            sql =
                "select count(1) from security_group a,object_relation b where a.is_deleted = 0 and a.id = b.res_id and b.category = 'SecurityGroup' and b.catalog = 'USER' and b.target = "
                    + userId + " and a.tenant_id = " + tenantId;
        } else if (null == userId && null != tenantId) {
            sql = "select count(1) from security_group a where a.is_deleted = 0 and a.tenant_id = " + tenantId;
        } else {
            sql = "select count(1) from security_group a where a.is_deleted = 0";
        }
        if (null != projectId && 0L != projectId) {
            sql += " and a.project_id = " + projectId;
        }
        sql = QueryBuilder.buildRaw(sql, params, null, "a");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        return this.countQuery(sql, paramMap).intValue();
    }

    public List<SecurityGroup> list(int page, int rows, List<Param> params, Map<String, String> sorter, Long userId,
        Long tenantId, Long projectId) throws Exception {
        String sql = null;
        if (null != userId && null != tenantId) {
            sql =
                "select a.*,v.name vendor_name,v.type vendor_type,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id left join cloud_vendor v on a.vendor_id = v.id,object_relation b where a.is_deleted = 0 and a.id = b.res_id and b.category = 'SecurityGroup' and b.catalog = 'USER' and b.target = "
                    + userId + " and a.tenant_id = " + tenantId;
        } else if (null == userId && null != tenantId) {
            sql =
                "select a.*,v.name vendor_name,v.type vendor_type,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id left join cloud_vendor v on a.vendor_id = v.id,object_relation b where a.is_deleted = 0 and a.id = b.res_id and b.category = 'SecurityGroup' and b.catalog = 'USER' and a.tenant_id = "
                    + tenantId;
        } else {
            sql =
                "select a.*,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0";
        }
        if (null != projectId && 0L != projectId) {
            sql += " and a.project_id = " + projectId;
        }
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        return this.list(SecurityGroup.class, sql, paramMap);
    }

    public SecurityGroup getByGroupId(String groupUuid) throws Exception {
        String sql =
            "select a.*,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.group_uuid = :groupUuid";
        Map<String, Object> params = MapTools.simpleMap("groupUuid", groupUuid);
        List<SecurityGroup> list = this.list(SecurityGroup.class, sql, params);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public SecurityGroup getByGroupId(String groupUuid, Long vendorId) throws Exception {
        String sql =
            "select a.*,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.group_uuid = :groupUuid and a.vendor_id = :vendorId ";
        Map<String, Object> params = MapTools.simpleMap("groupUuid", groupUuid);
        params.put("vendorId", vendorId);
        List<SecurityGroup> list = this.list(SecurityGroup.class, sql, params);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 根据UUID查询安全组
     *
     * @param groupUuid
     * @param vendorId
     * @return
     * @throws Exception
     */

    public SecurityGroup getByGroupUuid(String groupUuid, Long vendorId) throws Exception {
        String sql =
            "select a.*,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.group_uuid = :groupUuid and a.vendor_id = :vendorId";
        Map<String, Object> params = MapTools.simpleMap("groupUuid", groupUuid);
        params.put(Common.VENDORID, vendorId);
        List<SecurityGroup> list = this.list(SecurityGroup.class, sql, params);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public SecurityGroup getByName(String name, String tenantUuid) throws Exception {
        String sql =
            "select a.*,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.name = :name";
        Map<String, Object> params = MapTools.simpleMap("name", name);
        if (!StringUtils.isEmpty(tenantUuid)) {
            sql += " and a.tenant_uuid = :tenantUuid ";
            params.put("tenantUuid", tenantUuid);
        }
        List<SecurityGroup> list = this.list(SecurityGroup.class, sql, params);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public boolean inUseByTenants(Long vendorId) throws Exception {
        String sql =
            "select count(1) from security_group a where a.is_deleted = 0 and a.tenant_id is not null and a.tenant_id != 0 and a.vendor_id = :vendorId";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        return this.countQuery(sql, params).intValue() > 0;
    }

    public SimpleBean getDefaultSgroup(Long vendorId, String tenantUuid) throws Exception {
        String sql =
            "select a.id,a.name,a.group_uuid from security_group a where a.is_deleted = 0 and a.name = 'default' and a.vendor_id = :vendorId";
        Map<String, Object> paramMap = MapTools.simpleMap(Common.VENDORID, vendorId);
        if (!StringUtils.isEmpty(tenantUuid)) {
            sql += " and a.tenant_uuid = :tenantUuid";
            paramMap.put("tenantUuid", tenantUuid);
        }
        List<SecurityGroup> list = this.list(SecurityGroup.class, sql, paramMap);
        if (ListTool.isEmpty(list)) {
            return null;
        }
        SecurityGroup group = list.get(0);
        return new SimpleBean(group.getId(), group.getName(), group.getGroupUuid());
    }

    public List<SecurityGroup> listByServerId(Long serverId) throws Exception {
        String sql =
            "select a.* from security_group a,server_sgroup b where a.id = b.group_id and b.server_id = :serverId";
        Map<String, Object> paramMap = MapTools.simpleMap("serverId", serverId);
        return this.list(SecurityGroup.class, sql, paramMap);
    }

    public boolean tenantCheck(Long tenantId, Long projectId, Long creatorId) throws Exception {
        String sql = "select count(1) from security_group a where a.is_deleted = 0 ";
        Map<String, Object> paramMap = Maps.newHashMap();
        if (null != tenantId && 0L != tenantId) {
            sql += " and a.tenant_id = :tenantId";
            paramMap.put("tenantId", tenantId);
        }
        if (null != projectId && 0L != projectId) {
            sql += " and a.project_id = :projectId";
            paramMap.put("projectId", projectId);
        }
        if (null != creatorId && 0L != creatorId) {
            sql += " and a.creator_id = :creatorId";
            paramMap.put("creatorId", creatorId);
        }
        return this.countQuery(sql, paramMap).intValue() > 0;
    }

    public List<SecurityGroup> listByVendorId(Long vendorId, String regionId, List<Long> projectIds) throws Exception {
        String sql =
            "select a.*,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.vendor_id = :vendorId"
                + " and a.region_id = :regionId ";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        params.put(Common.REGIONID, regionId);
        if (null != projectIds && projectIds.size() > 0) {
            sql += " and a.project_id in ( :projectIds ) ";
            params.put("projectIds", projectIds);
        }
        return this.list(SecurityGroup.class, sql, params);
    }

    public boolean removeByVid(Long vendorId, String regionId, Long userId) throws Exception {
        String sql =
            "update security_group set is_deleted = true,gmt_modify = :gmtModify,mender_id = :menderId 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);
        params.put("menderId", userId);
        params.put("gmtModify", new Date());
        return this.execute(sql, params) > 0;
    }

    public SecurityGroup getByName(String name, String region, Long vendorId) throws Exception {
        String sql =
            "select a.*,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.name = :name"
                + " and a.region_id = :region and a.vendor_id = :vendorId ";
        Map<String, Object> params = MapTools.simpleMap("name", name);
        params.put("region", region);
        params.put(Common.VENDORID, vendorId);
        List<SecurityGroup> list = this.list(SecurityGroup.class, sql, params);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public List<SecurityGroup> listByGroupName(Long vendorId, String regionId, String resourceGroupName)
        throws Exception {
        String sql =
            "select a.*,t.name tenant_name from security_group a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.vendor_id = :vendorId and azure_resource_group_name = :resourceGroupName and region_id = :regionId ";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        params.put("resourceGroupName", resourceGroupName);
        params.put("regionId", regionId);
        return this.list(SecurityGroup.class, sql, params);
    }

    public List<SecurityGroup> listByVpcId(Long vpcId, Long tenant, List<Long> projectIds) {
        String sql = " SELECT s.* FROM security_group s WHERE s.is_deleted = 0 and s.vpc_id = :vpcId ";
        Map<String, Object> params = MapTools.simpleMap("vpcId", vpcId);
        if (null != projectIds && projectIds.size() > 0) {
            sql += " and s.project_id in ( :projectIds ) ";
            params.put("projectIds", projectIds);
        }
        return this.list(SecurityGroup.class, sql, params);
    }

    public int count(List<Param> params, List<Long> tenantVendorIds, List<String> tenantUuids, Long tenantId) {
        String sql = "select count(1) from security_group a where a.is_deleted = 0 ";
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        if (!ListTool.isEmpty(tenantVendorIds)) {
            sql += " and a.vendor_id in (:tenantVendorIds) ";
            paramMap.put("tenantVendorIds", tenantVendorIds);
        }
        if (!ListTool.isEmpty(tenantUuids) && null != tenantId) {
            sql += " and (a.tenant_id = :tenantId or a.tenant_uuid in (:tenantUuids)) ";
            paramMap.put("tenantUuids", tenantUuids);
            paramMap.put("tenantId", tenantId);
        }
        sql = QueryBuilder.buildRaw(sql, params, null, "a");
        return this.countQuery(sql, paramMap).intValue();
    }

    public List<SecurityGroup> list(Integer page, Integer rows, List<Param> params, Map<String, String> sorter,
        List<Long> tenantVendorIds, List<String> tenantUuids, Long tenantId) {
        String sql =
            "select a.*,v.name vendor_name,v.type vendor_type,t.name tenant_name, project.visibility project_visibility, reg.name region_name, vpc.`name` vpc_name from security_group a "
                + " left join project project on a.project_id = project.id "
                + " left join region reg on a.region_id = reg.region_id and a.vendor_id = reg.vendor_id "
                + " left join tenant t on a.tenant_id = t.id left join cloud_vendor v on a.vendor_id = v.id "
                + " left join vpc vpc on a.vpc_id = vpc.id where a.is_deleted = 0";
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        if (!ListTool.isEmpty(tenantVendorIds)) {
            sql += " and a.vendor_id in (:tenantVendorIds) ";
            paramMap.put("tenantVendorIds", tenantVendorIds);
        }
        if (!ListTool.isEmpty(tenantUuids) && null != tenantId) {
            sql += " and (a.tenant_id = :tenantId or a.tenant_uuid in (:tenantUuids)) ";
            paramMap.put("tenantUuids", tenantUuids);
            paramMap.put("tenantId", tenantId);
        }
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
        return this.list(SecurityGroup.class, sql, paramMap);
    }

    public List<SimpleBean> list(List<Param> params, Map<String, String> sorter, List<Long> tenantVendorIds,
        List<String> tenantUuids, Long tenantId) {
        String sql = "select a.id,a.name,a.group_uuid from security_group a where a.is_deleted = 0";
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        if (!ListTool.isEmpty(tenantVendorIds)) {
            sql += " and a.vendor_id in (:tenantVendorIds) ";
            paramMap.put("tenantVendorIds", tenantVendorIds);
        }
        if (!ListTool.isEmpty(tenantUuids) && null != tenantId) {
            sql += " and (a.tenant_id = :tenantId or a.tenant_uuid in (:tenantUuids)) ";
            paramMap.put("tenantUuids", tenantUuids);
            paramMap.put("tenantId", tenantId);
        }
        sql = QueryBuilder.build(sql, new Pager(1, Integer.MAX_VALUE, params, sorter), "a");
        List<SecurityGroup> list = this.list(SecurityGroup.class, sql, paramMap);
        List<SimpleBean> beans = new ArrayList<>();
        for (SecurityGroup group : list) {
            beans.add(new SimpleBean(group.getId(), group.getName(), group.getGroupUuid()));
        }
        return beans;
    }

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

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