package com.bocloud.ims.repository.database;

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.middleware.RdsPublicCloudInstance;
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 java.util.*;

/**
 * liuyuanyuan
 */
@Repository("rdsPublicCloudInstanceRepository")
public class RdsPublicCloudInstanceRepository extends BasicGenericDao<RdsPublicCloudInstance, Long> {


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

    public List<RdsPublicCloudInstance> list(Long vendorId) throws Exception {
        String sql = "select * from rds_pc_instance where vendor_id = :vendorId and is_deleted = 0";
        Map<String, Object> params = MapTools.simpleMap("vendorId", vendorId);
        return this.list(RdsPublicCloudInstance.class, sql, params);
    }


    public RdsPublicCloudInstance query(Long id) throws Exception {
        String sql = "select * from rds_pc_instance where id = :id";
        Map<String, Object> params = MapTools.simpleMap(Common.ID, id);
        List<RdsPublicCloudInstance> list = this.list(RdsPublicCloudInstance.class, sql, params);
        if (list.isEmpty()) {
            return null;
        } else {
            return list.get(0);
        }
    }


    public boolean delete(Long id, Long userId) throws Exception {
        String sql = "update rds_pc_instance set is_deleted = 1,status = 'Released', 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;
    }


    public List<RdsPublicCloudInstance> list(int page, int rows, List<Param> params, Map<String, String> sorter, String privateIp, String dnsName) throws Exception {
        String sql = "select a.*,v.name vendor_name,b.expired_time,b.target target,t.name tenant_name,u.name target_name,p.name project_name,d.name department_name " +
                "from rds_pc a left join project p on a.project_id = p.id left join tenant t on a.tenant_id = t.id left join cloud_vendor v on a.vendor_id = v.id left join object_relation b on b.res_id=a.id and b.category = 'Rds'" +
                "left join user u on u.id = b.target left join department d on d.id = u.depart_id where a.is_deleted = 0 ";
        Map<String, Object> param = QueryBuilder.getParam(params);
        if (StringUtils.isNotBlank(privateIp)) {
            sql += " and FIND_IN_SET('" + privateIp + "', a.private_ip)";
        }
        if (StringUtils.isNotBlank(dnsName)) {
            sql += " and FIND_IN_SET('" + dnsName + "', a.dns_name)";
        }
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");

        return this.list(RdsPublicCloudInstance.class, sql, param);
    }


    public List<SimpleBean> list(List<Param> params, Map<String, String> sorter, String privateIp, String dnsName) throws Exception {
        String sql = "select a.id,a.name,a.flavor_id from rds_pc_instance a where a.is_deleted = 0";
        Map<String, Object> param = QueryBuilder.getParam(params);
        if (StringUtils.isNotBlank(privateIp)) {
            sql += " and FIND_IN_SET('" + privateIp + "', a.private_ip)";
        }
        if (StringUtils.isNotBlank(dnsName)) {
            sql += " and FIND_IN_SET('" + dnsName + "', a.dns_name)";
        }
        sql = QueryBuilder.buildRaw(sql, new Pager(1, Integer.MAX_VALUE, params, sorter), "a");
        List<RdsPublicCloudInstance> list = this.list(RdsPublicCloudInstance.class, sql, param);
        List<SimpleBean> beans = new ArrayList<>();
        for (RdsPublicCloudInstance rds : list) {
            SimpleBean simpleBean = new SimpleBean(rds.getId(), rds.getName(), rds.getFlavorId());
            beans.add(simpleBean);
        }
        return beans;
    }

    public int count(List<Param> params) throws Exception {
        String sql = "select count(1) from rds_pc_instance 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 removeByVid(Long vendor, Long userId) throws Exception {
        String sql = "update rds_pc_instance set is_deleted = 1, gmt_modify = :gmtModify, mender_id = :menderId where vendor_id = :vendorId";
        Map<String, Object> params = MapTools.simpleMap("vendorId", vendor);
        params.put("gmtModify", new Date());
        params.put("menderId", userId);
        return this.execute(sql, params) > 0;
    }

    public List<RdsPublicCloudInstance> list(int page, int rows, List<Param> params, Map<String, String> sorter) throws Exception {
        String sql = "select * from rds_pc_instance a 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(RdsPublicCloudInstance.class, sql, paramMap);
    }

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


    public List<RdsPublicCloudInstance> listByVid(Long vendor) throws Exception {
        String sql = "select a.* from rds_pc_instance a where a.is_deleted = 0 and a.vendor_id = :vendorId";
        Map<String, Object> params = MapTools.simpleMap("vendorId", vendor);
        return this.list(RdsPublicCloudInstance.class, sql, params);
    }


    public RdsPublicCloudInstance queryByInsId(String instance_id) throws Exception {
        String sql = "select * from rds_pc_instance where instance_id = :id and is_deleted = 0";
        Map<String, Object> params = MapTools.simpleMap(Common.ID, instance_id);
        List<RdsPublicCloudInstance> list = this.list(RdsPublicCloudInstance.class, sql, params);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }


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

    public int count(List<Param> params, List<Long> projectIds, String privateIp, String dnsName) throws Exception {

        String sql = "select count(*)" +
                "from rds_pc_instance a left join project p on a.project_id = p.id left join tenant t on a.tenant_id = t.id left join cloud_vendor v on a.vendor_id = v.id left join object_relation b on b.res_id=a.id and b.category = 'Rds' left join user u on u.id = b.target left join department d on d.id = u.depart_id\n" +
                "where a.is_deleted = 0 ";
        Map<String, Object> param = QueryBuilder.getParam(params);
        if (StringUtils.isNotBlank(privateIp)) {
            sql += " and FIND_IN_SET('" + privateIp + "', a.private_ip)";
        }
        if (StringUtils.isNotBlank(dnsName)) {
            sql += " and FIND_IN_SET('" + dnsName + "', a.dns_name)";
        }
        if (!ListTool.isEmpty(projectIds)) {
            sql += " and a.project_id in (:projectIds) ";
            param.put("projectIds", projectIds);
        }
        sql = QueryBuilder.build(sql, params, new HashMap<>(), "a");
        return this.countQuery(sql, param).intValue();
    }

    public List<RdsPublicCloudInstance> list(int page, int rows, List<Param> params, Map<String, String> sorter, List<Long> projectIds, String privateIp, String dnsName) throws Exception {
        String sql = "select a.*,v.name vendor_name,b.expired_time,b.target target,t.name tenant_name,u.name target_name,p.name project_name,d.name department_name " +
                "from rds_pc_instance a left join project p on a.project_id = p.id left join tenant t on a.tenant_id = t.id left join cloud_vendor v on a.vendor_id = v.id left join object_relation b on b.res_id=a.id and b.category = 'Rds' " +
                "left join user u on u.id = b.target left join department d on d.id = u.depart_id where a.is_deleted = 0 ";
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        if (StringUtils.isNotBlank(privateIp)) {
            sql += " and FIND_IN_SET('" + privateIp + "', a.private_ip)";
        }
        if (StringUtils.isNotBlank(dnsName)) {
            sql += " and FIND_IN_SET('" + dnsName + "', a.dns_name)";
        }
        if (!ListTool.isEmpty(projectIds)) {
            sql += " and a.project_id in (:projectIds) ";
            paramMap.put("projectIds", projectIds);
        }
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
        return this.list(RdsPublicCloudInstance.class, sql, paramMap);
    }

}
