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

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

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

@Repository
public class PartnerDao extends BaseDao<CrmPartner> {

    public CrmPartner findByUserId(String userId) {
        return getByHql("from CrmPartner where userId=:p1", new Parameter(userId));
    }

    public List<Record> listPartner(LayuiPage<Record> page, Map<String, String> map) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("select p.name, date_format(p.create_time, '%Y-%m-%d %H:%i:%s') as create_time, u.login_name");
        sql.line(" ,p.person_in_charge, p.mobile, concat(p.province, p.city, p.area, p.address) as address, p.id");
        sql.line(" ,p.authorized_id from crm_partner p ");
        sql.line(" left join sys_user u ON p.user_id = u.id and u.status <> '1'");
        sql.line(" where p.status = '0' ");
        appendQueryCondition(sql, map);
        sql.line("order by p.create_time desc");
        sql.line("limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
        List<Record> list = Db.find(sql.build(), sql.params());
        for (Record record : list) {
            String authorizedId = record.getStr("authorized_id");
            if (StringUtil.isNotBlank(authorizedId)) {
                String authorizedName = Db.queryStr("SELECT GROUP_CONCAT(s.`code`) FROM crm_project_setting s WHERE s.`id` IN (" + StringUtil.joinInSql(authorizedId.split(",")) + ")");
                record.set("authorizedName", authorizedName);
            }
        }
        return list;
    }

    public long countPartner(Map<String, String> map) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("select count(*) from crm_partner p where p.status = '0'");
        appendQueryCondition(sql, map);
        return Db.queryLong(sql.build(), sql.params());
    }

    public void appendQueryCondition(SqlBuilder sql, Map<String, String> map) {
        if (StringUtil.checkParamsValid(map.get("name"))) {
            sql.line(" and p.name like concat('%', ?, '%')", map.get("name"));
        }
        if (StringUtil.checkParamsValid(map.get("authorizedId"))) {
            String[] ids = map.get("authorizedId").split(",");
            sql.line(" and ( ");
            int index = 0;
            for (String id : ids) {
                if (index > 0) {
                    sql.line(" or ");
                }
                sql.line(" find_in_set(?, p.authorized_id) > 0", id);
                index ++;
            }
            sql.line(")");
        }
        if (StringUtil.checkParamsValid(map.get("personInCharge"))) {
            sql.line(" and p.person_in_charge like concat('%', ?, '%')", map.get("personInCharge"));
        }
        if (StringUtil.checkParamsValid(map.get("mobile"))) {
            sql.line(" and p.mobile = ?", map.get("mobile"));
        }
        if (StringUtil.checkParamsValid(map.get("createTimeMin"))) {
            sql.line("AND p.`create_time` >= CONCAT(? ,' 00:00:00')", map.get("createTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("createTimeMax"))) {
            sql.line("AND p.`create_time` <= CONCAT(? ,' 23:59:59')", map.get("createTimeMax"));
        }
    }

    public Record findByProjectId(String projectId){

        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT * FROM crm_partner p where p.status = '0'")
                .like(" and p.authorized_id like concat('%', ?, '%')",projectId);

        return Db.findFirst(sql.build(),sql.params());
    }

    public List<Record> partnerList(){
        return Db.find("select id,name,person_in_charge from crm_partner where status='0' order by create_time asc");
    }

    public List<CrmPartner> findAllForChoose() {
        return find("from CrmPartner where status = '0'");
    }
    public List<Record> getPartnerByIds(String ids) {
        String[] arr = ids.split(",");
        SqlBuilder builder = new SqlBuilder();
        builder.inst(" SELECT id,name FROM crm_partner where id in ",arr);
        return Db.find(builder.build(), builder.params());
    }

    public Record getTenantFlagById(String id){
        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT tenant_flag AS tenantFlag FROM crm_partner where status = '0' AND id="+id );
        return Db.findFirst(sql.build(),sql.params());
    }

    public List<Record> partnerList(String partnerIds){
        SqlBuilder sb=new SqlBuilder();
        sb.line("select s.id,s.name,s.person_in_charge from crm_partner s where s.status='0'  ");
        if(StringUtil.isNotBlank(partnerIds)){
            sb.inst(" and s.id in ",partnerIds.split(","));
        }
        sb.line("order by s.create_time asc ");
        return Db.find(sb.build(),sb.params());
    }

    public CrmPartner findByName(String name) {
        return getByHql("from CrmPartner where name=:p1", new Parameter(name));
    }

}
