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

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
import com.sifang.modules.sunshine.SystemSetting.entity.ProjectPcd;
import com.sifang.modules.sunshine.SystemSetting.entity.TraderPcd;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
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;
import java.util.Objects;

/**
 * @author hongzq
 */
@Repository
public class ProjectSettingDao extends BaseDao<CrmProjectSetting> {

    public List<Record> selectProjectSettings(LayuiPage<Record> page,Map<String, String> map){
        SqlBuilder builder = new SqlBuilder();
        builder.line("select s.id, s.code, s.name, s.status, s.create_time,s.install_mode_name,s.install_mode_id,s.management_type,s.filing_type ")
                .line(" ,l.attribute,l.name as productLineName,s.epc_price,s.pay_cycle,c.name as companyName ,p.name as partnerName")
                .line(" from crm_project_setting s ")
                .line(" left join crm_product_line_set l on l.id=s.product_line_id ")
                .line(" left join  crm_project_company_settings c on c.id=s.project_company_id  ")
                .line(" left join crm_partner p on p.id = s.management ")
                .line(" where s.status <> '1' ");
        getConditionMap(map,builder);
        builder.line(" order by s.create_time desc ,code asc ,id asc ");
        if(page != null){
            builder.limit(page.getPage(), page.getLimit());
        }
        return Db.find(builder.build(), builder.params());
    }

    public Long countProjectSettings(Map<String, String> map){
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(s.id) ")
                .line("from crm_project_setting s where s.status <> '1'");
        getConditionMap(map,builder);
        return Db.queryLong(builder.build(), builder.params());
    }

    public Record getProjectSettingDetail(String projectId){
        StringBuffer sb=new StringBuffer();
        sb.append(" select s.id, s.code, s.name, s.status,s.install_mode_name,s.install_mode_id,s.management_type  as managementType,s.filing_type,s.state_authorized_flag ");
        sb.append(" ,l.attribute,l.name as productLineName,s.epc_price,s.pay_cycle,s.product_line_id,s.project_company_id,assembly_specs,s.management ");
        sb.append(" ,s.connect_manage_flag,s.buy_insurance_flag,s.insurance_id,s.management,s.epc_company_id  ");
        sb.append(" from crm_project_setting s  ");
        sb.append(" left join crm_product_line_set l on l.id=s.product_line_id ");
        sb.append(" where s.id=?  ");
        return Db.findFirst(sb.toString(),projectId);
    }

    public void getConditionMap(Map<String, String> map, SqlBuilder sf) {
        if (StringUtil.isNotBlank(map.get("name"))) {
            sf.like(" AND s.name LIKE ? ", map.get("name"));
        }
        if (StringUtil.isNotBlank(map.get("projectCompanyId"))) {
            sf.line("and s.project_company_id = ?", map.get("projectCompanyId"));
        }
        if (StringUtil.isNotBlank(map.get("productLineId"))) {
            sf.line("and s.product_line_id = ?", map.get("productLineId"));
        }
        if (StringUtil.isNotBlank(map.get("ids"))) {
            sf.inst("and s.id not in ", map.get("ids").split(","));
        }
        if (StringUtil.isNotBlank(map.get("proIds"))) {
            sf.inst("and s.id  in ", map.get("proIds").split(","));
        }
        if (StringUtil.isNotBlank(map.get("code"))) {
            sf.like(" AND s.code LIKE ? ", map.get("code"));
        }
        if (StringUtil.isNotBlank(map.get("status"))) {
            sf.line("and s.status = ?", map.get("status"));
        }
        if (StringUtil.isNotBlank(map.get("partnerId"))){
            sf.line(" and s.management = ? ",map.get("partnerId"));
        }
    }

    public Long countExistsName(String name, String excludeId){
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(*) ")
                .line("from crm_project_setting")
                .line("where status='0'")
                .line("and name=? ", name);
        if(StrKit.notBlank(excludeId)){
            builder.line("and id != ?", excludeId);
        }
        return Db.queryLong(builder.build(), builder.params());
    }

    public Long countExistsCode(String code, String excludeId){
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(*) ")
                .line("from crm_project_setting")
                .line("where status='0'")
                .line("and code=? ", code);
        if(StrKit.notBlank(excludeId)){
            builder.line("and id != ?", excludeId);
        }
        return Db.queryLong(builder.build(), builder.params());
    }

    public List<Record> getProductLineList(){
        StringBuffer sb=new StringBuffer();
        sb.append(" SELECT s.id,s.name,s.attribute FROM `crm_product_line_set` s  ");
        return Db.find(sb.toString());
    }


    public Record getProject(String projectId){
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT p.id,p.code,p.name,p.pay_cycle,p.product_line_id,p.project_company_id,p.epc_price,p.management_type,p.filing_type");
        builder.line(",pc.name AS companyName,pl.name AS lineName,pl.attribute,p.assembly_specs,p.management ");
        builder.line("FROM crm_project_setting p");
        builder.line("LEFT JOIN crm_project_company_settings pc ON pc.id = p.project_company_id");
        builder.line("LEFT JOIN crm_product_line_set pl ON pl.id = p.product_line_id");
        builder.line("WHERE p.status='0' AND p.id=?",projectId);
        return Db.findFirst(builder.build(),builder.params());
    }

    public Record getProjects(String projectId){
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT p.id,p.code,p.name,p.pay_cycle,p.product_line_id,p.project_company_id,p.epc_price,p.management_type,p.filing_type");
        builder.line(",pc.name AS companyName,pl.name AS lineName,pl.attribute,p.assembly_specs,p.management ");
        builder.line("FROM crm_project_setting p");
        builder.line("LEFT JOIN crm_project_company_settings pc ON pc.id = p.project_company_id");
        builder.line("LEFT JOIN crm_product_line_set pl ON pl.id = p.product_line_id");
        builder.line("WHERE p.status='0' AND p.management=?",projectId);
        return Db.findFirst(builder.build(),builder.params());
    }

    /**
     * 录单获取产品信息
     */
    public Record findProjectForTranscription(String projectId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT p.id,p.code,p.name,p.pay_cycle,p.filing_type,p.management,pc.name AS companyName,");
        builder.line("p.product_line_id AS productLineId");
        builder.line("FROM crm_project_setting p");
        builder.line("LEFT JOIN crm_project_company_settings pc ON pc.id = p.project_company_id");
        builder.line("WHERE p.id = ?", projectId);
        return Db.findFirst(builder.build(), builder.params());
    }


    public Record finProjectSettingById(String projectId){
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT p.project_company_id");
        builder.line("FROM crm_project_setting p");
        builder.line("WHERE id = ?",projectId);
        return Db.findFirst(builder.build(), builder.params());
    }

    public Record findProjectById(String id){
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT p.id,p.code,p.name,p.status,");
        builder.line("p.filing_type AS filingType,pl.name AS productLineName");
        builder.line("FROM crm_project_setting p");
        builder.line("LEFT JOIN crm_product_line_set pl ON pl.id = p.product_line_id");
        builder.line("WHERE p.id = ?", id);
        return Db.findFirst(builder.build(),builder.params());
    }

    public List<CrmProjectSetting> getProjectSettingList(){
        return find("FROM CrmProjectSetting WHERE status = '0' ");
    }

    public List<Record> getProjectList(){
        StringBuffer sb=new StringBuffer();
        sb.append(" select s.id,s.name,s.code from crm_project_setting s ");
        sb.append(" where s.status='0' ");
        return Db.find(sb.toString());
    }


    /**
     * 根据项目Id获取授权区域
     * @param proId
     * @return
     */
    public List<Record> getProjectAreaListByPId(String proId){
        SqlBuilder sql=new SqlBuilder();
        sql.line(" SELECT province ,city,area FROM `crm_project_pcd` where project_id = ? " ,proId);
        return Db.find(sql.build(), sql.params());
    }


    /**
     * 根据地区获取项目信息
     * @param province
     * @return
     */
    public List<Record> getProjectInfoByArea(String province){
        SqlBuilder sql=new SqlBuilder();
        sql.line(" SELECT * FROM crm_project_setting WHERE `status` = '0' ");
        if (StringUtil.isNotBlank(province)){
            sql.inst(" and id in (SELECT project_id from crm_project_pcd WHERE province in ",province.split(","));
            sql.line(" )");
        }
        return Db.find(sql.build(), sql.params());
    }

    public boolean checkAuth(String projectId, String province, String city, String area) {
        List<ProjectPcd> pcdList = find("from ProjectPcd where projectId = :p1 and province = :p2", new Parameter(projectId, province));
        if (pcdList == null || pcdList.size() <= 0) {
            return false;
        }
        for (ProjectPcd pcd : pcdList) {
            if (StringUtil.isBlank(pcd.getCity())) {
                return true;
            } else if (Objects.equals(pcd.getCity(), city)) {
                if (StringUtil.isBlank(pcd.getArea())
                        || Objects.equals(pcd.getArea(), area)) {
                    return true;
                }
            }
        }
        return false;
    }

    public List<Record> getEntryProjectByEntryId(String entryId){
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT p.id as projectId,p.code as projectCode,p.name as projectName,p.status,");
        builder.line("p.filing_type as filingType,ep.roof_type as roofType,p.pay_cycle AS payCycle,ep.entry_id as entryId");
        builder.line("FROM crm_project_setting p");
        builder.line("LEFT JOIN crm_customer_entry_project ep ON ep.project_id = p.id");
        builder.line("WHERE ep.entry_id = ?", entryId);
        builder.line(" order by ep.project_id  asc ");
        return Db.find(builder.build(), builder.params());
    }


}
