package com.bocloud.ims.repository.resource;

import com.bocloud.cmp.entity.enums.CloudProvider;
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.IDFactory;
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.DataStore;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

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

/**
 * 数据存储数据处理接口实现
 *
 * @author wangyu
 * @version 1.0
 * @since 2020年5月15日
 */
@Slf4j
@Component("dataStoreRepository")
public class DataStoreRepository extends BasicGenericDao<DataStore, Long> {

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

    @Override
    public void save(DataStore store) throws BoCloudDBException {
        if ("6.8".equals(store.getVersion())) {
            super.save(store);
        } else {
            store.setGuid(IDFactory.instance().uuid());
            super.save(store);
        }
    }

    public List<DataStore> list(int page, int rows, List<Param> params, Map<String, String> sorter) {
        String sql = "select a.*,e.name vdc_name from data_store a " +
                "left join vdc e on a.vdc_id = e.id and e.vendor_id = a.vendor_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(DataStore.class, sql, paramMap);
    }

    public List<DataStore> listByServerIds(List<Long> serverIds) throws BoCloudDBException {
        String sql = "select a.* from data_store a left JOIN store_host s on a.id = s.store_id WHERE a.is_deleted = 0 and s.vhost_id in (:serverIds)";
        Map<String, Object> paramMap = MapTools.simpleMap("serverIds", serverIds);
        return this.list(DataStore.class, sql, paramMap);
    }

    public List<SimpleBean> list(List<Param> params, Map<String, String> sorter) {
        String sql = "SELECT a.id,a.name,a.free_space from (select data_store.az_uuid,data_store.status,data_store.gmt_create,data_store.free_space,data_store.is_deleted,data_store.id,data_store.name,data_store.vendor_id,store_host.vhost_id,store_host.category from data_store left JOIN store_host on data_store.id = store_host.store_id) as 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<DataStore> stores = this.list(DataStore.class, sql, paramMap);
        List<SimpleBean> beans = new ArrayList<SimpleBean>();
        for (DataStore store : stores) {
            beans.add(new SimpleBean(store.getId(), store.getName(), String.valueOf(store.getFreeSpace())));
        }
        return beans;
    }

    public boolean remove(Long id, Long userId) {
        String sql = "update data_store 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 int count(List<Param> params) {
        String sql = "select count(1) from data_store 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 List<DataStore> listByVendorId(Long vendorId) {
        String sql = "select * from data_store  where is_deleted = 0 and sangfor_type='vs'";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        return this.list(DataStore.class, sql, params);
    }

    public int stCount(List<Param> params, Long vendorId, String type) {
        String sql = "select count(1) from data_store a  where a.is_deleted=0";
        if (vendorId != null) {
            sql += " and a.vendor_id = '" + vendorId + "'  ";
        }
        if (type != null) {
            if (type.equalsIgnoreCase("VS")) {
                sql += " and a.type = '" + type.toLowerCase() + "'  ";
            } else {
                sql += " and a.type <> 'vs'  ";
            }
        }
        sql = QueryBuilder.build(sql, params, null, "a");
        Map<String, Object> param = QueryBuilder.getParam(params);
        return this.countQuery(sql, param).intValue();
    }

    public List<DataStore> stList(int page, int rows, List<Param> params, Map<String, String> sorter, Long vendorId, String type) throws BoCloudDBException {
        String sql = "select * from data_store a where a.is_deleted=0";
        if (vendorId != null) {
            sql += " and a.vendor_id = '" + vendorId + "'  ";
        }
        if (type != null) {
            if (type.equalsIgnoreCase("VS")) {
                sql += " and a.type = '" + type.toLowerCase() + "'  ";
            } else {
                sql += " and a.type <> 'vs'  ";
            }
        }
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
        return this.list(DataStore.class, sql);
    }


    public DataStore query(Long id) {
        String sql = "select a.*,b.name vdc_name from data_store a left join vdc b on a.vdc_id = b.id where a.id = :id";
        Map<String, Object> param = MapTools.simpleMap(Common.ID, id);
        List<DataStore> list = this.list(DataStore.class, sql, param);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public boolean removeByVendor(Long vendorId, Long userId) {
        String sql = "update data_store 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 removeByHost(Long hostId, Long userId) {
        String sql = "update data_store set is_deleted = true , gmt_modify = :gmtModify ,mender_id = :menderId where is_deleted = 0 and server_id = :hostId";
        Map<String, Object> params = MapTools.simpleMap("hostId", hostId);
        params.put("menderId", userId);
        params.put("gmtModify", new Date());
        return this.execute(sql, params) > 0;
    }

    public int simpleCount(List<Param> params) {
        String sql = "SELECT count(1) from (select data_store.gmt_create,data_store.is_deleted,data_store.id,data_store.name,data_store.vendor_id,store_host.vhost_id,store_host.category,data_store.status from data_store left JOIN store_host on data_store.id = store_host.store_id) as 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 List<DataStore> listByVdc(Long vdcId) {
        String sql = "select a.* from data_store a where a.is_deleted = 0 and a.vdc_id = :vdcId";
        Map<String, Object> params = MapTools.simpleMap("vdcId", vdcId);
        return this.list(DataStore.class, sql, params);
    }

    public List<DataStore> listByVendor(Long vendorId) {
        String sql = "select a.* from data_store a where a.is_deleted = 0 and a.vendor_id = :vendorId";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        return this.list(DataStore.class, sql, params);
    }

    public DataStore listByVendorAndGuid(Long vendorId,String guid) {
        String sql = "select a.* from data_store a where a.is_deleted = 0 and a.vendor_id = :vendorId and a.guid = :guid";
        Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
        params.put("guid",guid);
        List<DataStore> list = this.list(DataStore.class, sql, params);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

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

    public List<DataStore> listByHost(Long hostId) {
        String sql = "select a.* from data_store a left join store_host b on a.id = b.store_id where a.is_deleted = 0 and b.vhost_id = :hostId and b.category = 'PM'";
        Map<String, Object> params = MapTools.simpleMap("hostId", hostId);
        return this.list(DataStore.class, sql, params);
    }

    public DataStore getByValue(Long vdcId, String storeVal) {
        String sql = "select a.* from data_store a where a.vdc_id = :vdcId and a.store_val = :storeVal";
        Map<String, Object> param = MapTools.simpleMap("vdcId", vdcId);
        param.put("storeVal", storeVal);
        List<DataStore> list = this.list(DataStore.class, sql, param);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public DataStore getByPath(Long vdcId, String path) {
        String sql = "select a.* from data_store a where a.is_deleted = 0 and a.vdc_id = :vdcId and a.path = :path";
        Map<String, Object> param = MapTools.simpleMap("vdcId", vdcId);
        param.put("path", path);
        List<DataStore> list = this.list(DataStore.class, sql, param);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

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

    public boolean unbind(Long id, Long userId) {
        String sql = "update data_store set catalog_id = null , gmt_modify = :gmtModify ,mender_id = :menderId where 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 List<DataStore> listByDataStoreCatalog(Long dataStoreCatalogId) {
        String sql = "select a.* from data_store a where a.is_deleted = 0 and a.catalog_id = :catalogId";
        Map<String, Object> params = MapTools.simpleMap("catalogId", dataStoreCatalogId);
        return this.list(DataStore.class, sql, params);
    }

    public boolean exists(String name, Long vendorId) {
        String sql = "select a.* from data_store a 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);
        return this.list(DataStore.class, sql, params).size() > 0;
    }

    public int countByHost(Long hostId, List<Param> params) {
        String sql = "select count(1) from data_store a left join store_host b on a.id = b.store_id where a.is_deleted = 0 and b.vhost_id = "
                + hostId + " and b.category = 'PM'";
        if (!ListTool.isEmpty(params)) {
            for (int i = 0; i < params.size(); i++) {
                if (params.get(i).getParam().get("hostId") != null) {
                    params.remove(i);
                    i--;
                }
            }
        }
        sql = QueryBuilder.buildRaw(sql, params, null, "a");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        return this.countQuery(sql, paramMap).intValue();
    }

    public List<DataStore> listByHost(Long hostId, List<Param> params, Map<String, String> sorter, Integer page,
                                      Integer rows) {
        String sql = "select a.* from data_store a left join store_host b on a.id = b.store_id where a.is_deleted = 0 and b.vhost_id = "
                + hostId + " and b.category = 'PM'";
        if (!ListTool.isEmpty(params)) {
            for (int i = 0; i < params.size(); i++) {
                if (params.get(i).getParam().get("hostId") != null) {
                    params.remove(i);
                    i--;
                }
            }
        }
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, null), "a");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        return this.list(DataStore.class, sql, paramMap);
    }

    /**
     * 根据名称查询
     *
     * @param name
     * @param vdcId
     * @return
     * @throws Exception
     */

    public DataStore getByName(String name, Long vdcId) {
        String sql = "select a.* from data_store a where a.vdc_id = :vdcId and a.name = :name";
        Map<String, Object> param = MapTools.simpleMap("vdcId", vdcId);
        param.put("name", name);
        List<DataStore> list = this.list(DataStore.class, sql, param);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public DataStore getByServerId(Long serverId, String path) {
        String sql = "select a.* from data_store a where a.server_id = :serverId and a.path = :path";
        Map<String, Object> param = MapTools.simpleMap("serverId", serverId);
        param.put("path", path);
        List<DataStore> list = this.list(DataStore.class, sql, param);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public int countByHost(List<Param> params) {
        String sql = "select count(1) from data_store 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 List<DataStore> listByHost(List<Param> params, Map<String, String> sorter, Integer page, Integer rows) {
        String sql = "select a.*, s.name host_name from data_store a  left join server s on a.server_id = s.id and a.vendor_id = s.vendor_id where a.is_deleted = 0 ";
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, null), "a");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        return this.list(DataStore.class, sql, paramMap);
    }

    public List<DataStore> listByServerId(Long serverId) {
        String sql = "select a.* from data_store a  where a.is_deleted = 0 and a.server_id = :serverId ";
        Map<String, Object> params = MapTools.simpleMap("serverId", serverId);
        return this.list(DataStore.class, sql, params);
    }

    public List<DataStore> listByHost(List<Param> params) {
        String sql = "select a.* from data_store a where a.is_deleted = 0 ";
        sql = QueryBuilder.buildRaw(sql, new Pager(1, Integer.MAX_VALUE, params, null), "a");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        return this.list(DataStore.class, sql, paramMap);
    }



    public int count(List<Param> params, Long vHostId, String category, String clusterName, String vdcName, String cloudType) {
        String sql = "select count(1) from data_store a " +
                "left join vdc e on a.vdc_id = e.id  and e.vendor_id = a.vendor_id " +
                "left join store_host sh on sh.store_id = a.id and sh.vendor_id = a.vendor_id " +
                "left join server s on sh.vhost_id= s.id and s.vendor_id = a.vendor_id " +
                "left join clusters  d on d.id = s.cluster_id and d.vendor_id = a.vendor_id " +
                "where a.is_deleted = 0  ";
        if (!CloudProvider.SANGFOR.toString().equals(cloudType)){
            sql += " and s.name is not null and sh.category = 'PM' ";
        }
        if (null != vHostId && !StringUtils.isNullOrEmpty(category)) {
            sql += " and a.id in ( select sh.store_id from store_host sh where sh.vhost_id = " + vHostId
                    + " and sh.category = '" + category + "' )  ";
        }
        if (!StringUtils.isNullOrEmpty(clusterName)) {
            sql += " and d.name like '%" + clusterName + "%' ";
        }
        if (!StringUtils.isNullOrEmpty(vdcName)) {
            sql += " and e.name like '%" + vdcName + "%' ";
        }
        sql = QueryBuilder.buildRaw(sql, params, null, "a");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        return this.countQuery(sql, paramMap).intValue();
    }

    public List<DataStore> list(Integer page, Integer rows, List<Param> params, Map<String, String> sorter,
                                Long vHostId, String category, String clusterName, String vdcName,String cloudType) {
        String sql = "select a.*,e.name vdc_name,d.name cluster_name from data_store a " +
                "left join vdc e on a.vdc_id = e.id and e.vendor_id = a.vendor_id " +
                "left join store_host sh on sh.store_id = a.id and sh.vendor_id = a.vendor_id " +
                "left join server s on sh.vhost_id= s.id and s.vendor_id = a.vendor_id " +
                "left join clusters  d on d.id = s.cluster_id  and d.vendor_id = a.vendor_id where a.is_deleted = 0 ";
        if (!CloudProvider.SANGFOR.toString().equals(cloudType)){
            sql += " and s.name is not null and sh.category = 'PM' ";
        }
        if (null != vHostId && !StringUtils.isNullOrEmpty(category)) {
            sql += " and a.id in ( select sh.store_id from store_host sh where sh.vhost_id = " + vHostId
                    + " and sh.category = '" + category + "' )  ";
        }
        if (!StringUtils.isNullOrEmpty(clusterName)) {
            sql += " and d.name like '%" + clusterName + "%' ";
        }
        if (!StringUtils.isNullOrEmpty(vdcName)) {
            sql += " and e.name like '%" + vdcName + "%' ";
        }
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        return this.list(DataStore.class, sql, paramMap);
    }

    /**
     * 查询云平台中磁盘落在该存储上的虚拟机台数
     *
     * @author sxp
     * @since 2023/5/29
     */
    public Integer getVmNum(Long vendorId, Long dataStoreId) {
        String sql = " select count(a.id) from cloud_server a " +
                " where is_deleted = 0  " +
                "   and vendor_id = :vendorId " +
                "   and exists(select 'x' from volume b where b.server_id = a.id and b.is_deleted = 0 " +
                "               and b.data_store_id = :dataStoreId) ";
        Map<String, Object> param = MapTools.simpleMap("vendorId", vendorId);
        param.put("dataStoreId", dataStoreId);
        Long vmNum = this.countQuery(sql, param);
        return vmNum.intValue();
    }
}
