package com.sifang.modules.customer.dao;

import com.google.common.collect.Maps;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.form.AddEntryReq;
import com.sifang.modules.site.siteInfo.service.SiteEmployeeService;
import com.sifang.modules.smallprogram.stategrid.utils.StateGridConstants;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import com.sifang.modules.sys.util.SqlUtils;
import com.sifang.modules.taskdispatch.util.ItemDispatchUtil;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.*;

@Repository
public class CustomerEntryDao extends BaseDao<CustomerEntry> {

    @Autowired
    UserDao userDao;

    @Autowired
    SiteEmployeeService siteEmployeeService;

    Logger logger = LoggerFactory.getLogger(getClass());


    public List<Record> getInputPieceInProgress(String partnerId) {
        return Db.find(" select a.id from crm_customer_entry a where a.apply_status in ('5','14') and a.status <> 'b'  and a.partner_id = ?", partnerId);
    }
    public CustomerEntry findCustomerEntryById(String powerStationCode) {

        return getByHql(" from CustomerEntry where powerStationCode =:p1", new Parameter(powerStationCode));
    }

    //根据身份证号，找预审待审批的数据
    public List<CustomerEntry> getCustomerEntryByIdCode(String idCode, String partnerId) {
        return find(" from CustomerEntry  WHERE status='0' AND credit IN ('2','3') AND idCode=:p1 AND partnerId=:p2",
                new Parameter(idCode, partnerId));
    }


    //查询华融待预审数据
    public List<Record> getCustomerEntryBypartnerId( String partnerId) {
        return Db.find(" select a.id from crm_customer_entry a WHERE a.status != 'b' AND a.credit IN ('2','3')  AND a.partner_id=?",
                partnerId);
    }

    public List<Record> getCustomerEntryInfoByIdCode(String keywords, String tenantType) {
        SqlBuilder sb = new SqlBuilder();
        sb.line(" select a.* ");
        sb.line(" FROM crm_customer_entry_tenant a");
        sb.line(" where a.status = '1' and a.yx_flag = '1' ");
        if ("2".equals(tenantType)) { // 单位客户校验
            sb.line(" and a.tenant_type = '2' and a.regno = ?", keywords);
        } else {
            sb.line(" and a.tenant_type = ? and a.id_code = ?", tenantType, keywords);
        }
        sb.line(" ORDER BY a.create_time desc LIMIT 0,1 ");
        return Db.find(sb.build(), sb.params());
    }


    public List<Record> selectTenantNameByIds(List<String> ids) {
        SqlBuilder sb = new SqlBuilder()
                .line("select id, tenant_name from crm_customer_entry")
                .inst("where id in", ids);
        return Db.find(sb.build(), sb.params());
    }


    //AND credit IN ('2','3')
    public CustomerEntry getInfoByPowerGenerationNo(String powerGenerationNo){
        return getByHql(" from CustomerEntry  WHERE status <>'b' and  generator_no=:p1 ", new Parameter(powerGenerationNo));
    }


    public List<Record> getCustomerList(String port, LayuiPage<Record> page, Map<String, String> map, User user) {
        StringBuilder sf = new StringBuilder();
        String sqlMap = getOrderMap(map, user);
        sf.append(" SELECT a.*, a.project_code AS projectCode, a.project_name AS projectName,a.trader_name AS distributorName,a.trader_tel AS distributorMobile,m.name AS flag_name,m.type AS flag_type ,a.credit,a.credit_dsc,a.apply_status,f.status AS archivesStatus ");
        sf.append(" ,a.create_trader_name as createTraderName,n.assign_audit_user_id,k.assign_audit_user_id as archive_audit_user_id");
        sf.append(" FROM crm_customer_entry a ");
        sf.append(" LEFT JOIN crm_order_mark_settings m ON m.`id`=a.`flag` AND m.status='0' and m.use_type='2' ");
        sf.append(" LEFT JOIN crm_customer_entry_org_files f ON f.entry_id = a.id");
        sf.append(" left join crm_item_manage as n on n.application_id=a.id and n.status='1' and n.form_key='91'");
        sf.append(" left join crm_item_manage as k on k.application_id=a.id and k.status='1' and k.form_key='92'");
        //  sf.append(" LEFT JOIN crm_project_setting s ON s.id=a.project_id ");
        //  sf.append(" LEFT JOIN crm_project_install_way w ON w.id=a.method ");
        //  sf.append(" LEFT JOIN crm_trader t ON t.id=a.distributor_id ");
        if ("PC".equals(port)) {
            sf.append(" WHERE (a.status in ('1','2','h') or (a.status = '0' and a.design_audit_flag in ('1','3','a')) ) ");
        } else {
            sf.append(" WHERE a.status = '1' ");
        }
        sf.append(sqlMap);
        sf.append(" order by create_time desc ");
        if (page != null) {
            sf.append(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
            Long count = getCount(port, sqlMap);
            page.setCount(count);
        }

        List<Record> records = Db.find(sf.toString());
        ItemDispatchUtil.setReviewFlag(records, true);
        return records;
    }

    public long getCount(String port, String sqlMap) {
        StringBuilder sf = new StringBuilder();
        sf.append(" SELECT count(1)  ");
        sf.append(" FROM crm_customer_entry a ");
        sf.append(" LEFT JOIN crm_order_mark_settings m ON m.`id`=a.`flag` AND m.status='0' and m.use_type='2' ");
        sf.append(" LEFT JOIN crm_customer_entry_org_files f ON f.entry_id = a.id");
        // sf.append(" LEFT JOIN crm_project_setting s ON s.id=a.project_id ");
        // sf.append(" LEFT JOIN crm_project_install_way w ON w.id=a.method ");
        // sf.append(" LEFT JOIN crm_trader t ON t.id=a.distributor_id ");
        if ("PC".equals(port)) {
            sf.append(" WHERE (a.status in ('1','2','h') or (a.status = '0' and a.design_audit_flag in ('1','3','a')) ) ");
        } else {
            sf.append(" WHERE a.status = '1' ");
        }
        sf.append(sqlMap);
        return Db.queryLong(sf.toString());
    }

    public List<Record> getGdtCustomerList(LayuiPage<Record> page, Map<String, String> map, User user) {
        StringBuilder sf = new StringBuilder();
        String sqlMap = getOrderMap(map, user);
        sf.append(" SELECT a.*, a.project_code AS projectCode, a.project_name AS projectName,a.trader_name AS distributorName,a.trader_tel AS distributorMobile,m.name AS flag_name,m.type AS flag_type ,a.credit,a.credit_dsc,a.apply_status ");
        sf.append(" FROM crm_customer_entry a ");
        sf.append(" LEFT JOIN crm_order_mark_settings m ON m.`id`=a.`flag` AND m.status='0' and m.use_type='2' ");
        sf.append(" WHERE a.status !='c' ");
        sf.append(sqlMap);
        sf.append(" order by create_time desc ");
        if (page != null) {
            sf.append(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
            Long count = getGdtCount(sqlMap);
            page.setCount(count);
        }

        return Db.find(sf.toString());
    }

    public long getGdtCount(String sqlMap) {
        StringBuilder sf = new StringBuilder();
        sf.append(" SELECT count(*)  ");
        sf.append(" FROM crm_customer_entry a ");
        sf.append(" LEFT JOIN crm_order_mark_settings m ON m.`id`=a.`flag` AND m.status='0' and m.use_type='2' ");
        sf.append(" WHERE a.status !='c' ");
        sf.append(sqlMap);
        return Db.queryLong(sf.toString());
    }


    public List<Record> getJjShCustomerList(LayuiPage<Record> page, Map<String, String> map, User user) {
        StringBuilder sf = new StringBuilder();
        String sqlMap = getOrderMap(map, user);
        sf.append(" SELECT i.input_piece_id AS inputPieceId,a.*, a.project_code AS projectCode, a.project_name AS projectName,a.trader_name AS distributorName,a.trader_tel AS distributorMobile,m.name AS flag_name,m.type AS flag_type ,a.credit,a.credit_dsc,a.apply_status ");
        sf.append(" ,concat(a.province, a.city, a.area, a.address) as address,a.filing_type,pa.tenant_flag tenantFlag,s.name as companyName,i.partners_contract_number,a.actual_capacity*a.epc_price AS amount ,a.is_history as isHistory,a.apply_back_time FROM crm_customer_entry a ");
        sf.append(" LEFT JOIN crm_order_mark_settings m ON m.`id`=a.`flag` AND m.status='0' and m.use_type='2' ");
        sf.append(" LEFT JOIN `crm_project_company_settings` s on s.company_code=a.management_type ");
        sf.append(" LEFT JOIN `crm_customer_incoming_application` i on i.entry_id=a.id and i.if_delete<>'1' ");
        sf.append(" left join crm_partner pa on pa.id = a.partner_id");
        sf.append(" WHERE (a.apply_status >=1 or i.id is not null) and a.status<>'b' ");
        sf.append(sqlMap);
        sf.append(" order by a.create_time desc ");
        if (page != null) {
            sf.append(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
            Long count = getJjShCount(sqlMap);
            page.setCount(count);
        }

        logger.info("getJjShCustomerList小程序获取项目信息sql {}：", sf.toString());
        return Db.find(sf.toString());
    }

    public long getJjShCount(String sqlMap) {
        StringBuilder sf = new StringBuilder();
        sf.append(" SELECT count(*)  ");
        sf.append(" FROM crm_customer_entry a ");
        sf.append(" LEFT JOIN crm_order_mark_settings m ON m.`id`=a.`flag` AND m.status='0' and m.use_type='2' ");
        sf.append(" LEFT JOIN `crm_customer_incoming_application` i on i.entry_id=a.id and i.if_delete<>'1' ");
        sf.append(" WHERE (a.apply_status >=1 or i.id is not null)  and a.status<>'b'  ");
        sf.append(sqlMap);
        return Db.queryLong(sf.toString());
    }

    public List<Record> getMaterialByCustomerEntry(Map<String, String> map, User user) {
        StringBuilder sf = new StringBuilder();
        sf.append(" SELECT any_value(e.code) as code,any_value(e.name) as name,any_value(e.spec) as spec,any_value(e.unit)as unit,sum(e.amount) as amount,any_value(component_spec) as component_spec FROM crm_customer_entry a  ");
        sf.append(" LEFT JOIN crm_plan_material_entry e ON e.entry_id=a.id  ");
        sf.append(" WHERE  e.amount>0 ");
        sf.append(getOrderMap(map, user));
        sf.append(" GROUP BY e.code ");
        return Db.find(sf.toString());
    }

    public Record getMaterialcomponentCount(Map<String, String> map, User user) {
        StringBuilder sf = new StringBuilder();
        sf.append(" SELECT sum(component_count) component_count FROM crm_customer_entry a  ");
        sf.append(" LEFT JOIN crm_plan_material_entry e ON e.entry_id=a.id  ");
        sf.append(" WHERE  e.amount>0 ");
        sf.append(getOrderMap(map, user));
        return Db.findFirst(sf.toString());
    }


    public List<Record> getCustomerEntryByScheme(Map<String, String> map) {
        StringBuilder sf = new StringBuilder();
        sf.append(" SELECT a.*,p.name as planName,p.code as planCode,p.type FROM crm_customer_entry a  LEFT JOIN crm_plan p ON p.id=a.scheme_id  ");
        sf.append(" WHERE  1=1  ");
        sf.append(getOrderMap(map, null));
        sf.append(" GROUP BY a.scheme_id  ");
        return Db.find(sf.toString());
    }

    public String getOrderMap(Map<String, String> map, User user) {
        StringBuilder sf = new StringBuilder();
        if (StringUtil.equalsAny(user.getUserType(), UserConstants.TYPE_TRADER, User.USER_TYPE_ADVISOR)) {
            Record record = CrmUtils.getUserTrader(user.getUserType(), user.getId());
            String traderId = record.getStr("id");
            String type = record.getStr("type");
            if (UserConstants.TYPE_TRADER.equals(user.getUserType())) { //代理商
                if ("1".equals(type)) {  // 1.一级代理商 2.二级代理商
                    sf.append(" and a.distributor_id ='" + traderId + "'");
                } else {  //二级代理商
                    if (UserConstants.TYPE_TRADER.equals(user.getUserType())) {
                        //代理商只能查看自己的
                        sf.append(" and a.create_trader_id ='" + traderId + "'");
                    }
                }
            } else { //代理商人员
                String dataAuthority = record.getStr("data_authority");
                if ("1".equals(type) && UserConstants.DATA_AUTHORITY_ALL.equals(dataAuthority)) {
                    sf.append(" and a.distributor_id = '" + traderId + "'");
                } else {
                    sf.append(" and a.create_trader_id ='" + traderId + "'");
                    if (StringUtil.isBlank(dataAuthority) || UserConstants.DATA_AUTHORITY_ONLY.equals(dataAuthority)) {  //仅看自己的
                        sf.append(" and (a.create_by ='" + user.getId() + "' ");
                        sf.append(" or (a.dispatch_status = '1' and find_in_set('" + map.get("engineerId") + "', a.engineer_id)))");
                    }
                }

            }
        }
        long checkRo = userDao.isDefaultPlatRole(user.getId());
        if (checkRo > 0) {
            List<Record> employeeRole = siteEmployeeService.findEmployeeByUserId(user.getId());
            List<String> provinceList = appendColumns(employeeRole, "provices");
            List<String> cityList = appendColumns(employeeRole, "city");
            List<String> numberList = appendColumns(employeeRole, "project_number");
            List<String> traderList = appendColumns(employeeRole, "trader_id");
            logger.info("appendConditions :  count :{}  ,  employeeRole :{}  ，provinceList:{},cityList:{},numberList:{}", checkRo, employeeRole, provinceList, cityList, numberList);
            if (!provinceList.isEmpty()) {
                sf.append(" and a.province in (" + StringUtil.joinInSql(provinceList) + ")");
            }
            if (!cityList.isEmpty()) {
                sf.append(" and a.city in (" + StringUtil.joinInSql(cityList) + ")");
            }
            if (!numberList.isEmpty()) {
                sf.append(" and a.project_id in (" + StringUtil.joinInSql(numberList) + ")");
            }
            if (!traderList.isEmpty()) {
                if (map.get("traderId") != null && !map.get("traderId").isEmpty()) {
                    sf.append(" and a.distributor_id in ( '" + map.get("traderId") + "')");
                } else {
                    sf.append(" and a.distributor_id in (" + StringUtil.joinInSql(traderList) + ")");
                }
            } else {
                if (StringUtil.checkParamsValid(map.get("traderId"))) {
                    sf.append(" and a.distributor_id = '" + map.get("traderId") + "'");
                }
            }
        }
        if (map == null) {
            return "";
        }

        if (StringUtil.checkParamsValid(map.get("ids"))) {
            sf.append("and a.id in(" + StringUtil.joinInSql(map.get("ids").split(",")) + ")");
        }

        if (StringUtil.checkParamsValid(map.get("searchParameter"))) {
            sf.append("and (a.tenant_name like concat('%'" + map.get("searchParameter") + "'%') or a.mobile ='" + map.get("searchParameter") + "' )");
        }

        if (StringUtil.checkParamsValid(map.get("archivesStatus"))) {
            sf.append(" and f.status in(" + StringUtil.joinInSql(map.get("archivesStatus").split(",")) + ")");
        }

        if (StringUtil.checkParamsValid(map.get("id"))) {
            sf.append(" and a.id = '" + map.get("id") + "'");
        }
        if (StringUtil.checkParamsValid(map.get("tenantAddress"))) {
            String location = map.get("tenantAddress");
            sf.append(" and concat_ws('',a.province,a.city,a.area,a.address) like '%" + location.trim() + "%'");
        }
//        if (StringUtil.checkParamsValid(map.get("method"))) {
//            sf.append(" and a.method = '" + map.get("method") + "'");
//        }
        if (StringUtil.checkParamsValid(map.get("status")) && !"f".equals(map.get("status"))) {
            sf.append(" and a.status in(" + StringUtil.joinInSql(map.get("status").split(",")) + ")");
        }
        if (StringUtil.checkParamsValid(map.get("designAuditFlag"))) {
            String designAuditFlag = map.get("designAuditFlag");
            if("5".equals(designAuditFlag)){
                sf.append("and  ( a.design_audit_flag = '5' or a.zs_result = '4' )");
            }else {
                sf.append("and a.design_audit_flag = '" + designAuditFlag + "' ");
            }

        }
        //
//        if (StringUtil.checkParamsValid(map.get("installWay"))) {
//            sf.append("and a.method='"+map.get("installWay")+"'");
//        }
        if (StringUtil.checkParamsValid(map.get("partner"))) {
            sf.append("and a.partner_id ='" + map.get("partner") + "'");
        }
        if (StringUtil.checkParamsValid(map.get("schemeType"))) {
            sf.append("and a.scheme_type ='" + map.get("schemeType") + "'");
        }
        if (StringUtil.checkParamsValid(map.get("applyChange"))) {
            sf.append("and a.apply_change ='" + map.get("applyChange") + "'");
        }
        //标记类型
        if (StringUtil.checkParamsValid(map.get("flag"))) {
            sf.append("and a.flag in(" + StringUtil.joinInSql(map.get("flag").split(",")) + ")");
        }
        if (StringUtil.checkParamsValid(map.get("projectId"))) {
            sf.append(" and a.project_id = '" + map.get("projectId") + "'");
        }
        if (StringUtil.checkParamsValid(map.get("projectName"))) {
            sf.append(" and a.project_name like '%" + map.get("projectName") + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("distributorId"))) {
            sf.append(" and a.distributor_id = '" + map.get("distributorId") + "'");
        }
        if (StringUtil.checkParamsValid(map.get("tenantName"))) {
            sf.append(" and a.tenant_name like '%" + map.get("tenantName") + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("roofType"))) {
            sf.append(" and a.roof_type = '" + map.get("roofType") + "'");
        }
        //设计审核人
        if (StringUtil.checkParamsValid(map.get("examineName"))) {
            sf.append(" and a.examine_name like  '%" + map.get("examineName") + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("plan"))) {
            sf.append("and a.scheme_id='" + map.get("plan") + "'");
        }
        if (StringUtil.checkParamsValid(map.get("powerStationCode"))) {
            sf.append(" and a.power_station_code like '%" + map.get("powerStationCode") + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("jjPowerStationCode"))) {
            sf.append(" and i.partners_contract_number like '%" + map.get("jjPowerStationCode") + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("inputPieceId"))) {
            sf.append(" and i.input_piece_id like '%" + map.get("inputPieceId") + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("mobileTel"))) {
            sf.append(" and a.mobile like '%" + map.get("mobileTel") + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("traderMobile"))) {
            sf.append(" and a.trader_tel = '" + map.get("traderMobile") + "'");
        }

        if (StringUtil.checkParamsValid(map.get("remarks"))) {
            sf.append(" and a.remarks like '%" + map.get("remarks") + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("customerAddress"))) {
            sf.append(" and a.address like '%" + map.get("customerAddress") + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("projectNumber"))) {
            sf.append(" and a.project_id in (" + StringUtil.joinInSql(map.get("projectNumber").split(",")) + ")");
        }
        if (StringUtil.checkParamsValid(map.get("province"))) {
            sf.append(" and a.province in (" + StringUtil.joinInSql(map.get("province").split(",")) + ")");
        }
        if (StringUtil.checkParamsValid(map.get("city"))) {
            sf.append(" and a.city in (" + StringUtil.joinInSql(map.get("city").split(",")) + ")");
        }

        if (StringUtil.checkParamsValid(map.get("area"))) {
            sf.append("and a.area ='" + map.get("area") + "' ");
        }
        if (StringUtil.checkParamsValid(map.get("address"))) {
           // sf.append("and a.address ='" + map.get("address") + "' ");
            sf.append(" and a.address like '%" + map.get("address") + "%'");

        }

        if (StringUtil.checkParamsValid(map.get("traderIds"))) {
            sf.append(" and a.distributor_id in (" + StringUtil.joinInSql(map.get("traderIds").split(",")) + ")");
        }
        if (StringUtil.checkParamsValid(map.get("retrial"))) {
            sf.append("and a.retrial in " + StringUtil.joinInSql(map.get("retrial").split(",")) + ")");
        }

        if (StringUtil.checkParamsValid(map.get("whetherToPay"))) {
            sf.append("and a.whether_to_pay ='" + map.get("whetherToPay") + "'");
        }
        //发电户号
        if (StringUtil.checkParamsValid(map.get("generatorNo"))) {
            sf.append("and a.generator_no ='" + map.get("generatorNo") + "'");
        }

        if (StringUtil.checkParamsValid(map.get("examineRemarks"))) {
            sf.append(" and a.examine_remarks like '%" + map.get("examineRemarks") + "%'");
        }
        if (StringUtil.checkParamsValid(map.get("createTimeMin"))) {
            sf.append(" and a.create_time >= concat('" + map.get("createTimeMin") + "', ' 00:00:00')");
        }
        if (StringUtil.checkParamsValid(map.get("createTimeMax"))) {
            sf.append(" and a.create_time <= concat('" + map.get("createTimeMax") + "', ' 23:59:59')");
        }
        if (StringUtil.checkParamsValid(map.get("examineTimeMin"))) {
            sf.append(" and a.examine_time >= concat('" + map.get("examineTimeMin") + "', ' 00:00:00')");
        }
        if (StringUtil.checkParamsValid(map.get("examineTimeMax"))) {
            sf.append(" and a.examine_time <= concat('" + map.get("examineTimeMax") + "', ' 23:59:59')");
        }
        if (StringUtil.checkParamsValid(map.get("indocTimeMin"))) {
            sf.append(" and a.indoc_time >= concat('" + map.get("indocTimeMin") + "', ' 00:00:00')");
        }
        if (StringUtil.checkParamsValid(map.get("indocTimeMax"))) {
            sf.append(" and a.indoc_time <= concat('" + map.get("indocTimeMax") + "', ' 23:59:59')");
        }
        if (StringUtil.checkParamsValid(map.get("receiveTimeMin"))) {
            sf.append("and a.receive_time >=  concat('" + map.get("receiveTimeMin") + "', ' 00:00:00')");
        }
        if (StringUtil.checkParamsValid(map.get("receiveTimeMax"))) {
            sf.append("and a.receive_time <= concat('" + map.get("receiveTimeMax") + "', ' 23:59:59')");
        }
        if (StringUtil.checkParamsValid(map.get("installTimeMin"))) {
            sf.append("and a.install_time >= concat('" + map.get("installTimeMin") + "', ' 00:00:00')");
        }
        if (StringUtil.checkParamsValid(map.get("installTimeMax"))) {
            sf.append("and a.install_time <= concat('" + map.get("installTimeMax") + "', ' 23:59:59')");
        }
        if (StringUtil.checkParamsValid(map.get("mergeTimeMin"))) {
            sf.append("and a.merge_time >= concat('" + map.get("mergeTimeMin") + "', ' 00:00:00')");
        }
        if (StringUtil.checkParamsValid(map.get("mergeTimeMax"))) {
            sf.append("and a.merge_time <= concat('" + map.get("mergeTimeMax") + "', ' 23:59:59')");
        }
        if (StringUtil.checkParamsValid(map.get("checkAcceptTimeMin"))) {
            sf.append("and a.check_accept_time >= concat('" + map.get("checkAcceptTimeMin") + "', ' 00:00:00')");
        }
        if (StringUtil.checkParamsValid(map.get("checkAcceptTimeMax"))) {
            sf.append("and a.check_accept_time <= concat('" + map.get("checkAcceptTimeMax") + "', ' 23:59:59')");
        }
        if (StringUtil.checkParamsValid(map.get("deliverTimeMin"))) {
            sf.append("and a.deliver_time >= concat('" + map.get("deliverTimeMin") + "', ' 00:00:00')");
        }
        if (StringUtil.checkParamsValid(map.get("deliverTimeMax"))) {
            sf.append("and a.deliver_time <= concat('" + map.get("deliverTimeMax") + "', ' 23:59:59')");
        }
        if (StringUtil.checkParamsValid(map.get("orderTimeMin"))) {
            sf.append("and a.order_time >= concat('" + map.get("orderTimeMin") + "', ' 00:00:00')");
        }
        if (StringUtil.checkParamsValid(map.get("orderTimeMax"))) {
            sf.append("and a.order_time <= concat('" + map.get("orderTimeMax") + "', ' 23:59:59')");
        }
        if (StringUtil.checkParamsValid(map.get("credit"))) {
            sf.append(" and a.credit = '" + map.get("credit") + "'");
        }
        if (StringUtil.checkParamsValid(map.get("applyStatus"))) {
            sf.append(" and a.apply_status ='" + map.get("applyStatus") + "'");

        }
        if (StringUtil.checkParamsValid(map.get("authorization"))) {
            sf.append("and e.authorization in (" + StringUtil.joinInSql(map.get("authorization").split(",")) + ")");
        }
        if (StringUtil.checkParamsValid(map.get("secCardStatus"))) {
            sf.append("and e.sec_card_status in (" + StringUtil.joinInSql(map.get("secCardStatus").split(",")) + ")");
        }
        if (StringUtil.checkParamsValid(map.get("signStatus"))) {
            sf.append("and e.sign_status in (" + StringUtil.joinInSql(map.get("signStatus").split(",")) + ")");
        }
        if (StringUtil.checkParamsValid(map.get("twoTrader"))) {
            sf.append(" and a.create_trader_id ='" + map.get("twoTrader") + "'");

        }
        return sf.toString();
    }


    public Record getCustimerByDisId(String distributor_id) {
        StringBuilder sf = new StringBuilder();
        sf.append("select * from crm_customer_entry where distributor_id =? order by create_time desc LIMIT 1 ");

        return Db.findFirst(sf.toString(), distributor_id);
    }

    public List<Record> selectWaitOrders(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select DISTINCT e.id,e.partner_id patnerId, pa.tenant_flag tenantFlag, e.power_station_code, e.scheme_id,e.scheme_type_id,e.scheme_type_name ,e.scheme_name as planName,e.project_id, e.project_code AS projectCode, e.project_name AS projectName, e.tenant_name ")
                .line(", e.mobile, concat(e.province, e.city, e.area, e.address) as address, e.roof_type, sr.angle,e.province,e.area,e.street,e.remove_sign")
                .line(", sr.distance, e.remarks, e.examine_name,e.examine_time,e.examine_remarks, e.order_time, e.receive_time, e.tenant_type")
                .line(", e.check_accept_name, e.check_accept_time, e.deliver_name, e.deliver_time, e.install_time, e.merge_time, e.deliver_file,e.generator_no,e.retrial,e.whether_to_pay,e.wait_loan_time,e.payment_time")
                .line(", e.indoc_name, e.indoc_time, e.create_time, e.examine, e.creator, e.status, e.admit_flag, e.receiving_report_id,e.flag,e.uniformity,e.id_code,e.scheme_type,ifnull(e.component_spec,r.component_spec) as component_spec,r.component_spec as componentSpec")
                .line(", e.trader_name as traderName, e.trader_tel as traderMobile,e.accept_flag,e.partner_name,e.dispatch_status,e.to_examine_status")
                .line(", r.capacity,r.fix_accept_time, r.component_num,m.name AS flag_name,m.type AS flag_type,e.apply_change,e.apply_status,e.next_apply_status,e.credit,e.credit_dsc ")
                .line(", e.contract, sr.azimuth, sr.building_height, sr.repayment_method, e.to_examine_time, e.bill, e.sign_status, e.payment_status , e.wind_pressure , e.snow_pressure , e.pressure_level ")
                .line(", e.design_capacity, e.actual_capacity,e.oneself_flag,e.change_reason,e.engineer_name,e.project_company_name,e.product_line_name,e.product_line")
                .line(",e.authorization,e.first_apply_status,e.apply_back_reason,e.create_trader_name as createTraderName,e.create_trader_id,e.distributor_id,e.id_code as idCode ")
                .line(", e.install_flag,e.filing_type,e.status as entryStratus, e.design_audit_flag, e.check_accept_flag,e.on_grid_flag,e.merge_flag,(select count(1) from crm_customer_interface where entry_id=e.id and status = '0') as coun   ")
                .line(" ,a.payment_finish_time,DATE_FORMAT(e.first_generation_time,'%Y-%m-%d') as first_generation_time,e.in_coming_time,e.pre_audit_time ,e.install_audit_finish_time ,e.install_accept_time,n.assign_audit_user_id  ")
                .line(" ,a.partners_contract_number,a.input_piece_id AS inputPieceId , e.actual_capacity*se.epc_price AS powerStationAmount,i.insurance_amount,i.insurance_number,i.insurance_type,e.if_state_grid_status ,e.is_history,e.is_check_accept,concat(e.province, e.city, e.area) as pca ");
        if("01".equals(map.get("partner")) && "all".equals(map.get("entryPage"))){
            builder.line(" ,de.type as boxGroupType,gr.group_number as boxGroupNumber,gr.group_name as boxGroupName,gr.total_count as  boxGroupTotalCount,gr.already_into_count as boxGroupAlreadyIntoCount,de.serial_number as serialNumber ");
        }
        builder.line("from crm_customer_entry e")
                .line(" left join crm_item_manage as n on n.application_id=e.id and n.status='1' and n.form_key in ( '91' ,'93','94') ")
                .line(" LEFT JOIN crm_order_mark_settings m ON m.`id`=e.`flag` AND m.status='0' and m.use_type='2' ")
                .line("left join crm_customer_incoming_application a on a.entry_id = e.id and a.if_delete = '0'")
                .line("left join crm_accepting_report r on e.receiving_report_id=r.id")
                .line("left join crm_customer_entry_survey_record sr on sr.entry_id = e.id")
                .line("left join crm_partner pa on pa.id = e.partner_id")
                .line("LEFT JOIN crm_project_setting se ON se.id = e.project_id");
        builder.line(" LEFT JOIN crm_customer_incoming_application_insurance i ON i.entry_id = e.id and (e.partner_id in ('01','04')  or (e.partner_id = '03' and  i.insurance_name <>  '工程安装一切险'))  ");
        if (StringUtil.checkParamsValid(map.get("partner"))) {
            //广发资方
//            if("03".equals(map.get("partner"))){
//                builder.line(" AND i.insurance_name <>  '工程安装一切险' ");
//            }else
            if("01".equals(map.get("partner")) && "all".equals(map.get("entryPage"))){
               builder.line("left join crm_entry_combiner_box_group_detail de on de.entry_id=e.id ");
               builder.line(" left join crm_entry_combiner_box_group gr on de.box_group_id=gr.id ");
            }

        }
        builder.line("where 1=1 ");
        appendConditions(builder, map, operator);
        builder.line("and e.status in ('0','1','2','3','4','5','6','7','8','9','10','a','c','d','e','f','g','h','i','11')");
        //待并网，优先显示验收未通过的
        if ("6,10".equals(map.get("status")) || "8,11".equals(map.get("status"))) {
            builder.line("order by e.status*1 desc, e.create_time desc");
        }  else {
            builder.line("order by e.create_time desc");
        }
        builder.limit(page.getPage(), page.getLimit());
        List<Record> records = Db.find(builder.build(), builder.params());
        ItemDispatchUtil.setReviewFlag(records);
        return records;
    }


    public Long countWaitOrders(Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(1) from crm_customer_entry e");
        builder.line(" left join crm_item_manage as n on n.application_id=e.id and n.status='1' and n.form_key in ( '91' ,'93','94')  ")
                .line(" LEFT JOIN crm_order_mark_settings m ON m.`id`=e.`flag` AND m.status='0' and m.use_type='2' ")
                .line("left join crm_customer_incoming_application a on a.entry_id = e.id and a.if_delete = '0'")
                .line("left join crm_accepting_report r on e.receiving_report_id=r.id")
                .line("left join crm_customer_entry_survey_record sr on sr.entry_id = e.id");
        builder.line("where 1=1 ");
        appendConditions(builder, map, operator);
        builder.line("and e.status in ('0','1','2','3','4','5','6','7','8','9','10','a','c','d','e','f','g','h','i','11')");
        //待并网，优先显示验收未通过的
        if ("6,10".equals(map.get("status")) || "8,11".equals(map.get("status"))) {
            builder.line("order by e.status*1 desc, e.create_time desc");
        }  else {
            builder.line("order by e.create_time desc");
        }
        return Db.queryLong(builder.build(), builder.params());
    }

    private List<String> appendColumns(List<Record> records, String column) {
        List<String> ret = new ArrayList<>();
        for (Record record : records) {
            String value = record.getStr(column);
            if (StrKit.notBlank(value)) {
                ret.addAll(Arrays.asList(value.split(",")));
            }
        }
        return ret;
    }

    private void appendConditions(SqlBuilder builder, Map<String, String> map, Operator operator) {

        if (StringUtil.equalsAny(operator.getUserType(), UserConstants.TYPE_TRADER, User.USER_TYPE_ADVISOR)) {
            Record record = CrmUtils.getUserTrader(operator.getUserType(), operator.getUserId());
            String traderId = record.getStr("id");
            String type = record.getStr("type");
            //电站变更选择电站 只能查看自己的
            if ("1".equals(map.get("changeFlag"))) {
                if (UserConstants.TYPE_TRADER.equals(operator.getUserType())) {  //代理商
                    //代理商只能查看自己的
                    builder.line(" and e.create_trader_id =?", traderId);
                } else {
                    String dataAuthority = record.getStr("data_authority");
                    //一级代理商人员
                    if ("1".equals(type) && UserConstants.DATA_AUTHORITY_ALL.equals(dataAuthority)) {
                        builder.line(" and e.create_trader_id =?", traderId);
                    } else { //代理商人员
                        builder.line(" and e.create_trader_id =?", traderId);
                        if (StringUtil.isBlank(dataAuthority) || UserConstants.DATA_AUTHORITY_ONLY.equals(dataAuthority)) {
                            builder.line(" and (e.create_by =? ", operator.getUserId());
                            builder.line(" or (e.dispatch_status = '1' and find_in_set(?, e.engineer_id)))", map.get("engineerId"));
                        }
                    }
                }
            } else {
                if ("1".equals(type)) {  // 1.一级代理商 2.二级代理商
                    builder.line(" and e.distributor_id =?", traderId);
                } else {
                    //二级代理商 代理商只能查看自己的
                    builder.line(" and e.create_trader_id =?", traderId);
                }
                String dataAuthority = record.getStr("data_authority");
                //代理商人员
                if (!UserConstants.TYPE_TRADER.equals(operator.getUserType()) &&
                        (StringUtil.isBlank(dataAuthority) || UserConstants.DATA_AUTHORITY_ONLY.equals(dataAuthority)) ) {
                    builder.line(" and (e.create_by =? ", operator.getUserId());
                    builder.line(" or (e.dispatch_status = '1' and find_in_set(?, e.engineer_id)))", map.get("engineerId"));
                }
            }

        }

        if (StringUtil.checkParamsValid(map.get("authorizedId"))) {
            builder.inst("and e.project_id IN ", Arrays.asList(map.get("authorizedId").split(",")));
        }
        //资方
        if (StringUtil.checkParamsValid(map.get("partner"))) {
            builder.line("and e.partner_id =?", map.get("partner"));
        }
        if(StringUtil.checkParamsValid(map.get("traderId"))){
            builder.line(" and e.distributor_id =?", map.get("traderId"));
        }

        if (StringUtil.checkParamsValid(map.get("acceptFlag"))) {
            builder.line("and e.accept_flag =?", map.get("acceptFlag"));
        }

        if (StringUtil.checkParamsValid(map.get("removeSign"))) {
            builder.line("and e.remove_sign =?", map.get("removeSign"));
        }

        if (StringUtil.checkParamsValid(map.get("ifStateGridStatus"))) {
            builder.line(" AND e.`status` not in ('0','1','2','3','4','5','6') ");
            builder.line(" and e.filing_type = '1' ");
            if (StringUtil.checkParamsValid(map.get("onGridFlag"))){
                builder.inst(" AND e.on_grid_flag not in ",map.get("onGridFlag").split(","));
            }
            builder.line(" AND e.if_state_grid_status = ?",map.get("ifStateGridStatus"));
        }
        if (StringUtil.checkParamsValid(map.get("applyChange"))) {
            builder.line("and e.apply_change =?", map.get("applyChange"));
        }
        //发电户号
        if (StringUtil.checkParamsValid(map.get("generatorNo"))) {
            builder.line("and e.generator_no =?", map.get("generatorNo"));
        }
        //标记类型
        if (StringUtil.checkParamsValid(map.get("flag"))) {
            builder.inst("and e.flag in ", map.get("flag").split(","));
        }
        if (StringUtil.checkParamsValid(map.get("installFlag"))) {
            builder.inst("and e.install_flag in ", map.get("installFlag").split(","));
        }
        if (StringUtil.checkParamsValid(map.get("designAuditFlag"))) {
            builder.inst("and e.design_audit_flag in ", map.get("designAuditFlag").split(","));
        }
        if (StringUtil.checkParamsValid(map.get("checkAcceptFlag"))) {
            builder.inst("and e.check_accept_flag in ", map.get("checkAcceptFlag").split(","));
        }
        if (StringUtil.checkParamsValid(map.get("credit"))) {
            builder.inst("and e.credit in ", map.get("credit").split(","));
        }

        if (StringUtil.checkParamsValid(map.get("status"))) {
            if ("1".equals(map.get("status"))) {
                builder.line(" and (e.status in ('1','2','h') or (e.status = '0' and e.credit = '4') ) ");
            } else if ("0".equals(map.get("status"))) {
                builder.line("and (e.status = 'w' or  (e.status='0' and e.credit !='4') )");
            } else if ("5".equals(map.get("status"))) {
                builder.line("and e.status in ('5','i','f')");
            } else if ("kcbgstatus".equals(map.get("status"))) {//勘测信息变更申请 待设计之后、并网验收之前
                builder.line("and (e.status in ('0','1','2','3','4','5','6','7','10','h','i','f') and e.design_audit_flag  in ('6','7','9','a') and e.credit='4' and  e.apply_status not in('5','14','19','23'))");
            } else if ("wgbgstatus".equals(map.get("status"))) {//电站待并网、并网验收驳回、待并网验收
                builder.line("and e.status in ('6','7','10') ");
            } else if ("khxxbgStatus".equals(map.get("status"))) {
                builder.line(" and e.credit='4' and  e.apply_status not in('5','14','19','23') ");  //预审通过后，可以提交客户信息变更
            }else if("bwxxbg".equals(map.get("status"))){  //并网信息变更：进件状态 并网补充资料待审核 和 并网信息审核驳回  可以提交并网资料变更
                builder.line(" and ( e.next_apply_status='WAITING' or e.next_apply_status='NEW' or e.next_apply_status='DS' or e.next_apply_status='30') and e.apply_status>16 ");
            } else if("sjxxbg".equals(map.get("status"))){// 暂时不允许变更安装验收之后的电站
                builder.line("and ( ");
                builder.line(" e.status in ('4','5','f','i')  ");
                builder.line(" or (e.`status` = '1' AND e.`design_audit_flag` IN ('6','7','8','9')) ");
                builder.line(" or (e.apply_status>1 and e.apply_status not in('3','5') and e.design_audit_flag in ('6','7','9','a') and e.apply_status<13) ");
                builder.line(" ) ");
            }else if ("wlxxbg".equals(map.get("status"))){//物料信息变更
                builder.line(" and e.status in ('5','6','7','10','f','i') and e.apply_status not in('14','19','23') ");
            }else {
                builder.inst("and e.status in ", map.get("status").split(","));
            }
        }
        if (StringUtil.checkParamsValid(map.get("stageStatus"))) {
            if ("0,1,2,3".contains(map.get("stageStatus"))) {
                if ("2".equals(map.get("stageStatus"))) {
                    builder.line("and e.credit in('2','3')");
                } else if ("3".equals(map.get("stageStatus"))) {
                    builder.line("and e.credit ='5'");
                } else {
                    builder.line("and e.credit =?", map.get("stageStatus"));

                }
            } else if ("4,5,6,7,8,n".contains(map.get("stageStatus"))) {
                //设计审核状态：1.待踏勘 2.待自审 3.自审驳回 4.自审通过 5.设计审核驳回 6.设计审核通过/已完成 7.进件审核驳回
                if ("4".equals(map.get("stageStatus"))) {
                    builder.line("and e.design_audit_flag ='1'");
                } else if ("n".equals(map.get("stageStatus"))) {
                    builder.line("and e.design_audit_flag ='a'");
                } else if ("5".equals(map.get("stageStatus"))) {
                    builder.line("and e.design_audit_flag ='2'");
                } else if ("6".equals(map.get("stageStatus"))) {
                    builder.line("and e.design_audit_flag ='3'");
                } else if ("7".equals(map.get("stageStatus"))) {
                    builder.line("and e.design_audit_flag ='4'");
                } else if ("8".equals(map.get("stageStatus"))) {
                    builder.line("and  ( e.design_audit_flag ='5'  or e.zs_result = '4' ) ");
                }
            } else if ("j,l,g".contains(map.get("stageStatus"))) {
                //0.未开始 1.待自审 2.自审通过 3.验收驳回 4.验收通过
                if ("j".equals(map.get("stageStatus"))) {
                    builder.line("and e.check_accept_flag ='1'");
                } else if ("l".equals(map.get("stageStatus"))) {
                    builder.line("and e.check_accept_flag ='2'");
                } else if ("g".equals(map.get("stageStatus"))) {
                    builder.line("and e.check_accept_flag ='3'");
                }
            } else if ("m,k,i".contains(map.get("stageStatus"))) {
                //安装状态：0.未开始 1.待派工 2.待安装 3.自审驳回 4.安装完成
                if ("m".equals(map.get("stageStatus"))) {
                    builder.line("and e.install_flag ='1'");
                } else if ("k".equals(map.get("stageStatus"))) {
                    builder.line("and e.install_flag ='2'");
                } else if ("i".equals(map.get("stageStatus"))) {
                    builder.line("and e.install_flag ='3'");
                } else {
                    builder.line("and e.install_flag ='4'");
                }

            } else if ("f,d,e".contains(map.get("stageStatus"))) {
                //并网状态 0.未开始 1.待并网 2.并网验收驳回   3.资方审核驳回
                if ("f".equals(map.get("stageStatus"))) {
                    builder.line("and e.status ='6'");
                } else if ("d".equals(map.get("stageStatus"))) {
                    builder.line("and e.on_grid_flag ='3'");
                } else {
                    builder.line("and e.status ='10'");
                }
            } else if ("c,b,a".contains(map.get("stageStatus"))) {
                //并网验收状态：0.未开始 1.待并网验收 3.资方审核中 4.资方审核通过
                if ("c".equals(map.get("stageStatus"))) {
                    builder.line("and e.merge_flag ='1'");
                } else if ("b".equals(map.get("stageStatus"))) {
                    builder.line("and e.merge_flag ='3'");
                } else {
                    builder.line("and e.merge_flag ='4'");
                }
            }

        }
        if (StringUtil.checkParamsValid(map.get("isCheckAccept"))) {//
            builder.line("and e.is_check_accept =?", map.get("isCheckAccept"));
        }
        if (StringUtil.checkParamsValid(map.get("projectCompanyName"))) {
            builder.like("and e.project_company_name like ?", map.get("projectCompanyName"));
        }
        if (StringUtil.checkParamsValid(map.get("creator"))) {
            builder.like("and e.creator like ?", map.get("creator"));
        }

        if (StringUtil.checkParamsValid(map.get("credit"))) {
            builder.inst("and e.credit in ", map.get("credit").split(","));
        }

        if (StringUtil.checkParamsValid(map.get("authorization"))) {
            builder.inst("and e.authorization in ", map.get("authorization").split(","));
        }
        if (StringUtil.checkParamsValid(map.get("secCardStatus"))) {
            builder.inst(" and e.filing_type='1' and e.sec_card_status in ", map.get("secCardStatus").split(","));
        }
        if (StringUtil.checkParamsValid(map.get("signStatus"))) {
            builder.inst("and e.sign_status in ", map.get("signStatus").split(","));
        }
        if (StringUtil.checkParamsValid(map.get("schemeType"))) {
            builder.line("and e.scheme_type =?", map.get("schemeType"));
        }
        if (StringUtil.checkParamsValid(map.get("createBy"))) {
            builder.line("and e.create_by =?", map.get("createBy"));
        }
        if (StringUtil.checkParamsValid(map.get("whetherToPay"))) {
            builder.line("and e.whether_to_pay =?", map.get("whetherToPay"));
        }


        if (StringUtil.checkParamsValid(map.get("province"))) {
            builder.line("and e.province =?", map.get("province"));
        }
        if (StringUtil.checkParamsValid(map.get("city"))) {
            builder.line("and e.city =?", map.get("city"));
        }
        if (StringUtil.checkParamsValid(map.get("area"))) {
            builder.line("and e.area =?", map.get("area"));
        }
        if (StringUtil.checkParamsValid(map.get("address"))) {
            builder.like("and e.address like ? ", map.get("address"));
        }

        if (StringUtil.checkParamsValid(map.get("projectCode"))) {
            builder.line("and e.project_id=?", map.get("projectCode"));
        }

        if (StringUtil.checkParamsValid(map.get("projectName"))) {
            builder.like("and e.project_name like ?", map.get("projectName"));
        }

        if (StringUtil.checkParamsValid(map.get("mobile"))) {
            String mobile = map.get("mobile").replaceAll("\\*", "_");
            builder.like("and e.mobile like ?", mobile);
        }

        if (StringUtil.checkParamsValid(map.get("repaymentMethod"))) {
            builder.line("and sr.repayment_method = ?", map.get("repaymentMethod"));
        }

        if (StringUtil.checkParamsValid(map.get("examineRemarks"))) {
            builder.like("and e.examine_remarks like ?", map.get("examineRemarks"));
        }

        if (StringUtil.checkParamsValid(map.get("installWay"))) {
            builder.line("and e.scheme_type_id=?", map.get("installWay"));
        }
        if (StringUtil.checkParamsValid(map.get("roofType"))) {
            builder.line("and e.roof_type = ?", map.get("roofType"));
        }
        if (StringUtil.checkParamsValid(map.get("uniformity"))) {
            builder.line("and e.uniformity = ?", map.get("uniformity"));
        }
        if (StringUtil.checkParamsValid(map.get("plan"))) {
            builder.line("and FIND_IN_SET(?, e.scheme_type_id)", map.get("plan"));
        }
        if (StringUtil.checkParamsValid(map.get("traderId"))) {
            builder.line("and e.distributor_id=?", map.get("traderId"));
        }
        if (StringUtil.checkParamsValid(map.get("checkAcceptBy"))) {
            builder.line("and e.check_accept_by = ?", map.get("checkAcceptBy"));
        }
        if (StringUtil.checkParamsValid(map.get("deliverBy"))) {
            builder.line("and e.deliver_by = ?", map.get("deliverBy"));
        }

        if (StringUtil.checkParamsValid(map.get("examine"))) {
            builder.line("and e.examine = ?", map.get("examine"));
        }

        long checkRo = userDao.isDefaultPlatRole(operator.getUserId());
        if (checkRo > 0) {
            List<Record> employeeRole = siteEmployeeService.findEmployeeByUserId(operator.getUserId());
            List<String> provinceList = appendColumns(employeeRole, "provices");
            List<String> cityList = appendColumns(employeeRole, "city");
            List<String> numberList = appendColumns(employeeRole, "project_number");
            List<String> traderList = appendColumns(employeeRole, "trader_id");
            logger.info("appendConditions :  count :{}  ,  employeeRole :{}  ，provinceList:{},cityList:{},numberList:{}", checkRo, employeeRole, provinceList, cityList, numberList);
            if (!provinceList.isEmpty()) {
                builder.inst("and e.province in ", provinceList);
            }
            if (!cityList.isEmpty()) {
                builder.inst("and e.city in ", cityList);
            }
            if (!numberList.isEmpty()) {
                builder.inst("and e.project_id in ", numberList);
            }

            if (!traderList.isEmpty()) {
                if (map.get("traderId") != null && !map.get("traderId").isEmpty()) {
//                    builder.inst(" and e.distributor_id in ('"+ map.get("traderId") + "')");
                } else {
                    builder.inst(" and e.distributor_id in ", traderList);
                }

            }
        }

        if (!StringUtil.checkParamsValid(map.get("apply"))) {
            builder.line(" and e.retrial <>'2' and e.apply_change <> '2'");
        }


        if (StringUtil.checkParamsValid(map.get("powerStationCode"))) {
            builder.line("and e.power_station_code like concat('%', ?, '%')", map.get("powerStationCode").trim());
        }
        if (StringUtil.checkParamsValid(map.get("tenantName"))) {
            builder.line("and e.tenant_name like concat('%', ?, '%')", map.get("tenantName").trim());
        }
        if (StringUtil.checkParamsValid(map.get("tenantAddress"))) {
            builder.line("and concat(e.province, e.city, e.area,e.street, e.address) like concat('%', ?, '%')", map.get("tenantAddress"));
        }


        if (StringUtil.checkParamsValid(map.get("remarks"))) {
            builder.line("and e.remarks like concat('%', ?, '%')", map.get("remarks"));
        }
        if (StringUtil.checkParamsValid(map.get("createTimeMin"))) {
            builder.line("and e.create_time >= concat(?, ' 00:00:00')", map.get("createTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("createTimeMax"))) {
            builder.line("and e.create_time <= concat(?, ' 23:59:59')", map.get("createTimeMax"));
        }
        if (StringUtil.checkParamsValid(map.get("matchTimeMin"))) {
            builder.line("and e.examine_time >= concat(?, ' 00:00:00')", map.get("matchTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("matchTimeMax"))) {
            builder.line("and e.examine_time <= concat(?, ' 23:59:59')", map.get("matchTimeMax"));
        }
        if (StringUtil.checkParamsValid(map.get("orderTimeMin"))) {
            builder.line("and e.order_time >= concat(?, ' 00:00:00')", map.get("orderTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("orderTimeMax"))) {
            builder.line("and e.order_time <= concat(?, ' 23:59:59')", map.get("orderTimeMax"));
        }
        if (StringUtil.checkParamsValid(map.get("installTimeMin"))) {
            builder.line("and e.install_time >= concat(?, ' 00:00:00')", map.get("installTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("installTimeMax"))) {
            builder.line("and e.install_time <= concat(?, ' 23:59:59')", map.get("installTimeMax"));
        }
        //进件时间
        if (StringUtil.checkParamsValid(map.get("inComingTimeSta"))) {
            builder.line("and e.in_coming_time >= concat(?, ' 00:00:00')", map.get("inComingTimeSta"));
        }
        if (StringUtil.checkParamsValid(map.get("inComingTimeEnd"))) {
            builder.line("and e.in_coming_time <= concat(?, ' 23:59:59')", map.get("inComingTimeEnd"));
        }
        //安装验收时间
        if (StringUtil.checkParamsValid(map.get("fixAcceptTimeSta"))) {
            builder.line("and e.install_accept_time >= concat(?, ' 00:00:00')", map.get("fixAcceptTimeSta"));
        }
        if (StringUtil.checkParamsValid(map.get("fixAcceptTimeEnd"))) {
            builder.line("and e.install_accept_time <= concat(?, ' 23:59:59')", map.get("fixAcceptTimeEnd"));
        }
        //投放通过时间
        if (StringUtil.checkParamsValid(map.get("paymentFinishTimeSta"))) {
            builder.line("and a.payment_finish_time >= concat(?, ' 00:00:00')", map.get("paymentFinishTimeSta"));
        }
        if (StringUtil.checkParamsValid(map.get("paymentFinishTimeEnd"))) {
            builder.line("and a.payment_finish_time <= concat(?, ' 23:59:59')", map.get("paymentFinishTimeEnd"));
        }
        if (StringUtil.checkParamsValid(map.get("receiveTimeMin"))) {
            builder.line("and e.receive_time >= concat(?, ' 00:00:00')", map.get("receiveTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("receiveTimeMax"))) {
            builder.line("and e.receive_time <= concat(?, ' 23:59:59')", map.get("receiveTimeMax"));
        }
        if (StringUtil.checkParamsValid(map.get("mergeTimeMin"))) {
            builder.line("and e.merge_time >= concat(?, ' 00:00:00')", map.get("mergeTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("mergeTimeMax"))) {
            builder.line("and e.merge_time <= concat(?, ' 23:59:59')", map.get("mergeTimeMax"));
        }
        if (StringUtil.checkParamsValid(map.get("checkAcceptTimeMin"))) {
            builder.line("and e.check_accept_time >= concat(?, ' 00:00:00')", map.get("checkAcceptTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("checkAcceptTimeMax"))) {
            builder.line("and e.check_accept_time <= concat(?, ' 23:59:59')", map.get("checkAcceptTimeMax"));
        }
        if (StringUtil.checkParamsValid(map.get("deliverTimeMin"))) {
            builder.line("and e.deliver_time >= concat(?, ' 00:00:00')", map.get("deliverTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("deliverTimeMax"))) {
            builder.line("and e.deliver_time <= concat(?, ' 23:59:59')", map.get("deliverTimeMax"));
        }
        if (StringUtil.checkParamsValid(map.get("indocTimeMin"))) {
            builder.line("and e.indoc_time >= concat(?, ' 00:00:00')", map.get("indocTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("indocTimeMax"))) {
            builder.line("and e.indoc_time <= concat(?, ' 23:59:59')", map.get("indocTimeMax"));
        }
        if (StringUtil.checkParamsValid(map.get("applyTimeMin"))) {
            builder.line("and e.apply_time >= concat(?, ' 00:00:00')", map.get("applyTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("applyTimeMax"))) {
            builder.line("and e.apply_time <= concat(?, ' 23:59:59')", map.get("applyTimeMax"));
        }
        if (StringUtil.checkParamsValid(map.get("applyReasonName"))) {
            builder.line("and e.apply_reason_name like concat('%', ?, '%')", map.get("applyReasonName"));
        }

        if (StringUtil.checkParamsValid(map.get("changeTimeMin"))) {
            builder.line("and e.change_time >= concat(?, ' 00:00:00')", map.get("changeTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("changeTimeMax"))) {
            builder.line("and e.change_time <= concat(?, ' 23:59:59')", map.get("changeTimeMax"));
        }
        if (StringUtil.checkParamsValid(map.get("changeReason"))) {
            builder.line("and e.change_reason like concat('%', ?, '%')", map.get("changeReason"));
        }
        if (StringUtil.checkParamsValid(map.get("searchParameter"))) {
            builder.line("and (e.tenant_name like concat('%', ?, '%') or e.mobile =? )", map.get("searchParameter"), map.get("searchParameter"));
        }

        if (StringUtil.checkParamsValid(map.get("retrial"))) {
            builder.inst("and e.retrial in ", map.get("retrial").split(","));
        }

        if (StringUtil.checkParamsValid(map.get("traderName"))) {
            builder.line("and e.trader_name like concat('%', ?, '%')", map.get("traderName"));
        }
        if (StringUtil.checkParamsValid(map.get("traderMobile"))) {
            builder.line("and e.trader_tel like concat('%', ?, '%')", map.get("traderMobile"));
        }

        if (StringUtil.checkParamsValid(map.get("applyStatus"))) {
        /*    if ("a".equals(map.get("applyStatus"))) {
                builder.line(" and e.apply_status in ('0','1')  and e.management_type='2' ");
            } else {
                builder.line(" and e.apply_status =?  and e.management_type='2' ", map.get("applyStatus"));
            }*/
            builder.line(" and e.apply_status =? ", map.get("applyStatus"));
        }

        // 小程序搜索
        if (StringUtil.checkParamsValid(map.get("keyword"))) {
            builder.like("AND (e.project_code LIKE ?",map.get("keyword"));
            builder.like("OR e.power_station_code LIKE ?",map.get("keyword"));
            builder.like("OR e.tenant_name LIKE ?",map.get("keyword"));
            builder.like("OR CONCAT(e.province,e.city,e.area,e.address) LIKE ? ",map.get("keyword"));
            builder.like("OR e.mobile LIKE ?)",map.get("keyword"));
//            builder.inst("AND (e.project_code IN ", Arrays.asList(map.get("keyword").split(",")));
//            builder.inst("OR e.power_station_code IN ", Arrays.asList(map.get("keyword").split(",")));
//            builder.inst("OR e.tenant_name IN ", Arrays.asList(map.get("keyword").split(",")));
//            builder.inst("OR e.mobile  IN ", Arrays.asList(map.get("keyword").split(",")));
//            builder.line(" )");
        }
        if (StringUtil.checkParamsValid(map.get("twoTrader"))) {
            if ("0".equals(map.get("twoTrader"))) {
                builder.line(" and e.distributor_id =  e.create_trader_id ");
            }else {
                builder.line(" and e.create_trader_id =? ", map.get("twoTrader"));
            }

        }

        if (Objects.equals("1", map.get("orgFlag"))) {
            builder.line("AND e.credit = '4' AND f.status IN ('0','2')");
        } else if (Objects.equals("2", map.get("orgFlag"))) {
            builder.line("AND e.credit = '4' AND f.status = '1'");
        }
    }

    public Record statisticForTrader(String traderId, String userId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select COUNT(CASE WHEN status in ('1', '2') THEN 0 END) dsh,")//待审核
                .line("COUNT(CASE WHEN status='7' THEN 0 END) dys,")//待验收
                .line("COUNT(CASE WHEN status='3' THEN 0 END) dxd,")//待下单
                .line("COUNT(CASE WHEN status='4' THEN 0 END) dshuo,")//待收货
                .line("COUNT(CASE WHEN status='5' THEN 0 END) daz,")//待安装
                .line("COUNT(CASE WHEN status in('6', '10') THEN 0 END) dbw,")//待并网
                .line(" COUNT(CASE WHEN status ='9' THEN 0 END) xmgd,")//项目归档
                .line("COUNT(CASE WHEN status in ('8', '11') THEN 0 END) djf,")//待交付
                .line("COUNT(CASE WHEN status in ('9', 'a') THEN 0 END) yjf")//已交付
                .line("from crm_customer_entry")
                .line("where status <> 'b' and retrial<>'2' and distributor_id=?", traderId);
        if (StringUtil.isNotBlank(userId)) {
            builder.line(" and create_by =?", userId);
        }
        return Db.findFirst(builder.build(), builder.params());
    }

    public Record statisticForPlaft(Map<String, String> map) {
        String sqlMap = getOrderMap(map, null);
        SqlBuilder builder = new SqlBuilder();//7.待验收 8.待交付 9.待归档 a.已完成
        builder.line("select COUNT(CASE WHEN a.status ='1' THEN 0 END) dsh,")
                .line("COUNT(CASE WHEN a.status='2' THEN 0 END) shbh,")
                .line("COUNT(CASE WHEN a.status ='3' and a.apply_status  in('0','1','2','3') and management_type='2' THEN 0 END) jjshCount,")
                .line("COUNT(CASE WHEN a.status ='7' THEN 0 END) dys,")
                .line(" COUNT(CASE WHEN a.status in ('8', '11') THEN 0 END) djf,")
                .line(" COUNT(CASE WHEN a.status ='9' THEN 0 END) dgd,")
                .line(" COUNT(CASE WHEN a.status ='a' THEN 0 END) ywx")
                .line("from crm_customer_entry a")
                .line("where a.status <> 'b' ")
                .line(sqlMap);

        return Db.findFirst(builder.build());
    }

    /**
     * 查询首页统计
     */
    public Record homeStatistics(Map<String, String> map, User user, boolean isShow, Operator operator) {
        // 如果账号无权限显示统计数据，则显示的值都是0
        if (!isShow) {
            Record r = new Record();
            r.set("xxdjTotal", 0);
            r.set("xxsqTotal", 0);  //信息授权 ：显示待授权数量
            r.set("dzckTotal", 0);  //电站初勘：显示待勘测电站数量
            r.set("erlkTotal", 0); //开二类卡：显示待开卡数量
            r.set("nhhtTotal", 0); //农户合同：显示待签约合同
            r.set("sjshTotal", 0);
            r.set("wlxdTotal", 0);
            r.set("dzazTotal", 0);
            r.set("azysTotal", 0);
            r.set("dzbwTotal", 0);
            r.set("htqsTotal", 0);
            r.set("bwysTotal", 0);
            r.set("xmgdTotal", 0);
            r.set("dzzgTotal", 0);
            r.set("ifsgsNum", 0);
            r.set("nbqNum", 0);
        }
        String sqlMap = getOrderMap(map, user);
        String sqlCount = "";
        if (StringUtil.checkParamsValid(map.get("partner")) && map.get("partner").equals(PartnerConstants.PARTNER_ID_HR) ) {
            sqlCount = "COUNT(CASE WHEN a.sign_status IN ('f','1','2','6') THEN 0 END) AS nhhtTotal,";
        }else {
            sqlCount = "COUNT(CASE WHEN a.sign_status IN ('1','4') AND a.apply_change <> '2' THEN 0 END) AS nhhtTotal,";
        }

        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT ")
                .line("COUNT(CASE WHEN a.status = '0' AND a.credit IN ('0','1','2','3','5') AND a.apply_change <> '2' THEN 0 END) AS xxdjTotal,")
                .line("COUNT(CASE WHEN a.status = '0' AND a.authorization in('2') AND a.apply_change <> '2' THEN 0 END) AS xxsqTotal,")
                .line("COUNT(CASE WHEN a.status IN ('0','2') AND a.credit = '4' AND a.apply_change <> '2' and a.design_audit_flag in ('1','3','7','a') THEN 0 END) AS dzckTotal,")
                .line("COUNT(CASE WHEN a.sec_card_status IN ('0','3','4') and p.is_open_bank_card = '1' and a.filing_type='1' and a.credit='4' AND a.apply_change <> '2' THEN 0 END) AS erlkTotal,")
                .line(sqlCount)
                .line("COUNT(CASE WHEN (a.status in ('1','2','h') or (a.status = '0' and a.design_audit_flag in ('2','3')) ) AND a.design_audit_flag IN ('2','4','5','7','8')  THEN 0 END) AS sjshTotal,")
                .line("COUNT(CASE WHEN a.status = '3' AND a.retrial <> '2' AND a.apply_change <> '2' THEN 0 END) AS wlxdTotal,")
                .line("COUNT(CASE WHEN a.status IN ('4') AND a.retrial <> '2' AND a.apply_change <> '2' THEN 0 END) AS dzazTotal,")
                .line("COUNT(CASE WHEN  a.status in ('5','i','f') THEN 0 END) AS azysTotal,")
                .line("COUNT(CASE WHEN a.status IN ('6','10') AND a.retrial <> '2' AND a.apply_change <> '2' THEN 0 END) AS dzbwTotal,")
                .line("COUNT(CASE WHEN a.status = 'e' AND a.retrial <> '2' AND a.apply_change <> '2' THEN 0 END) AS htqsTotal,")
                .line("COUNT(CASE WHEN a.status = '7' AND a.retrial <> '2' AND a.apply_change <> '2' THEN 0 END) AS bwysTotal,")
                .line("COUNT(CASE WHEN a.status = 'a' AND a.retrial <> '2' AND a.apply_change <> '2' THEN 0 END) AS xmgdTotal,")
                .line("COUNT(CASE WHEN a.apply_change = '2' THEN 0 END) AS dzzgTotal,")
                .line("COUNT(CASE WHEN a.credit = '4' AND f.status IN ('0','2') THEN 0 END) AS dzdaTotal,")
                .line("COUNT(CASE WHEN a.`status` not in ('0','1','2','3','4','5','6') and a.on_grid_flag not in ('0','1','2','3') and a.if_state_grid_status = '0'  THEN 0 END) AS ifsgsNum,")  //未国网授权信息
                .line("COUNT(CASE WHEN a.credit = '4' AND f.status = '1' THEN 0 END) AS dashTotal ")
                .line("FROM crm_customer_entry a")
                .line("LEFT JOIN crm_customer_entry_org_files f on f.entry_id = a.id")
                .line(" LEFT JOIN crm_partner p on p.id = a.partner_id ")
                .line("WHERE a.status <> 'b' ")
                .line(sqlMap);
        Record record = Db.findFirst(builder.build());
        SqlBuilder querySql = new SqlBuilder();
        querySql.line("select count(1) FROM crm_customer_entry a WHERE a.`status` in ('6','10') AND a.nbq_dz_id = '' AND a.nbq_factory != '00'  ");
        querySql.line(" and a.id not in(select entry_id from crm_customer_interface where status='0') ");
        querySql.line(sqlMap);
        Long result = Db.queryLong(querySql.build());
        record.set("nbqNum", result);
        return record;
    }

    /**
     * 获取已删除的数据
     */
    public List<Record> findRecycleBinOrders(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select e.id, e.power_station_code, e.scheme_id, e.scheme_name as planName, e.project_code AS projectCode, e.project_name AS projectName, e.tenant_name ")
                .line(", e.mobile, concat(e.province, e.city, e.area,e.street, e.address) as address, e.roof_type, sr.angle, p.attach,e.street")
                .line(", sr.distance, e.remarks, e.examine_name,e.examine_time,e.examine_remarks, e.order_time, e.receive_time")
                .line(", e.check_accept_name, e.check_accept_time, e.deliver_name, e.deliver_time, e.install_time, e.merge_time, e.deliver_file")
                .line(", e.indoc_name, e.indoc_time, e.create_time, e.examine, e.creator, e.status, e.receiving_report_id,e.flag,e.id_code")
                .line(", e.trader_name AS traderName, e.trader_tel AS traderMobile,e.engineer_name,e.project_company_name,e.product_line_name,e.product_line")
                .line(", r.capacity, r.component_num,r.component_spec,m.name AS flag_name,m.type AS flag_type ,e.create_trader_name as createTraderName,e.create_trader_id,e.distributor_id  ")
                .line("from crm_customer_entry e")
                .line(" LEFT JOIN crm_order_mark_settings m ON m.`id`=e.`flag` AND m.status='0' and m.use_type='2' ")
                //  .line("left join crm_trader t on e.distributor_id=t.id")
                .line("left join crm_plan p on e.scheme_id=p.id")
                // .line("left join crm_project_setting s on e.project_id=s.id")
                .line("left join crm_accepting_report r on e.receiving_report_id=r.id")
                .line("left join crm_customer_entry_survey_record sr on sr.entry_id = e.id")
                .line("where e.status = 'b' ");
        appendConditions(builder, map, operator);

        builder.line("order by e.create_time desc");
        builder.limit(page.getPage(), page.getLimit());
        return Db.find(builder.build(), builder.params());
    }

    public Long countRecycleBinOrders(Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(1)")
                .line("from crm_customer_entry e")
                .line(" LEFT JOIN crm_order_mark_settings m ON m.`id`=e.`flag` AND m.status='0' and m.use_type='2' ")
                // .line("left join crm_trader t on e.distributor_id=t.id")
                .line("left join crm_plan p on e.scheme_id=p.id")
                // .line("left join crm_project_setting s on e.project_id=s.id")
                .line("left join crm_accepting_report r on e.receiving_report_id=r.id")
                .line("where e.status = 'b' ");
        appendConditions(builder, map, operator);
        return Db.queryLong(builder.build(), builder.params());
    }


    public List<Record> esalesBasisList(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line(" SELECT any_value(e.id) id,any_value(e.power_station_code) as power_station_code,any_value(e.`project_name`) as project_name,any_value(e.`trader_name`) as trader_name,any_value(e.`tenant_name`) as tenant_name,any_value(e.`mobile` ) as mobile, ")
                .line("any_value(e.`project_code`) as project_code ,any_value(e.design_capacity) as design_capacity  ")
                .line(",any_value(e.actual_capacity) as actual_capacity ,any_value(e.project_company_name) as project_company_name,any_value(e.merge_time) as merge_time,any_value(e.check_accept_time) as check_accept_time")
                .line(",any_value(t.`creator`) as creator,any_value(s.epc_price) as epc_price,sum(k.bd_sale_price) as finalCost ")
                .line("from crm_customer_entry e")
                .line(" LEFT JOIN `crm_trader` t on t.id=e.distributor_id ")
                .line("left join `crm_project_setting`s on s.id=e.project_id ")
                .line("left join `crm_supply_material_keep`k on k.source_id=e.id and `source` = '5' ")
                .line("where e.status = 'a' ");
        appendConditions(builder, map, operator);

        builder.line("order by e.create_time desc");
        builder.limit(page.getPage(), page.getLimit());
        List<Record> records = Db.find(builder.build(), builder.params());
        if (records != null && records.size() > 0) {
            if (StringUtil.isBlank(records.get(0).getStr("id"))) {
                records.remove(0);
            }
        }

        return records;
    }

    public Long countEsalesBasis(Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(1)")
                .line("from crm_customer_entry e")
                .line("LEFT JOIN `crm_trader` t on t.id=e.`distributor_id` ")
                .line("left join `crm_project_setting`s on s.id=e.`project_id`")
                .line("where e.status = 'a' ");
        appendConditions(builder, map, operator);
        return Db.queryLong(builder.build(), builder.params());
    }


    public Record findAccountByentryId(String entryId) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("select SUM(CASE WHEN d.type IN('0','1')THEN d.amount  ELSE 0 END ) AS jsCount, ");
        sql.line("  SUM(CASE WHEN d.type='2' THEN d.amount  ELSE 0 END ) AS thCount from `crm_trader_account_settle_detail` d ");
        sql.line("where d.`entry_id` = ? and type in('1','2','3')", entryId);

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


    /**
     * 获取申请重审的数据
     */
    public List<Record> findRetrialOrders(LayuiPage<Record> page, Map<String, String> map, Operator operator, String objType) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select e.id, e.power_station_code, e.scheme_id, e.scheme_name as planName, e.project_code AS projectCode, e.project_name AS projectName, e.tenant_name,e.street ")
                .line(", e.mobile, concat(e.province, e.city, e.area,e.street, e.address) as address, e.roof_type, sr.angle, p.attach")
                .line(", sr.distance, e.remarks, e.examine_name,e.examine_time,e.examine_remarks, e.order_time, e.receive_time")
                .line(", e.check_accept_name, e.change_reason,e.check_accept_time, e.deliver_name, e.deliver_time, e.install_time, e.merge_time, e.deliver_file,e.retrial,e.apply_reason_id,e.apply_reason_name,e.apply_time")
                .line(", e.indoc_name, e.indoc_time, e.create_time, e.examine, e.creator, e.status, e.receiving_report_id,e.flag,e.id_code")
                .line(", e.trader_name AS traderName, e.trader_tel AS traderMobile,sr.azimuth,sr.building_height,sr.repayment_method")
                .line(",m.name AS flag_name,m.type AS flag_type, e.create_trader_name as createTraderName,e.create_trader_id,e.create_trader_id,e.create_trader_name,e.distributor_id ")
                .line("from crm_customer_entry e")
                .line(" LEFT JOIN crm_order_mark_settings m ON m.`id`=e.`flag` AND m.status='0' and m.use_type='2' ")
                .line("left join crm_plan p on e.scheme_id=p.id")
                .line("left join crm_customer_entry_survey_record sr on sr.entry_id = e.id")
                // .line("left join crm_project_setting s on e.project_id=s.id")
                //  .line("left join crm_trader t on e.distributor_id=t.id")
                .line("where e.status <> 'b' ");
        if ("1".equals(objType)) {
            builder.line(" and e.retrial='2' ");
        } else {
            builder.line(" and e.apply_change='2' ");
        }
        appendConditions(builder, map, operator);

        builder.line("order by e.create_time desc");
        builder.limit(page.getPage(), page.getLimit());
        return Db.find(builder.build(), builder.params());
    }

    public Long countRetrialOrders(Map<String, String> map, Operator operator, String objType) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(1)")
                .line("from crm_customer_entry e")
                .line(" LEFT JOIN crm_order_mark_settings m ON m.`id`=e.`flag` AND m.status='0' and m.use_type='2' ")
                //  .line("left join crm_trader t on e.distributor_id=t.id")
                .line("left join crm_plan p on e.scheme_id=p.id")
                //  .line("left join crm_project_setting s on e.project_id=s.id")
                .line("left join crm_accepting_report r on e.receiving_report_id=r.id")
                .line("where e.status <> 'b' ");
        if ("1".equals(objType)) {
            builder.line(" and e.retrial='2' ");
        } else {
            builder.line(" and e.apply_change='2' ");
        }
        appendConditions(builder, map, operator);
        return Db.queryLong(builder.build(), builder.params());
    }

    public List<Record> findCustomerEntryListNot() {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT a.id,a.tenant_name,a.id_code,r.component_spec,r.component_num, ")
                .line("CONCAT(a.tenant_name,a.id_code,r.component_spec,r.component_num) AS projcetInfo")
                .line(" FROM  crm_customer_entry a")
                .line("LEFT JOIN crm_accepting_report r ON r.id=a.receiving_report_id")
                .line(" WHERE a.status IN('7','8','9','11','a') AND a.uniformity='1'");

        return Db.find(builder.build());
    }

    public void updateUniformity(List<String> ids) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("UPDATE crm_customer_entry SET uniformity='2' WHERE")
                .inst("id IN", ids);
        Db.update(sql.build());
    }

    public void deleteById(String id) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("UPDATE crm_customer_entry SET status='b' WHERE id = ?", id);
        Db.update(sql.build(), sql.params());
    }

    public void updateStatusById(String id, String status) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("UPDATE crm_customer_entry SET status=?", status);
        sql.line("WHERE id = ?", id);
        Db.update(sql.build(), sql.params());
    }

    public void updateInstallFlagById(String id, String flag) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("UPDATE crm_customer_entry SET install_flag =?", flag);
        sql.line("WHERE id = ?", id);
        Db.update(sql.build(), sql.params());
    }

    public void updateDesignAuditFlagById(String id, String audit_remarks, String flag) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("UPDATE crm_customer_entry ");
        sql.line("SET design_audit_flag =?, audit_remarks = ?", flag, audit_remarks);
        sql.line("WHERE id = ?", id);
        Db.update(sql.build(), sql.params());
    }

    public void updateZsResultById(String id, String zsResult) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("UPDATE crm_customer_entry ");
        sql.line("SET zs_result =? ", zsResult);
        sql.line("WHERE id = ?", id);
        Db.update(sql.build(), sql.params());
    }

    public void updateCheckAcceptFlagById(String id, String flag) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("UPDATE crm_customer_entry SET check_accept_flag =?", flag);
        sql.line("WHERE id = ?", id);
        Db.update(sql.build(), sql.params());
    }

    public void updateMergeFlagById(String id, String flag) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("UPDATE crm_customer_entry SET merge_flag =?", flag);
        sql.line("WHERE id = ?", id);
        Db.update(sql.build(), sql.params());
    }

    /**
     * 根据发电户号获取 项目信息
     */
    public Record findCustomerEntryGeneratorNo(String generator_no, String powerStationCode) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT a.id,a.project_name,a.project_code as developer_code,a.receiving_report_id,a.tenant_name,a.trader_name as traderName,a.province,a.id_code,a.mobile,a.generator_no,IFNULL(r.component_num,a.component_count) AS component_count,DATE_FORMAT(a.merge_time,'%Y-%m-%d %H:%i:%s') as merge_time ")
                .line(" FROM  crm_customer_entry a")
                .line("left join crm_accepting_report r on r.id=a.receiving_report_id ")
                .line(" WHERE a.status<>'b' ");
        if (StringUtil.isNotBlank(generator_no)) {
            builder.line("and  a.generator_no=?", generator_no);
        } else if (StringUtil.isNotBlank(powerStationCode)) {
            builder.line("and  a.power_station_code=?", powerStationCode);
        }
        builder.line(" LIMIT 1");
        return Db.findFirst(builder.build(), builder.params());
    }

    /**
     * 根据条件获取项目及验收报告信息
     */
    public List<Record> findCustomerEntryList(LayuiPage<Record> page, Map<String, String> map) {
        SqlBuilder builder = new SqlBuilder();

        builder.line("SELECT a.project_code as projectCode,a.project_name as projectName,a.id,a.distributor_id as distributorId,a.trader_name as traderName,a.trader_tel as traderTel,a.power_station_code as powerStationCode,");
        builder.line("a.tenant_name as tenantName,a.id_code as idCode,a.province,a.city,a.area,a.address,a.mobile,a.roof_type,sr.angle,a.check_accept_imgs as checkAcceptFile, ");
        builder.line("a.method_name as methodName,sr.distance,a.receiving_report_id as reportId,a.generator_no as generatorNo,r.component_spec as  componentSpec,r.component_num as componentNum,r.capacity,r.conclusion");
        builder.line("FROM crm_customer_entry a");
        builder.line("LEFT JOIN crm_accepting_report r ON r.id=a.receiving_report_id");
        builder.line("left join crm_customer_entry_survey_record sr on sr.entry_id = a.id");
        builder.line("WHERE a.status ='9' AND a.project_code like 'TD%' ");
        if (StringUtil.isNotBlank(map.get("generatorNo"))) {
            builder.line("and  a.generator_no=?", map.get("generatorNo"));
        }
        if (StringUtil.isNotBlank(map.get("powerStationCode"))) {
            builder.line("and  a.power_station_code=?", map.get("powerStationCode"));
        }
        if (StringUtil.isNotBlank(map.get("idCode"))) {
            builder.line("and  a.id_code=?", map.get("idCode"));
        }
        if (StringUtil.checkParamsValid(map.get("checkAcceptTimeMin"))) {
            builder.line("and a.check_accept_time >= concat(?, ' 00:00:00')", map.get("checkAcceptTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("checkAcceptTimeMax"))) {
            builder.line("and a.check_accept_time <= concat(?, ' 23:59:59')", map.get("checkAcceptTimeMax"));
        }
        builder.limit(page.getPage(), page.getLimit());
        return Db.find(builder.build(), builder.params());
    }


    public List<Record> findCustomerEntryCount(Map<String, String> map, Operator operator) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT any_value(e.project_id) as project_id,any_value(e.project_name) as project_name,any_value(e.project_code) as project_code,COUNT(e.id) AS count,ROUND(SUM(b.capacity)/1000000,3) AS capacity   ")
                .line("FROM crm_customer_entry e")
                .line("LEFT JOIN crm_accepting_report b ON b.id=e.receiving_report_id")
                .line("WHERE e.status IN ('8','9','11','a','g','AN','BW','BN')");
        appendConditions(sql, map, operator);
        sql.line("GROUP BY e.project_id");
        return Db.find(sql.build());
    }

    /**
     * 首页统计值
     */
    public List<Record> findCustomerEntryGroupProvince(Map<String, String> map, Operator operator) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT any_value(e.project_id) as project_id,e.province,COUNT(e.id)*0.02 AS anl, ")
                .line("(CASE e.province WHEN '安徽省' THEN '160' ")
                .line("WHEN '河南省' THEN '273'")
                .line("WHEN '山西省' THEN '80'")
                .line("WHEN '河北省' THEN '270'")
                .line("WHEN '江西省' THEN '100'")
                .line("WHEN '山东省' THEN '300'")
                .line("ELSE 300 END")
                .line(") as jhl,")
                .line("ROUND(SUM(CASE WHEN  e.status IN('8','9','11','a') THEN (b.capacity) ELSE 0 END)/1000000,3) AS ysl  ")
                .line("FROM crm_customer_entry e ")
                .line("LEFT JOIN crm_accepting_report b ON b.id = e.receiving_report_id ")
                .line("WHERE  e.status IN('6','7','8','9','10','11','a','g','AN','BW','BN') ");
        appendConditions(sql, map, operator);
        sql.line(" GROUP BY e.province ");

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

    /**
     * 查询收货单关联的电站订单
     */
    public List<Record> findRelateNo(String relateNo) {
        return Db.find("SELECT id FROM crm_customer_entry WHERE power_station_code IN (" + StringUtil.joinInSql(relateNo.split(",")) + ")");
    }

    public List<Record> selectWaitOrdersFromSmallP(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select e.id,e.partner_id as partnerId, e.power_station_code, e.scheme_id, e.scheme_name as planName,e.project_id, e.design_audit_flag, e.install_flag,e.project_num,")
                .line("e.project_code AS projectCode, e.project_name AS projectName, e.tenant_type AS tenantType, e.tenant_name,e.authorization")
                .line(", e.mobile, CASE WHEN e.province = e.city THEN  CONCAT(e.province, e.area, e.address) ELSE CONCAT(e.province, e.city, e.area, e.address) END AS address, e.roof_type, sr.angle, e.check_accept_flag,e.on_grid_flag")
                .line(", sr.distance, e.remarks, e.examine_name,e.examine_time,e.examine_remarks, e.order_time, e.receive_time, e.merge_flag,e.zs_result ")
                .line(", e.check_accept_name, e.check_accept_time, e.deliver_name, e.deliver_time, e.install_time, e.merge_time, e.deliver_file,e.generator_no,e.retrial,e.whether_to_pay")
                .line(", e.indoc_name, e.indoc_time, e.create_time, e.examine, e.creator, e.status, e.admit_flag, e.receiving_report_id,e.flag,e.uniformity,e.id_code,e.scheme_type,ifnull(e.component_spec,r.component_spec) as component_spec,r.component_spec as componentSpec")
                .line(", e.trader_name as traderName, e.trader_tel as traderMobile,e.accept_flag,e.partner_name,e.dispatch_status")
                .line(", r.capacity, r.component_num,m.name AS flag_name,m.type AS flag_type,e.apply_change,e.apply_status,e.next_apply_status,e.credit,e.credit_dsc ")
                .line(", e.contract, sr.azimuth, sr.building_height, sr.repayment_method, e.to_examine_time, e.bill, e.sign_status,e.engineer_name,e.if_state_grid_status")
                .line(", e.design_capacity, e.actual_capacity,e.oneself_flag,e.change_reason,e.project_company_name,e.product_line_name,e.product_line,it.assign_audit_user_id");
        //builder.line(",(SELECT COUNT(me.id) FROM crm_plan_material_entry me WHERE me.entry_id = e.id AND me.status = '0' AND me.type IN ('组件','逆变器')) as isUsed,e.sec_card_status");
        builder.line(",5 as isUsed,e.sec_card_status , e.wind_pressure , e.snow_pressure , e.pressure_level ");
        if (Objects.equals("1", map.get("orgFlag")) || Objects.equals("2", map.get("orgFlag"))) {
            builder.line(",f.status AS archivesStatus");
        }
        builder.line(" ,e.age,n.if_click_sign,e.create_trader_id,e.create_trader_name as createTraderName,e.distributor_id,e.management_type, ")
                .line(" (SELECT c.material_brand FROM crm_supply_material as c WHERE c.`code` in(SELECT b.code FROM crm_plan_material_entry as b WHERE b.`entry_id` = e.id AND b.`type` = '逆变器' ) limit 1) as materialBrand ,pa.open_bank_card_way");
        if (map.containsKey("orgFlag") && map.get("orgFlag") != null && StringUtils.isNotBlank(map.get("orgFlag")) && "6".equals(String.valueOf(map.get("orgFlag")))) {
            builder.line(", '6' as orgFlag ");
        }
        builder.line(" from crm_customer_entry e")
                .line(" left join crm_partner pa on pa.id = e.partner_id")
                .line(" left join crm_item_manage as it on it.application_id=e.id and it.status='1' and it.form_key = '91'")
                .line(" left join crm_item_manage as k on k.application_id=e.id and k.status='1' and k.form_key='92'")
                .line(" LEFT JOIN crm_order_mark_settings m ON m.`id`=e.`flag` AND m.status='0' and m.use_type='2' ")
                .line("left join crm_accepting_report r on e.receiving_report_id=r.id")
                .line(" left join crm_customer_contract_management n on n.entry_id=e.id and n.status<>'0' ")
                .line("left join crm_customer_entry_survey_record sr on sr.entry_id = e.id");
        if (StringUtil.checkParamsValid(map.get("secCardStatus"))) {
            builder.line(" inner join crm_partner p on p.id = e.partner_id and p.is_open_bank_card = '1' ");
        }
        if (Objects.equals("1", map.get("orgFlag")) || Objects.equals("2", map.get("orgFlag"))) {
            builder.line("left join crm_customer_entry_org_files f on f.entry_id = e.id");
        }
        builder.line("where 1=1  ");
        appendConditions(builder, map, operator);
        builder.line("and e.status <> 'b'");
        if (StringUtils.isNotBlank(map.get("orgFlag")) && "6".equals(String.valueOf(map.get("orgFlag")))) {
            builder.line(" and e.status in ('6','10') AND e.nbq_dz_id = '' AND e.nbq_factory != '00' ");
            builder.line(" and e.id not in( select entry_id from crm_customer_interface where status=0) ");
            if (map.containsKey("keyword") && map.get("keyword") != null && StringUtils.isNotBlank(map.get("keyword"))) {
                String keyword = "%" + map.get("keyword") + "%";
                builder.line(" and (e.project_code like ? or e.power_station_code like ? or e.tenant_name like ? or e.mobile like ?)", keyword, keyword, keyword, keyword);
            }
        }

        //待并网，优先显示验收未通过的
        if ("6,10".equals(map.get("status")) || "8,11".equals(map.get("status"))) {
            builder.line("order by e.status*1 desc, e.create_time desc");
        } else if(StringUtils.isNotBlank(map.get("orgFlag")) && "1".equals(String.valueOf(map.get("orgFlag")))){
            builder.line("order by f.STATUS DESC ");
        } else{
            builder.line("order by e.create_time desc");
        }
        builder.limit(page.getPage(), page.getLimit());
        logger.info("selectWaitOrders小程序获取项目信息sql {}：", builder.build());
        logger.info("selectWaitOrders小程序获取项目信息params {}：", builder.params());
        List<Record> records = Db.find(builder.build(), builder.params());
        for (Record record : records) {
            record.set("review_flag", false);
            if (Objects.equals(record.getStr("assign_audit_user_id"), operator.getUserId())) {
                record.set("review_flag", true);
            }
        }
        return  records ;
    }


    public List<Record> queryInverterList(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        String params = String.valueOf(map.get("searchParams"));
        params = "%" + params + "%";
        StringBuilder querySql = new StringBuilder();
        querySql.append(" SELECT a.id,a.power_station_code as powerStationCode,(SELECT c.material_brand  FROM crm_supply_material as c ")
                .append(" WHERE c.`code` in(SELECT b.code FROM crm_plan_material_entry as b WHERE b.`entry_id` = a.id AND b.`type` = '逆变器')) as materialBrand,a.tenant_name as tenantName, ")
                .append(" (case a.tenant_type when '1' then '个人' else '单位' end ) tenantType,a.mobile,concat(a.province,a.city,a.area,a.address) as address ")
                .append(" FROM crm_customer_entry a ")
                .append(" WHERE a.`status` = '6' AND a.nbq_dz_id = '' AND a.nbq_factory != '00' ")
                .append(" and (a.project_code like ? or a.power_station_code like ? or a.tenant_name like ? or a.mobile like ?) ");
        return Db.find(querySql.toString(), params, params, params, params);
    }


    public Long countInverterList(Map<String, String> map, Operator operator) {
        String params = String.valueOf(map.get("searchParams"));
        params = "%" + params + "%";
        StringBuilder querySql = new StringBuilder();
        querySql.append(" SELECT count(1) ")
                .append(" FROM crm_customer_entry a ")
                .append(" WHERE a.`status` = '6' AND a.nbq_dz_id = '' AND a.nbq_factory != '00' ")
                .append(" and (a.project_code like ? or a.power_station_code like ? or a.tenant_name like ? or a.mobile like ?) ");
        return Db.queryLong(querySql.toString(), params, params, params, params);
    }

    public Long countWaitOrdersFromSmallP(Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(1)")
                .line("from crm_customer_entry e");
        if (Objects.equals("1", map.get("orgFlag")) || Objects.equals("2", map.get("orgFlag"))) {
            builder.line("left join crm_customer_entry_org_files f on f.entry_id = e.id");
        }
        if (StringUtil.checkParamsValid(map.get("secCardStatus"))) {
            builder.line(" inner join crm_partner p on p.id = e.partner_id and p.is_open_bank_card = '1' ");
        }
        builder.line("where 1=1 ");
        if (map.get("traderId") != null && !map.get("traderId").isEmpty()) {
            builder.line(" and e.distributor_id = ? ", map.get("traderId"));
        }
        appendConditions(builder, map, operator);
        builder.line("and e.status <> 'b'");
        if (StringUtils.isNotBlank(map.get("orgFlag")) && "6".equals(String.valueOf(map.get("orgFlag")))) {
            builder.line(" and e.status in ('6','10') AND e.nbq_dz_id = '' AND e.nbq_factory != '00' ");
            builder.line(" and e.id not in( select entry_id from crm_customer_interface where status=0) ");
            if (map.containsKey("keyword") && map.get("keyword") != null && StringUtils.isNotBlank(map.get("keyword"))) {
                String keyword = "%" + map.get("keyword") + "%";
                builder.line(" and (e.project_code like ? or e.power_station_code like ? or e.tenant_name like ? or e.mobile like ?)", keyword, keyword, keyword, keyword);
            }
        }
        return Db.queryLong(builder.build(), builder.params());
    }

    /**
     * 校验序列号唯一性
     */
    public boolean checkSnUniqueness(String sn) {
        Long aLong = Db.queryLong("SELECT COUNT(1) FROM crm_customer_entry e WHERE FIND_IN_SET(?, e.engineer_id)", sn);
        return aLong > 0;
    }

    /**
     * 首页统计
     */
    public Record findSysHomeList(Map<String, String> map, Operator operator) {

        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT");
        sql.line(" COUNT(a.id) AS newCount,");
        sql.line("COUNT(CASE WHEN a.design_audit_flag in('1','3','5','7','a')  THEN 1 END) AS tksjCount,"); //踏勘设计
        sql.line(" COUNT(CASE WHEN a.design_audit_flag IN ('2','4')   THEN 1 END) AS sjshCount,"); //设计审核
        sql.line("COUNT(CASE WHEN a.install_flag IN ('1','2','3') or a.check_accept_flag='3'   THEN 1 END) AS dazCount,");  //待安装
        sql.line(" COUNT(CASE WHEN a.check_accept_flag IN ('1','2')  THEN 1 END) AS azysCount,"); //安装验收
        sql.line("COUNT(CASE WHEN a.on_grid_flag in('1','3','2')  THEN 1 END) AS dzbwCount,"); //待并网
        sql.line("COUNT(CASE WHEN a.merge_flag in ('1','3')  THEN 1 END) AS bwysCount,"); //并网验收
        sql.line("COUNT(CASE WHEN a.status in('1','g','3','4')  THEN 1 END) AS ysjCount,");//已设计
        sql.line("COUNT(CASE WHEN a.status IN ('5','AN')  THEN 1 END) AS yazCount,");//已安装
        sql.line("COUNT(CASE WHEN a.status IN ('6','e','10','BN')   THEN 1 END) AS yysCount,");//已验收
        sql.line("COUNT(CASE WHEN a.status IN ('7','BW')  THEN 1 END) AS ybwCount,");//已并网
        sql.line("COUNT(CASE WHEN a.status = 'a'  THEN 1 END) AS ywcCount,");//已完成
        sql.line("COUNT(CASE WHEN a.status in('1','g','3','4','5','AN','6','e','7','BW','a','10','BN')  THEN 1 END) AS totalCount,");
        sql.line("COUNT(CASE WHEN a.apply_change = '2' THEN 1 END) AS dzzgCount");
        sql.line("FROM `crm_customer_entry` a WHERE a.status != 'b'   ");
        findMap(sql, map, operator);

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

    /**
     * 首页统计
     */
    public Record findSysPancakeList(Map<String, String> map, Operator operator) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT");
        sql.line("COUNT(CASE WHEN a.credit ='4' THEN 1  END) as ystoCount,");
        sql.line("ifnull(sum(CASE WHEN a.credit ='4' THEN a.estimate_capacity ELSE 0 END),0) AS yuguCount, ");
        sql.line("COUNT(CASE WHEN a.design_audit_flag in ('6','8','9') THEN 1  END) as sjtoCount,");
        sql.line("ifnull(sum(CASE WHEN a.design_audit_flag in ('6','8','9') THEN a.design_capacity ELSE 0 END),0) AS sjCount,");
        sql.line("COUNT(CASE WHEN a.check_accept_flag ='4' THEN 1  END) as azystoCount,");
        sql.line("ifnull(sum(CASE WHEN a.check_accept_flag ='4' THEN a.actual_capacity ELSE 0 END),0) AS azysCount,");
        sql.line("COUNT(CASE WHEN a.merge_flag ='4' THEN 1  END) as bwtoCount,");
        sql.line("ifnull(sum(CASE WHEN a.merge_flag ='4' THEN a.actual_capacity ELSE 0 END),0) AS ybwCount");
        sql.line("FROM `crm_customer_entry` a WHERE a.status != 'b' ");
        findMap(sql, map, operator);

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

    public void findMap(SqlBuilder sql, Map<String, String> map, Operator operator) {
        if (StringUtil.equalsAny(operator.getUserType(), UserConstants.TYPE_TRADER, User.USER_TYPE_ADVISOR)) {
            Record record = CrmUtils.getUserTrader(operator.getUserType(), operator.getUserId());
            String traderId = record.getStr("id");
            String type = record.getStr("type");
            if (UserConstants.TYPE_TRADER.equals(operator.getUserType())) {
                if ("1".equals(type)) {  // 1.一级代理商 2.二级代理商
                    sql.line(" and a.distributor_id =?", traderId);
                } else {  //二级代理商
                    if (UserConstants.TYPE_TRADER.equals(operator.getUserType())) {
                        //代理商只能查看自己的
                        sql.line(" and a.create_trader_id =?", traderId);
                    }
                }
            } else {//代理商员工
                String dataAuthority = record.getStr("data_authority");
                if ("1".equals(type) && UserConstants.DATA_AUTHORITY_ALL.equals(dataAuthority)) {
                    sql.line(" and a.distributor_id =?", traderId);
                } else {
                    sql.line(" and a.create_trader_id =?", traderId);
                    if (StringUtil.isBlank(dataAuthority) || UserConstants.DATA_AUTHORITY_ONLY.equals(dataAuthority)) {
                        sql.line(" and (a.create_by =? ", operator.getUserId());
                        sql.line(" or (a.dispatch_status = '1' and find_in_set(?, a.engineer_id)))", map.get("engineerId"));
                    }
                }

            }
        }
        if (StringUtil.checkParamsValid(map.get("authorizedId"))) {
            sql.inst("and a.project_id IN ", Arrays.asList(map.get("authorizedId").split(",")));
        }
        if (StringUtil.isNotBlank(map.get("productLine"))) {
            sql.line("  AND a.product_line =? ", map.get("productLine"));
        }
//        if(StringUtil.isNotBlank(map.get("timeList"))){
//            sql.inst("  AND DATE_FORMAT(a.create_time,'%Y-%m') in ",map.get("timeList").split(","));
//        }else{
//            sql.line(" AND DATE_FORMAT(a.create_time,'%Y%m')=DATE_FORMAT(CURDATE(),'%Y%m') ");
//        }
        if (StringUtil.isNotBlank(map.get("companyList"))) {
            sql.inst("and  a.project_company_id in ", map.get("companyList").split(","));
        }
        if (StringUtil.isNotBlank(map.get("projectList"))) {
            sql.inst("and  a.project_id in ", map.get("projectList").split(","));
        }
        if (StringUtil.isNotBlank(map.get("traderList"))) {
            sql.inst("and  a.distributor_id in ", map.get("traderList").split(","));
        }
        if (StringUtil.isNotBlank(map.get("provinceList"))) {
            sql.inst("and  a.province in ", map.get("provinceList").split(","));
        }
        if (StringUtil.isNotBlank(map.get("cityList"))) {
            sql.inst("and  a.city in ", map.get("cityList").split(","));
        }

        if (StringUtil.checkParamsValid(map.get("checkAcceptTimeMin"))) {
            sql.line("and a.check_accept_time >= concat(?, ' 00:00:00')", map.get("checkAcceptTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("checkAcceptTimeMax"))) {
            sql.line("and a.check_accept_time <= concat(?, ' 23:59:59')", map.get("checkAcceptTimeMax"));
        }
        if (StringUtil.checkParamsValid(map.get("twoTrader"))) {
            sql.line(" and a.create_trader_id =? ", map.get("twoTrader"));

        }


        long checkRo = userDao.isDefaultPlatRole(operator.getUserId());
        if (checkRo > 0) {
            List<Record> employeeRole = siteEmployeeService.findEmployeeByUserId(operator.getUserId());
            List<String> provinceList = appendColumns(employeeRole, "provices");
            List<String> cityList = appendColumns(employeeRole, "city");
            List<String> numberList = appendColumns(employeeRole, "project_number");
            List<String> traderList = appendColumns(employeeRole, "trader_id");
            logger.info("appendConditions :  count :{}  ,  employeeRole :{}  ，provinceList:{},cityList:{},numberList:{}", checkRo, employeeRole, provinceList, cityList, numberList);
            if (!provinceList.isEmpty()) {
                sql.inst("and a.province in ", provinceList);
            }
            if (!cityList.isEmpty()) {
                sql.inst("and a.city in ", cityList);
            }
            if (!numberList.isEmpty()) {
                sql.inst("and a.project_id in ", numberList);
            }

            if (!traderList.isEmpty()) {
                sql.inst("and a.distributor_id in ", traderList);
            }
        }

    }

    public Long checkIfCashOut(String id) {
        Long count = Db.queryLong(" SELECT COUNT(id) FROM `crm_trader_account_settle_detail` d WHERE entry_id=? AND flag='2'  ", id);
        return count;
    }

    public List<Record> selectOutConfirmData(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT a.id,a.status,a.confirm_time,a.entry_id")
                .line(",e.trader_name,e.power_station_code,e.scheme_name AS planName,e.scheme_id,e.scheme_type")
                .line(",e.trader_tel,e.tenant_name,e.mobile,e.install_time")
                .line("FROM crm_customer_entry_out_confirm a")
                .line("LEFT JOIN crm_customer_entry e on a.`entry_id` = e.`id`");
        builder.line("where 1=1");
        if (StringUtil.checkParamsValid(map.get("confirmStatus"))) {
            builder.line("and a.status = ?", map.get("confirmStatus"));
        }
        if (StringUtil.checkParamsValid(map.get("confirmTimeMin"))) {
            builder.line("and a.confirm_time >= concat(?, ' 00:00:00')", map.get("confirmTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("confirmTimeMax"))) {
            builder.line("and a.confirm_time <= concat(?, ' 23:59:59')", map.get("confirmTimeMax"));
        }
        appendConditions(builder, map, operator);
        builder.line("order by e.install_time desc");
        builder.limit(page.getPage(), page.getLimit());
        return Db.find(builder.build(), builder.params());
    }

    public Long countOutConfirmData(Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT count(a.id)")
                .line("FROM crm_customer_entry_out_confirm a")
                .line("LEFT JOIN crm_customer_entry e on a.`entry_id` = e.`id`");
        builder.line("where 1=1");
        if (StringUtil.checkParamsValid(map.get("confirmStatus"))) {
            builder.line("and a.status = ?", map.get("confirmStatus"));
        }
        if (StringUtil.checkParamsValid(map.get("confirmTimeMin"))) {
            builder.line("and a.confirm_time >= concat(?, ' 00:00:00')", map.get("confirmTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("confirmTimeMax"))) {
            builder.line("and a.confirm_time <= concat(?, ' 23:59:59')", map.get("confirmTimeMax"));
        }
        appendConditions(builder, map, operator);
        return Db.queryLong(builder.build(), builder.params());
    }

    public List<Record> selectMaterialList(String confirmId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT a.num,a.`create_time`,b.code,b.material_name,b.material_specs,b.material_brand,c.name AS typeName");
        builder.line("FROM crm_customer_entry_out_confirm_detail a");
        builder.line("LEFT JOIN crm_supply_material b ON b.id = a.material_id");
        builder.line("LEFT JOIN crm_supply_material_type c ON c.id = b.material_type_id");
        builder.line("WHERE a.main_id=?", confirmId);
        return Db.find(builder.build(), builder.params());
    }

    public Record getProvinceCode(String name) {
        return Db.findFirst("select ProvinceID,regionalism_code from s_province where ProvinceName=?", name);
    }

    public Record getCityCode(String name, Long provinceId) {
        return Db.findFirst("select CityID,regionalism_code from s_city where CityName=? and ProvinceId=?", name, provinceId);
    }

    public Long getDistrictCode(String name, Long cityId) {
        return Db.queryLong("select DistrictID from s_district where DistrictName=? and CityId=?", name, cityId);
    }

    public Record findCustomerYxCondition(String idCode,String partner_id) {
        return Db.findFirst("SELECT * FROM crm_customer_yx_condition WHERE id_code = ? and partner_id=? order by filing_type asc  limit 1", idCode,partner_id);
    }

    public long countByTenantIdExcludeEntry(String tenantId, String entryId) {
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT count(1) FROM crm_customer_entry a ");
        sb.append("WHERE a.tenant_id = ? and a.status != 'b' ");
        if (StringUtil.isNotBlank(entryId)) {
            sb.append("AND a.id != '" + entryId + "' ");
        }
        return Db.queryLong(sb.toString(), tenantId);
    }

    public Record findYxBankCondition(String idCode, String mobile,String partner) {
        return Db.findFirst("SELECT * FROM crm_tenant_yx_bank_card WHERE id_code = ? and mobile=? and partner_id=?  limit 1", idCode, mobile,partner);
    }

    public String findYxBankConditionCode(String idCode, String mobile,String partner) {
        return Db.queryStr("SELECT account_code FROM crm_tenant_yx_bank_card WHERE id_code = ? and mobile=? and partner_id=? limit 1", idCode, mobile,partner);
    }

    //根据进件序号获取电站
    public Record findCustomerEntryByPartnersContractNumber(String partnersContractNumber) {
        return Db.findFirst("SELECT e.id,e.power_station_code,e.distributor_id FROM `crm_customer_entry` e WHERE power_station_code=? ", partnersContractNumber);
    }

    public BigDecimal getTotalAmount(String id, String accountFlag) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT SUM(bd_sale_price*amount)")
                .line("FROM crm_supply_material_keep k")
                .line("LEFT JOIN crm_supply_material m ON m.id = k.material_id")
                .line("WHERE k.source_id =? AND k.type = '2' AND m.material_attribute = '0'", id);
        if (StringUtil.isNotBlank(accountFlag)) {
            builder.line(" and k.account_flag=?", accountFlag);
        }
        BigDecimal total = Db.queryBigDecimal(builder.build(), builder.params());
        return total;
    }

    public Long checkSettlementType(String type, String line, String objectType) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(a.id) from crm_settlement_type a");
        builder.line("where a.status = '1'");
        builder.line("and a.name=?", type);
        builder.line("and a.product_line_name=?", line);
        builder.line("and a.type=?", objectType);
        return Db.queryLong(builder.build(), builder.params());
    }

    public Record findCustomerEntryByCode(String powerStationCode, String traderId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select e.id, e.power_station_code,e.tenant_name,e.mobile,e.roof_type,e.scheme_type,e.scheme_name");
        builder.line(",e.project_code,e.project_name,r.capacity,r.component_num");
        builder.line(",e.province,e.area,e.street,e.tenant_name,e.design_capacity,e.actual_capacity");
        builder.line("from crm_customer_entry e");
        builder.line("left join crm_accepting_report r on e.receiving_report_id=r.id");
        builder.line("where power_station_code =?", powerStationCode);
        builder.line("and distributor_id =?", traderId);
        return Db.findFirst(builder.build(), builder.params());
    }

    public List<CustomerEntry> findEntryByIdCodeVsManagementType(String idCode, String managementType) {
        List<CustomerEntry> list = find(" from CustomerEntry where status!='b' AND (first_apply_status NOT IN ('APPROVING','APPROVED','CLOSED') OR first_apply_status IS NULL) AND  managementType =:p1 AND idCode=:p2 ", new Parameter(managementType, idCode));
        logger.info(">>>>>>>>>>findEntryByIdCodeVsMobile  managementType:{},idCode:{},list.size:{}", managementType, idCode, list.size());
        return list;
    }

    public List<CustomerEntry> findHuaRongEntryByIdCodeVsManagementType(String idCode, String managementType, String partnerId) {
        List<CustomerEntry> list = find(" from CustomerEntry where status!='b' AND  managementType =:p1 AND idCode=:p2 AND partnerId =:p3 ",
                new Parameter(managementType, idCode, partnerId));
        logger.info(">>>>>>>>>>findHuaRongEntryByIdCodeVsManagementType  managementType:{},idCode:{},list.size:{}", managementType, idCode, list.size());
        return list;
    }

    public Record customerManagementStatic(Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line(" SELECT COUNT(CASE WHEN e.status = '0' AND e.credit IN ('0','1','2','3','5')  THEN 0 END) AS totalCount ") //客户管理--全部
                .line(" ,COUNT(CASE WHEN e.status = '0' AND e.credit IN ('0')  THEN 0 END) AS zcCount ") //客户管理--暂存
                .line(" ,COUNT(CASE WHEN e.status = '0' AND e.credit IN ('1','2','3','5')  THEN 0 END) AS ytjCount ") //客户管理--已提交
                .line(" ,COUNT(CASE WHEN e.status = '0' AND e.authorization IN ('2') AND e.credit IN ('0','1','2','3','5')  THEN 0 END) AS dsqCount ") //信息授权--待授权
                .line(" ,COUNT(CASE WHEN e.authorization='3'  THEN 0 END) AS ysqCount ") //信息授权--已授权
                .line(" FROM `crm_customer_entry` e ");
        builder.line("where e.status <> 'b' AND e.apply_change <> '2' ");
        List<Record> employeeRole = siteEmployeeService.findEmployeeByUserId(map.get("userId"));
        List<String> traderList = appendColumns(employeeRole, "trader_id");
        if (!traderList.isEmpty()) {
            if (map.get("traderId") != null && !map.get("traderId").isEmpty()) {
                builder.line(" and e.distributor_id = ?", map.get("traderId"));
            } else {
                builder.line(" and e.distributor_id in (");
                int i = 0;
                for (String s : traderList) {
                    if (i++ != 0) {
                        builder.line(" ,");
                    }
                    builder.line("  ?  ", s);
                }
                builder.line(" )");
            }
        } else {
            if (map.get("traderId") != null && !map.get("traderId").isEmpty()) {
                builder.line(" and e.distributor_id  = ? ", map.get("traderId"));
            }
        }
        List<String> provinceList = appendColumns(employeeRole, "provices");
        if (!provinceList.isEmpty()) {
            builder.line(" and e.province in (");
            int i = 0;
            for (String s : provinceList) {
                if (i++ != 0) {
                    builder.line(" ,");
                }
                builder.line("  ?  ", s);
            }
            builder.line(" )");

        }

        if (StringUtil.equalsAny(operator.getUserType(), UserConstants.TYPE_TRADER, User.USER_TYPE_ADVISOR)) {
            Record record = CrmUtils.getUserTrader(operator.getUserType(), operator.getUserId());
            String traderId = record.getStr("id");
            String type = record.getStr("type");
            if (UserConstants.TYPE_TRADER.equals(operator.getUserType())) {  //代理商
                if ("1".equals(type)) {  // 1.一级代理商 2.二级代理商
                    builder.line(" and e.distributor_id =?", traderId);
                } else {  //二级代理商
                    if (UserConstants.TYPE_TRADER.equals(operator.getUserType())) {
                        //代理商只能查看自己的
                        builder.line(" and e.create_trader_id =?", traderId);
                    }
                }
            } else { //代理商人员
                String dataAuthority = record.getStr("data_authority");
                if ("1".equals(type) && UserConstants.DATA_AUTHORITY_ALL.equals(dataAuthority)) {
                    builder.line(" and e.distributor_id =?", traderId);
                } else {
                    builder.line(" and e.create_trader_id =?", traderId);
                    if (StringUtil.isBlank(dataAuthority) || UserConstants.DATA_AUTHORITY_ONLY.equals(dataAuthority)) {
                        builder.line(" and (e.create_by =? ", operator.getUserId());
                        builder.line(" or (e.dispatch_status = '1' and find_in_set(?, e.engineer_id)))", map.get("engineerId"));
                    }
                }

            }
        }
        if (StringUtil.checkParamsValid(map.get("partner"))) {
            builder.line("and e.partner_id =?", map.get("partner"));
        }
        if(StringUtil.checkParamsValid(map.get("traderId"))){
            builder.line(" and e.distributor_id =?", map.get("traderId"));
        }
        if (StringUtil.checkParamsValid(map.get("credit"))) {
            builder.inst("and e.credit in ", map.get("credit").split(","));
        }
        return Db.findFirst(builder.build(), builder.params());
    }

    public String lookAuthBook(String idCode, String partner_id) {
        String path = Db.queryStr("  SELECT authorization_contract_path FROM `crm_customer_yx_condition` c WHERE c.id_code=?  and c.partner_id=? ORDER BY c.authorization DESC LIMIT 1 ", idCode,partner_id);
        return path;
    }

    public CustomerEntry createOne(AddEntryReq req, CustomerEntry entry) {
        entry.setProjectId(req.getProjectId());
        entry.setTenantName(req.getTenantName());
        entry.setIdCode(req.getIdCode());
        entry.setGender(req.getGender());
        entry.setAge(req.getAge());
        entry.setIdCardFront(req.getIdCardFront());
        entry.setIdCardBack(req.getIdCardBack());
        entry.setBpName(req.getBpName());
        entry.setBpRelation(req.getBpRelation());
        entry.setBpIdCard(req.getBpIdCard());
        entry.setBpMobile(req.getBpMobile());
        entry.setBpCardFront(req.getBpCardFront());
        entry.setBpCardBack(req.getBpCardBack());
        entry.setBpFile(req.getBpFile());
        entry.setRoofType(req.getRoofType());
        entry.setBankName(req.getBankName());
        entry.setBankCode(req.getBankCode().trim());
        entry.setTssBankNumName(req.getTssBankNumName());
        entry.setTssBankNum(req.getTssBankNum());
        entry.setBankCard(req.getBankCard());
        entry.setResidenceBooklet(req.getResidenceBooklet());
        // 客户类型
        entry.setTenantType(req.getTenantType());
        entry.setCorp(req.getCorp());
        entry.setRegno(req.getRegno());
        return entry;
    }

    public List<Record> findEntryLists(String entryId, Operator operator, String ids) {
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.line("select e.id,e.power_station_code,e.tenant_name,concat(e.province, e.city, e.area, e.address) as address,e.design_capacity,e.create_time");
        sqlBuilder.line("from crm_customer_entry e")
                .line("where  e.accept_flag='0' and e.status in('4','5','6','7','10','a','i','f')");
        appendConditions(sqlBuilder, new HashMap<>(), operator);
        if (StringUtil.isNotBlank(entryId)) {
            sqlBuilder.line("and  e.id not in(" + SqlUtils.inParam(Arrays.asList(entryId.split(","))) + ")");
        }
        if (StringUtil.isNotBlank(ids)) {
            sqlBuilder.line("and  e.id in(" + SqlUtils.inParam(Arrays.asList(ids.split(","))) + ")");
        }

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

    public List<Record> getEntryListByEntryIds(String entryId, String ids) {
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.line("select e.id,e.power_station_code,e.tenant_name,concat(e.province, e.city, e.area, e.address) as address,e.design_capacity,DATE_FORMAT(e.create_time,'%Y-%m-%d %H:%i:%s') as createTime ");
        sqlBuilder.line("from crm_customer_entry e where 1=1 ");
        if (StringUtil.isNotBlank(entryId)) {
            sqlBuilder.line("and  e.id not in(" + SqlUtils.inParam(Arrays.asList(entryId.split(","))) + ")");
        }
        if (StringUtil.isNotBlank(ids)) {
            sqlBuilder.line("and  e.id in(" + SqlUtils.inParam(Arrays.asList(ids.split(","))) + ")");
        }

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


    public void changeIfRewardSettle(List<String> entryIds) {
        SQLQuery sqlQuery = getSession().createSQLQuery("update crm_customer_entry set if_reward_settle='1' where id in (" + StringUtil.joinInSql(entryIds) + " )");
        int cou = sqlQuery.executeUpdate();
        logger.info(">>>>>>changeIfRewardSettle cou:{}", cou);
    }

    public List<Record> findInfoBySGStatus(){
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.line(" SELECT province_code,if_state_grid_status,generator_no,power_station_code from crm_customer_entry");
        sqlBuilder.line("  where if_state_grid_status = '1' and status <> 'b'  and generator_no <> ''  and management_type in ('3707','3093') ");
        return Db.find(sqlBuilder.build(), sqlBuilder.params());
    }
    public void updateStateGridStatus(String powerGenerationNo,String status){
        SqlBuilder sql = new SqlBuilder();
        sql.line(" update crm_customer_entry set if_state_grid_status = ? where  ",status)
                .line(" generator_no = ? ",powerGenerationNo);
        Db.update(sql.build(),sql.params());
    }


    public Map getProjectInfoByPowerGenerationNo(String powerGenerationNo){
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.line(" SELECT * from crm_customer_entry where generator_no = ? and `status` <> 'b' ",powerGenerationNo);
        List<Record> entry = Db.find(sqlBuilder.build(), sqlBuilder.params());
        if(entry== null || entry.size()<1){
            return Maps.newHashMap();
        }
        String projectCompanyName = entry.get(0).getStr("project_company_name");
        Map<String,String> proComMap = new HashMap<>();
        if (projectCompanyName.equals("广州越晖光伏科技有限公司")){
            proComMap.put("H5SSL_SIGN_DATA", StateGridConstants.YH_H5SSL_SIGN_DATA);
            proComMap.put("DATA_ID",StateGridConstants.YH_DATA_ID);
        }else if (projectCompanyName.equals("广州越创皓光伏科技有限公司")){
            proComMap.put("H5SSL_SIGN_DATA", StateGridConstants.YCH_H5SSL_SIGN_DATA);
            proComMap.put("DATA_ID",StateGridConstants.YCH_DATA_ID);
        }else {
            proComMap.put("err","未找到该项目公司商户号及密钥");
        }
        return proComMap;
    }
    public Map getProjectInfoMap(CustomerEntry entry){
        String projectCompanyName = entry.getProjectCompanyName();
        Map<String,String> proComMap = new HashMap<>();
        if (projectCompanyName.equals("广州越晖光伏科技有限公司")){
            proComMap.put("H5SSL_SIGN_DATA", StateGridConstants.YH_H5SSL_SIGN_DATA);
            proComMap.put("DATA_ID",StateGridConstants.YH_DATA_ID);
        }else if (projectCompanyName.equals("广州越创皓光伏科技有限公司")){
            proComMap.put("H5SSL_SIGN_DATA", StateGridConstants.YCH_H5SSL_SIGN_DATA);
            proComMap.put("DATA_ID",StateGridConstants.YCH_DATA_ID);
        }else {
            proComMap.put("err","未找到该项目公司商户号及密钥");
        }
        return proComMap;
    }


    /**
     * 根据资方获取账号密码
     * @param partnerId 资方id
     * @param brand 品牌厂家：01.锦浪 02.固德威
     * @return
     */
    public Record findAccountById(String partnerId,String brand){
        SqlBuilder builder = new SqlBuilder();
        builder.line(" select login_name,password,keyword3 from sys_inverter_platform_account  ")
                .line(" where status = '0' and brand = ? ",brand)
                .line(" and parner = ? ",partnerId);
        Record record = Db.findFirst(builder.build(), builder.params());
        return record;
    }

    public void stockEntryCondition(SqlBuilder builder,Map<String, String> map, Operator operator){
        if(StringUtil.equalsAny(operator.getUserType(), UserConstants.TYPE_TRADER, User.USER_TYPE_ADVISOR)){
            Record record= CrmUtils.getUserTrader(operator.getUserType(),operator.getUserId());
            String traderName = record.getStr("name");
            builder.line(" and e.trader_name =?", traderName );
        }

        if (StringUtil.checkParamsValid(map.get("powerStationCode"))) {
            builder.like("and e.power_station_code like ? ", map.get("powerStationCode"));
        }
        if (StringUtil.checkParamsValid(map.get("tenantName"))) {
            builder.like("and e.tenant_name like ? ", map.get("tenantName"));
        }
        if (StringUtil.checkParamsValid(map.get("traderName"))) {
            builder.like("and e.trader_name  like ? ", map.get("traderName"));
        }
        if (StringUtil.checkParamsValid(map.get("mobile"))) {
            builder.like("and e.mobile like ? ", map.get("mobile"));
        }
        if (StringUtil.checkParamsValid(map.get("stationState"))) {
            builder.line("and g.station_state =?", map.get("stationState"));
        }
        if (StringUtil.checkParamsValid(map.get("customerState"))) {
            builder.line("and g.customer_state =?", map.get("customerState"));
        }
        if (StringUtil.checkParamsValid(map.get("inputPieceId"))) {
            builder.like("and g.input_piece_id  like ? ", map.get("inputPieceId"));
        }


    }
    public List<Record> getHistoryEntryList(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select e.id,e.partner_id patnerId, e.power_station_code, e.scheme_id,e.scheme_type_id,e.scheme_type_name ,e.scheme_name as planName,e.project_id, e.project_code AS projectCode, e.project_name AS projectName, e.tenant_name ")
                .line(", e.mobile, concat(e.province, e.city, e.area, e.address) as address, e.roof_type, sr.angle,e.province,e.area,e.street")
                .line(", sr.distance, e.remarks, e.examine_name,e.examine_time,e.examine_remarks, e.order_time, e.receive_time, e.tenant_type")
                .line(", e.check_accept_name, e.check_accept_time, e.deliver_name, e.deliver_time, e.install_time, e.merge_time, e.deliver_file,e.generator_no,e.retrial,e.whether_to_pay")
                .line(", e.indoc_name, e.indoc_time, e.create_time, e.examine, e.creator, e.status, e.admit_flag, e.receiving_report_id,e.flag,e.uniformity,e.id_code,e.scheme_type,ifnull(e.component_spec,r.component_spec) as component_spec,r.component_spec as componentSpec")
                .line(", e.trader_name as traderName, e.trader_tel as traderMobile,e.accept_flag,e.partner_name,e.dispatch_status,e.to_examine_status")
                .line(", r.capacity,r.fix_accept_time, r.component_num,e.apply_change,e.apply_status,e.next_apply_status,e.credit,e.credit_dsc ")
                .line(", e.contract, sr.azimuth, sr.building_height, sr.repayment_method, e.to_examine_time, e.bill, e.sign_status,g.input_piece_id ,g.customer_state ,g.station_state,g.station_msg ")
                .line(", e.design_capacity, e.actual_capacity,e.oneself_flag,e.change_reason,e.engineer_name,e.project_company_name,e.product_line_name,e.product_line")
                .line(",e.authorization,e.first_apply_status,e.apply_back_reason,e.create_trader_name as createTraderName,e.create_trader_id,e.distributor_id,e.id_code as idCode ")
                .line(", e.install_flag,e.filing_type,e.status as entryStratus, e.design_audit_flag, e.check_accept_flag,e.on_grid_flag,e.merge_flag,(select count(1) from crm_customer_interface where entry_id=e.id and status = '0') as coun   ")
                .line(" ,DATE_FORMAT(e.first_generation_time,'%Y-%m-%d') as first_generation_time,e.in_coming_time,e.pre_audit_time ,e.install_audit_finish_time ,e.install_accept_time  ");
        builder.line("from crm_customer_entry_stock e")
                .line("left join crm_accepting_report_stock r on e.id=r.id")
                .line("left join crm_customer_entry_survey_record_stock sr on sr.entry_id = e.id")
                .line(" left join crm_gf_stock_entry g on g.entry_id=e.id");
        builder.line("where 1=1 ");
        stockEntryCondition(builder, map, operator);
        builder.line("order by e.create_time desc");
        builder.limit(page.getPage(), page.getLimit());
        List<Record> records = Db.find(builder.build(), builder.params());
        return records;
    }

    public Long countHistoryEntryList(Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(1) from crm_customer_entry_stock e")
                .line("left join crm_accepting_report_stock r on e.receiving_report_id=r.id")
                .line("left join crm_customer_entry_survey_record_stock sr on sr.entry_id = e.id")
                .line(" left join crm_gf_stock_entry g on g.entry_id=e.id");
        builder.line("where 1=1 ");
        stockEntryCondition(builder, map, operator);
        return Db.queryLong(builder.build(), builder.params());
    }

    public List<Record> getHistoryEntryJjsh(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line(" select  e.id,e.power_station_code,e.trader_name ,e.trader_tel,e.tenant_name,concat(e.province, e.city, e.area, e.address) as address  ,")
                .line(" e.create_time,g.input_piece_id ,g.customer_state ,g.station_state,g.station_msg,g.customer_msg ")
                .line(" from crm_customer_entry_stock e")
                .line(" left join crm_gf_stock_entry g on g.entry_id=e.id ");
        builder.line("where 1=1 ");
        stockEntryCondition(builder, map, operator);
        builder.line("order by e.create_time desc");
        builder.limit(page.getPage(), page.getLimit());
        return Db.find(builder.build(), builder.params());
    }

    public long getHistoryJjShCount(Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT count(1)  ")
                .line(" from crm_customer_entry_stock e ")
               .line(" left join crm_gf_stock_entry g on g.entry_id=e.id ");
        builder.line("where 1=1 ");
        stockEntryCondition(builder, map, operator);
        return Db.queryLong(builder.build(), builder.params());
    }
}
