package com.sifang.modules.sunshine.SystemSetting.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmRectificationSet;
import com.sifang.modules.sunshine.SystemSetting.entity.ProductLineSet;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.stereotype.Repository;

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

@Repository
public class ProductLineSetDao extends BaseDao<ProductLineSet> {

    /**
     * 获取设置列表
     */
    public List<Record> findList(Map<String, String> params) {
        SqlBuilder sb = new SqlBuilder();
        sb.line("SELECT rs.id, rs.name, rs.attribute, rs.create_time");
        sb.line("FROM crm_product_line_set rs");
        sb.line("WHERE 1=1");
        queryCondition(sb, params);
        sb.line("ORDER BY rs.create_time DESC");
        return Db.find(sb.build(), sb.params());
    }

    /**
     * 查询变更类型设置详情
     */
    public Record findOneById(String id) {
        SqlBuilder sb = new SqlBuilder();
        sb.line("SELECT rs.id, rs.name, rs.attribute");
        sb.line("FROM crm_product_line_set rs");
        sb.line("WHERE rs.id = ?", id);
        return Db.findFirst(sb.build(), sb.params());
    }

    /**
     * 根据名称查询是否存在
     */
    public long queryCountByName(String name, String id) {
        SqlBuilder sb = new SqlBuilder();
        sb.line("SELECT COUNT(1)");
        sb.line("FROM crm_product_line_set rs");
        sb.line("WHERE rs.name = ?", name);
        if (StringUtil.isNotBlank(id)) {
            sb.line("AND rs.id != ?", id);
        }
        return Db.queryLong(sb.build(), sb.params());
    }

    public void deleteById(String id) {
        Db.deleteById("crm_product_line_set", id);
    }

    /**
     * 查询条件
     */
    private void queryCondition(SqlBuilder sql, Map<String, String> params) {
        if (params == null || params.size() == 0) {
            return;
        }
        if (StringUtil.isNotBlank(params.get("name"))) {
            sql.like("AND name LIKE ?", params.get("name"));
        }
        if (StringUtil.isNotBlank(params.get("startTime"))) {
            sql.line("AND create_time >= ?", params.get("startTime") + " 00:00:00");
        }
        if (StringUtil.isNotBlank(params.get("endTime"))) {
            sql.line("AND create_time <= ?", params.get("endTime") + " 23:59:59");
        }
    }
}
