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.CrmPlatformEmployee;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Repository
public class CrmPlatformEmpDao extends BaseDao<CrmPlatformEmployee> {

    public CrmPlatformEmployee findByUserId(String userId) {
        return getByHql(" from CrmPlatformEmployee where status = '0' and userId=:p1", new Parameter(userId));
    }

    public List<Record> findByIds(Set<String> empIds) {
        if (CollectionUtils.isEmpty(empIds)) {
            return new ArrayList<>();
        }
        SqlBuilder sb = new SqlBuilder()
                .line("select * from crm_platform_employee")
                .inst("where id in ", new ArrayList<>(empIds))
                .line("and status='0'");
        return Db.find(sb.build(), sb.params());
    }

    public List<Record> findValid() {
        SqlBuilder sb = new SqlBuilder()
                .line("select * from crm_platform_employee")
                .inst("where status='0'");
        return Db.find(sb.build(), sb.params());
    }

    public List<Record> findNotInReviewGroup(String groupId, String partnerId) {
        SqlBuilder sb = new SqlBuilder();
        sb.line("select e.* from crm_platform_employee as e");
        sb.line("where e.status='0' and not exists(");
        sb.line("    select 1 from crm_review_group_member as m where m.employee_id=e.id and m.status='0'");
        sb.line("    and m.group_id!=? and m.partner_id=?", groupId, partnerId);
        sb.line(")");

        return Db.find(sb.build(), sb.params());
    }

    public List<Record> getPlatformEmpList(){
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT e.id,e.name FROM crm_platform_employee e WHERE e.status='0' ORDER BY create_time ASC ");
        return Db.find(sb.toString());
    }

    public List<Record> findNotInReviewGroup(String groupName) {
        SqlBuilder sb = new SqlBuilder();
        sb.line("select DISTINCT e.* from crm_review_group_member m ");
        sb.line("left join crm_platform_employee e on e.user_id = m.user_id ");
        sb.line("where m.group_id in (select id from crm_review_group where name like '%" +groupName+"%')");
        sb.line("and m.status = '0' and e.status='0' ");
        return Db.find(sb.build());
    }
}
