package com.bocloud.ims.repository.resource;

import com.bocloud.common.model.Pager;
import com.bocloud.common.model.Param;
import com.bocloud.common.utils.Common;
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.ResourceAudit;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository("resourceAuditRepository")
public class ResourceAuditRepository extends BasicGenericDao<ResourceAudit, Long> {

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

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

    public int count(List<Param> params) {
        String sql = "select count(1) from resource_audit v where v.is_deleted = 0";
        sql = QueryBuilder.buildRaw(sql, params, null, "v");
        Map<String, Object> param = QueryBuilder.getParam(params);
        return this.countQuery(sql, param).intValue();
    }

    public List<ResourceAudit> list(int page, int rows, List<Param> params, Map<String, String> sorter) {
        String sql = "select * from resource_audit v where v.is_deleted = 0";
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "v");
        return this.list(ResourceAudit.class, sql);
    }

    public boolean remove(Long id) {
        String sql = "update resource_audit set is_deleted = true where is_deleted = 0 and id = :id";
        Map<String, Object> params = MapTools.simpleMap("id", id);
        return this.execute(sql, params) > 0;
    }

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

    public List<ResourceAudit> listByVendorIdAndType(Long vendorId, String type) {
        String sql = "select * from resource_audit where is_deleted = 0 and vendor_id = :vendorId and type = :type";
        Map<String, Object> params = MapTools.simpleMap("vendorId", vendorId);
        params.put("type", type);
        return this.list(ResourceAudit.class, sql, params);
    }
}
