package com.palmnest.dao.repair.impl;

import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.DateHelper;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.dao.repair.RepairBillDao;
import com.palmnest.model.repair.RepairBill;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import scala.collection.generic.BitOperations;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Repository("repairBillDao")
public class RepairBillDaoImpl extends GenericDaoHibernate<RepairBill, Long> implements RepairBillDao {

    public RepairBillDaoImpl() {
        super(RepairBill.class);
    }

    @Override
    public Page findPageByStatus(Integer status, String repairTypeIds, Long serviceUser, int pageSize, int pageNo, Integer orgId) {

        StringBuilder sql = new StringBuilder("select t.id id,t.code code,t.status status,"
                + "t.address address,t.description description,"
                + "t1.itemname repairAreaName,t2.itemname repairTypeName,t3.itemname repairWayName,"
                + "DATE_FORMAT(t.create_time,'%Y-%m-%d %H:%i') createTime,"
                + "DATE_FORMAT(t.meetingTime,'%Y-%m-%d %H:%i') meetingTime,"
                + "TIMESTAMPDIFF(SECOND,t.create_time,CASE WHEN t.end_time IS NULL THEN NOW() ELSE t.end_time END) keepTime "
                + "from tb_repair_bills t "
                + " LEFT join tb_dictionary_item t1 on t.repair_area=t1.id "
                + " LEFT join tb_dictionary_item t3 on t.repair_way=t3.id "
                + " LEFT join tb_dictionary_item t2 on t.repair_type=t2.id where 1=1 ");

        if (status != null) {
            if (status.equals(CodeConstants.IN_PROGRESS)) {//进行中包含转单和进行中  // add 新加挂单中状态
                sql.append("  and t.status in (3,5,4)");
            } else {
                sql.append("  and t.status =" + status);
            }
        }

        if (repairTypeIds != null) {
            if (repairTypeIds.length() == 0) {
                sql.append(" and t.repair_type in ('')");
            } else {
                sql.append(" and t.repair_type in (" + repairTypeIds + ")");
            }
        }

        if (serviceUser != null) {
            //sql.append(" and t.service_user ="+serviceUser);
            sql.append(" and FIND_IN_SET(" + serviceUser + ",t.service_user) ");
        }

        if (null != orgId) {
            sql.append(" and t.orgId= " + orgId);
        }

        sql.append(" order by t.create_time desc");
        log.info(sql.toString());
        return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
    }

    @Override
    public List<RepairBill> findBy(Long userId, Long areaId) {
        String strHql = "from RepairBill where status=3 and serviceUser= ?  and repairArea = ?";
        List<RepairBill> list = getSession().createQuery(strHql).setLong(0, userId).setLong(1, areaId).list();
        return list;
    }

    @Override
    public Page findPageBy(Map<String, Object> params, int pageSize, int pageNo) {
        StringBuilder sql = new StringBuilder("select t.id id,t.code code,t.status status,confirm_status confirmStatus,"
                + "t.repair_user repairUser,t.contact_way contactWay,"
                + "t.address address,t.description description,"
                + "t1.itemname repairAreaName,t2.id repairTypeId,t2.itemname repairTypeName,t3.id repairWayId,t3.itemname repairWayName,"
                + "t4.id repairTypeDetailId ,t4.itemname repairTypeDetailName,"
                + "DATE_FORMAT(t.create_time,'%Y-%m-%d %H:%i') createTime,"
                + "DATE_FORMAT(t.meetingTime,'%Y-%m-%d %H:%i') meetingTime,"
                + "TIMESTAMPDIFF(SECOND,t.create_time,CASE WHEN t.end_time IS NULL THEN NOW() ELSE t.end_time END) keepTime,"
                + "TIMESTAMPDIFF(SECOND,t.create_time,CASE WHEN t.end_time IS NULL THEN NOW() ELSE t.end_time END) finishTime,"
                + "c.star commentStar,v.star visitStar,org.`name` as org_name,t.orgId ");

        sql.append(" from tb_repair_bills t ");
        sql.append(" LEFT join tb_dictionary_item t1 on t.repair_area=t1.id ");
        sql.append(" LEFT join tb_dictionary_item t2 on t.repair_type=t2.id ");
        sql.append(" LEFT join tb_dictionary_item t3 on t.repair_way=t3.id ");
        sql.append(" LEFT join tb_dictionary_item t4 on t.repair_type_detail=t4.id ");
        sql.append(" left join tb_repair_bill_comments c on c.bill_id = t.id ");
        sql.append(" left join tb_repair_return_visits v on v.bill_id = t.id ");
        sql.append(" LEFT JOIN tb_organization org on org.ID=t.orgId ");

        sql.append(" where 1=1 ");

        if (params.get("star") != null && !params.get("star").equals("")) {
            sql.append(" and c.star =" + params.get("star"));
        }
        if (params.get("hasComment") != null && !params.get("hasComment").equals("")) {
            sql.append(" and t.has_comment = " + params.get("hasComment"));
        }
        if (params.get("hasReturnVisit") != null && !params.get("hasReturnVisit").equals("")) {
            sql.append(" and t.has_return_visit = " + params.get("hasReturnVisit"));
        }
        if (params.get("startTime") != null && !params.get("startTime").equals("")) {
            sql.append(" and t.create_time >= str_to_date('" + params.get("startTime") + " 00:00:00','%Y-%m-%d %H:%i:%s') ");
        }
        if (params.get("endTime") != null && !params.get("endTime").equals("")) {
            sql.append(" and t.create_time <= str_to_date('" + params.get("endTime") + " 23:59:59','%Y-%m-%d %H:%i:%s') ");
        }
        if (params.get("repairWay") != null && !params.get("repairWay").equals("")) {
            sql.append(" and t.repair_way = " + params.get("repairWay"));
        }

        if (params.get("confirmStatus") != null && !params.get("confirmStatus").equals("")) {
            sql.append(" and t.confirm_status = " + params.get("confirmStatus"));
        }

        if (params.get("repairArea") != null && !params.get("repairArea").equals("")) {
            sql.append(" and t.repair_area = " + params.get("repairArea"));
        }
        if (params.get("repairType") != null && !params.get("repairType").equals("")) {
            sql.append(" and t.repair_type = " + params.get("repairType"));
        }
        if (params.get("status") != null && !params.get("status").equals("")) {
            if (((String) params.get("status")).indexOf(",") != -1) {
                sql.append("  and t.status in (" + params.get("status") + ")");
            } else {
                if (params.get("status").equals(CodeConstants.IN_PROGRESS)) {//进行中包含转单和进行中
                    sql.append("  and t.status in (3,5)");
                } else {
                    sql.append("  and t.status =" + params.get("status"));
                }
                if (params.get("status").equals(CodeConstants.COMPLETED)) {//完成包含已完成和审核不通过
                    sql.append("  and t.status in (8,10)");
                } else {
                    sql.append("  and t.status =" + params.get("status"));
                }
            }
        }
        if (params.get("code") != null && !params.get("code").equals("")) {
            sql.append(" and t.code like '%" + params.get("code") + "%'");
        }
        if (params.containsKey("user_id") && params.get("user_id") != null && !params.get("user_id").equals("")) {
            sql.append(" and t.userId = " + params.get("user_id"));
        }
        if (params.get("bill_user_id") != null && !params.get("bill_user_id").equals("")) {
            sql.append(" and t.bill_user_id = " + params.get("bill_user_id"));
        }

        if (params.get("repairTypeIds") != null && ((String) params.get("repairTypeIds")).length() > 0) {
            sql.append(" and t.repair_type in(" + params.get("repairTypeIds") + ")");
        }
        if (params.get("serviceUsers") != null && ((String) params.get("serviceUsers")).length() > 0) {
            sql.append(" and t.service_user in(" + params.get("serviceUsers") + ")");
        }
        if (params.get("orgIds") != null && StringUtils.isNotEmpty(params.get("orgIds").toString())) {
            sql.append(" and t.orgId in (" + params.get("orgIds") + ")");
        }

        if (params.get("managerName") != null && StringUtils.isNotEmpty(params.get("managerName").toString())) {
            sql.append(" and t.id in (" +
                    " SELECT ror.repair_bill_id FROM tb_repair_operate_records ror" +
                    " LEFT JOIN tb_app_user u ON ror.user_id =u.id" +
                    " WHERE u.username LIKE '%" + params.get("managerName") + "%' " +
                    " OR u.full_name LIKE '%" + params.get("managerName") + "%'" +
                    ")");
        }

        sql.append(" order by t.create_time desc");
        log.info(sql.toString());
        return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
    }

    @Override
    public List<RepairBill> findSingleOvertime() {
        String sql = "SELECT DISTINCT t.* FROM tb_repair_bills t WHERE t.status = 2 AND TIMESTAMPDIFF(MINUTE,t.create_time,NOW()) > 2";
        log.info(sql);
        List<RepairBill> list = getSession().createSQLQuery(sql).addEntity(RepairBill.class).list();
        return list;
    }

    public List<RepairBill> findPendOvertime() {
//		String sql = "SELECT DISTINCT tb.* FROM tb_repair_operate_records t " + 
//				" JOIN tb_repair_bills tb ON t.repair_bill_id = tb.id " + 
//				" WHERE tb.status = 4  and STR_TO_DATE(t.expected_time,'%Y-%m-%d %H:%i') < NOW()";
        //----longmeizhen-------------改为查询挂单重新开始时间到现在小于30分钟的单 每5分钟推送一次
        String sql = "SELECT DISTINCT tb.* FROM tb_repair_operate_records t " +
                " JOIN tb_repair_bills tb ON t.repair_bill_id = tb.id " +
                " WHERE tb.status = 4  and TIMESTAMPDIFF(MINUTE,STR_TO_DATE(t.expected_time,'%Y-%m-%d %H:%i'),NOW())<30";

        log.info(sql);

        List<RepairBill> list = getSession().createSQLQuery(sql).addEntity(RepairBill.class).list();
        return list;
    }

    @Override
    public RepairBill findByCode(String code, BigDecimal repairCost) {
        String strHql = "from RepairBill where code=? and repairCost= ? ";
        List<RepairBill> list = getSession().createQuery(strHql).setString(0, code).setBigDecimal(1, repairCost).list();
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<RepairBill> findManagePendOvertime() {
//		String sql = "SELECT DISTINCT tb.* FROM tb_repair_operate_records t " + 
//				" JOIN tb_repair_bills tb ON t.repair_bill_id = tb.id " + 
//				" WHERE tb.status = 4  and TIMESTAMPDIFF(MINUTE,STR_TO_DATE(t.expected_time,'%Y-%m-%d %H:%i'),NOW()) > 2";
        //----longmeizhen-------------改为查询挂单重新开始时间到现在小于20分钟的单 每5分钟推送一次
        String sql = "SELECT DISTINCT tb.* FROM tb_repair_operate_records t " +
                " JOIN tb_repair_bills tb ON t.repair_bill_id = tb.id " +
                " WHERE tb.status = 4  and TIMESTAMPDIFF(MINUTE,STR_TO_DATE(t.expected_time,'%Y-%m-%d %H:%i'),NOW())<20 ";
        List<RepairBill> list = getSession().createSQLQuery(sql).addEntity(RepairBill.class).list();
        log.info(sql);
        return list;
    }

    @Override
    public Integer findCountBy(Integer status, String repairTypeIds, Long serviceUser, Integer orgId) {
        StringBuilder sql = new StringBuilder("select count(t.id) total"
                + " from tb_repair_bills t "
                + " join tb_dictionary_item t2 on t.repair_type=t2.id where 1=1 ");
        if (status != null) {
            if (status.equals(CodeConstants.IN_PROGRESS)) {//进行中包含转单和进行中
                sql.append("  and t.status in (3,5)");
            } else if (status.equals(200)) {//管理待处理去除已完成和已取消
                sql.append("  and t.status in (1,2,22)");
            } else if (status.equals(300)) {//管理权限去除已完成和已取消,待审核
                sql.append("  and t.status in (2,22)");
            } else {
                sql.append("  and t.status =" + status);
            }
        }
        if (repairTypeIds != null && repairTypeIds.length() > 0) {
            sql.append(" and t.repair_type in (" + repairTypeIds + ")");
        }
        if (serviceUser != null) {
            //sql.append(" and t.service_user ="+serviceUser);
            //change dz 1029
            sql.append(" and FIND_IN_SET(" + serviceUser + ",t.service_user) ");

        }
        if (null != orgId) {
            sql.append(" and t.orgId =" + orgId);
        }
        log.info(sql.toString());
        BigInteger i = (BigInteger) getSession().createSQLQuery(sql.toString()).uniqueResult();
        return i.intValue();
    }

    @Override
    public RepairBill findByCode(String code) {
        String strHql = "from RepairBill where code=?";
        List<RepairBill> list = getSession().createQuery(strHql).setString(0, code).list();
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public Integer updateGrabBill(RepairBill bill, Integer version) {

        String sql = "UPDATE tb_repair_bills t SET t.STATUS=" + bill.getStatus() +
                " , t.service_user= '" + bill.getServiceUser() + "', t.version=" + bill.getVersion() +
                ", t.modify_time= '" + DateHelper.formatDate(bill.getModifyTime(), DateHelper.DATE_TIME_STRING) + "' " ;

                if(null != bill.getSingleTime()){
                    sql = sql +  ", t.single_time= '" + DateHelper.formatDate(bill.getSingleTime(), DateHelper.DATE_TIME_STRING) +"' " ;
                }

                sql = sql +  " where t.id=" + bill.getId() + " and t.version=" + version;

        log.info(sql);
        return getSession().createSQLQuery(sql).executeUpdate();
    }

    @Override
    public Integer updateSendUserData(String sendBillIds) {

        String sql = "UPDATE tb_repair_operate_records SET is_confirm = 1 WHERE repair_bill_id in ("+sendBillIds+") AND operate_type = 5 AND is_confirm = 0";
        log.info(sql);
        return getSession().createSQLQuery(sql).executeUpdate();
    }

    @Override
    public List<RepairBill> getTotalByRepairTypeId(Long repairTypeDetailId, Date dateFrom, Date dateTo, String orgIds) {
        StringBuilder sql = new StringBuilder("SELECT DISTINCT * FROM tb_repair_bills " +
                " WHERE 1=1 and repair_type_detail =? and create_time >= ?  and create_time <= ? ");

        if (StringUtils.isNotEmpty(orgIds)) {
            sql.append(" and orgId in (" + orgIds + ")");
        }

        List<RepairBill> list = getSession().createSQLQuery(sql.toString())
                .addEntity(RepairBill.class)
                .setLong(0, repairTypeDetailId)
                .setString(1, DateHelper.formatDate(dateFrom, DateHelper.DATE_TIME_STRING))
                .setString(2, DateHelper.formatDate(dateTo, DateHelper.DATE_TIME_STRING))
                .list();
                //.setString(1, DateHelper.formatDate(dateFrom, DateHelper.DATE_TIME_STRING))
                //.setString(2, DateHelper.formatDate(dateTo, DateHelper.DATE_TIME_STRING))


        log.info("getTotalByRepairTypeId:  sql:\n" + sql);
        return list;
    }

    /**
     * 查询指定转单人的订单信息
     *
     * @param params
     * @param pageSize
     * @param pageNo
     * @return
     */
    @Override
    public Page findPageByRepairUser(Map<String, Object> params, int pageSize, int pageNo) {
        StringBuilder sql = new StringBuilder("select t.id id,t.code code,t.status status,"
                + "t.repair_user repairUser,t.contact_way contactWay,"
                + "t.address address,t.description description,"
                + "t1.itemname repairAreaName,t2.id repairTypeId,t2.itemname repairTypeName,t3.id repairWayId,t3.itemname repairWayName,"
                + "t4.id repairTypeDetailId ,t4.itemname repairTypeDetailName,"
                + "DATE_FORMAT(t.create_time,'%Y-%m-%d %H:%i') createTime,"
                + "DATE_FORMAT(t.meetingTime,'%Y-%m-%d %H:%i') meetingTime,"
                + "TIMESTAMPDIFF(SECOND,t.create_time,CASE WHEN t.end_time IS NULL THEN NOW() ELSE t.end_time END) keepTime,"
                + "TIMESTAMPDIFF(SECOND,t.create_time,CASE WHEN t.end_time IS NULL THEN NOW() ELSE t.end_time END) finishTime,"
                + "c.star commentStar,v.star visitStar,org.`name` as org_name,t.orgId ");

        sql.append(" from tb_repair_bills t ");
        sql.append(" LEFT join tb_dictionary_item t1 on t.repair_area=t1.id ");
        sql.append(" LEFT join tb_dictionary_item t2 on t.repair_type=t2.id ");
        sql.append(" LEFT join tb_dictionary_item t3 on t.repair_way=t3.id ");
        sql.append(" LEFT join tb_dictionary_item t4 on t.repair_type_detail=t4.id ");
        sql.append(" LEFT join tb_repair_bill_comments c on c.bill_id = t.id ");
        sql.append(" LEFT join tb_repair_return_visits v on v.bill_id = t.id ");
        sql.append(" LEFT JOIN tb_organization org on org.ID=t.orgId ");
        sql.append(" LEFT JOIN tb_repair_operate_records ror on t.id=ror.repair_bill_id ");
        sql.append(" where 1=1 and ror.operate_type =3");

        if (params.get("star") != null && !params.get("star").equals("")) {
            sql.append(" and c.star =" + params.get("star"));
        }
        if (params.get("hasComment") != null && !params.get("hasComment").equals("")) {
            sql.append(" and t.has_comment = " + params.get("hasComment"));
        }
        if (params.get("hasReturnVisit") != null && !params.get("hasReturnVisit").equals("")) {
            sql.append(" and t.has_return_visit = " + params.get("hasReturnVisit"));
        }
        if (params.get("startTime") != null && !params.get("startTime").equals("")) {
            sql.append(" and t.create_time >= str_to_date('" + params.get("startTime") + " 00:00:00','%Y-%m-%d %H:%i:%s') ");
        }
        if (params.get("endTime") != null && !params.get("endTime").equals("")) {
            sql.append(" and t.create_time <= str_to_date('" + params.get("endTime") + " 23:59:59','%Y-%m-%d %H:%i:%s') ");
        }
        if (params.get("repairWay") != null && !params.get("repairWay").equals("")) {
            sql.append(" and t.repair_way = " + params.get("repairWay"));
        }
        if (params.get("repairArea") != null && !params.get("repairArea").equals("")) {
            sql.append(" and t.repair_area = " + params.get("repairArea"));
        }
        if (params.get("repairType") != null && !params.get("repairType").equals("")) {
            sql.append(" and t.repair_type = " + params.get("repairType"));
        }
        if (params.get("status") != null && !params.get("status").equals("")) {
            if (((String) params.get("status")).indexOf(",") != -1) {
                sql.append("  and t.status in (" + params.get("status") + ")");
            } else {
                if (params.get("status").equals(CodeConstants.IN_PROGRESS)) {//进行中包含转单和进行中
                    sql.append("  and t.status in (3,5)");
                } else {
                    sql.append("  and t.status =" + params.get("status"));
                }
                if (params.get("status").equals(CodeConstants.COMPLETED)) {//完成包含已完成和审核不通过
                    sql.append("  and t.status in (8,10)");
                } else {
                    sql.append("  and t.status =" + params.get("status"));
                }
            }
        }
        if (params.get("code") != null && !params.get("code").equals("")) {
            sql.append(" and t.code like '%" + params.get("code") + "%'");
        }
        if (params.get("bill_user_id") != null && !params.get("bill_user_id").equals("")) {
            sql.append(" and t.bill_user_id = " + params.get("bill_user_id"));
        }
        if (params.get("repairTypeIds") != null && ((String) params.get("repairTypeIds")).length() > 0) {
            sql.append(" and t.repair_type in(" + params.get("repairTypeIds") + ")");
        }
        if (params.get("serviceUsers") != null && ((String) params.get("serviceUsers")).length() > 0) {
            sql.append(" and t.service_user in(" + params.get("serviceUsers") + ")");
        }
        if (params.get("orgIds") != null && StringUtils.isNotEmpty(params.get("orgIds").toString())) {
            sql.append(" and t.orgId in (" + params.get("orgIds") + ")");
        }
        if (params.get("userId") != null && !params.get("userId").equals("")) {
            sql.append(" AND ror.user_id= " + params.get("userId"));
        }
        sql.append(" order by t.create_time desc");
        log.info(sql.toString());
        return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
    }

    @Override
    public Page findBordPage(Map<String, Object> conditions, int pageSize, int pageNo) {
        StringBuilder sql = new StringBuilder("SELECT "
                + " t.id repairBillId, "
                + " t.`CODE` `code`, "
                + " t.`STATUS` `status`, "
                + "  t2.id repairTypeId, t2.itemname repairTypeName, "
                + " t.repair_user repairUser, t.contact_way contactWay, "
                + " DATE_FORMAT(t.create_time, '%Y-%m-%d %H:%i:%S') createTime , "
                + " DATE_FORMAT(t.create_time, '%Y-%m-%d %H:%i') reportTime, "
                + " DATE_FORMAT(t.meetingTime, '%Y-%m-%d %H:%i') meetingTime, "
                + " org.`name` AS orgName, t.orgId, "
                + " auser.FULL_NAME serviceUserName, "
                + " auser.TELEPHONE serviceUserPhone ");

        sql.append(" FROM tb_repair_bills t ");
        sql.append(" LEFT JOIN tb_dictionary_item t2 ON t.repair_type = t2.id ");
        sql.append(" LEFT JOIN tb_organization org ON org.ID = t.orgId");
        sql.append(" LEFT JOIN tb_app_user auser ON t.service_user = auser.id ");
        sql.append(" where 1=1  AND t.`status` NOT IN (8, 10, 11)");

        if (conditions.get("orgIds") != null && StringUtils.isNotEmpty(conditions.get("orgIds").toString())) {
            sql.append(" and t.orgId in (" + conditions.get("orgIds") + ")");
        }
        sql.append(" order by t.create_time asc");

        log.info(sql.toString());
        return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
    }

    @Override
    public List<RepairBill> findByOrg(String orgIds) {
        StringBuilder sql = new StringBuilder("SELECT DISTINCT * FROM tb_repair_bills " +
                " WHERE  1=1  ");

        if (StringUtils.isNotEmpty(orgIds)) {
            sql.append(" and orgId in (" + orgIds + ")");
        }

        List<RepairBill> list = getSession().createSQLQuery(sql.toString()).addEntity(RepairBill.class).list();

        log.info("findByOrg:  sql:\n" + sql);
        return list;
    }

	@Override
	public Page getAllWxOrder(Map<String, Object> conditions,int type,int pageNo,int pageSize) {
		StringBuilder sql=new StringBuilder("");
		sql.append(" SELECT r.orgId, o.`name` orgName, v.id virtId, v.`name` virtName,  ");
		sql.append(" ifnull(count(r.id), 0) sumCount, ifnull(t.sumCount, 0) amountCount, IFNULL(t.sumAmount,0) sumAmount  ");
		if(conditions.get("dateString") != null && StringUtils.isNotEmpty(conditions.get("dateString").toString())){
			sql.append(" ,'"+conditions.get("dateString")+"' dateInfo ");
		}
		sql.append(" FROM tb_repair_bills r  ");
		sql.append(" LEFT JOIN tb_user u ON r.userId = u.ID  ");
		sql.append(" LEFT JOIN tb_organization o ON o.id = r.orgId  ");
		sql.append(" LEFT JOIN tb_virtualarchitecture v ON v.id = u.virtualArchId AND v.organizationId = o.id  ");
		sql.append(" LEFT JOIN (   ");
		sql.append("     SELECT r1.orgId, u1.virtualArchId, count(r1.id) sumCount, sum(r1.repair_cost) sumAmount  ");
		sql.append("     FROM tb_repair_bills r1 LEFT JOIN tb_user u1 ON r1.userId = u1.ID  AND r1.orgId = u1.organizationId ");
		sql.append("     WHERE 1 = 1 AND r1.orgId IS NOT NULL AND r1.userId IS NOT NULL AND r1.repair_cost > 0  ");
		if (1 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and year(r1.create_time) = "+conditions.get("date"));
        }else if (2 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString()) 
        		&& conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r1.create_time) = "+conditions.get("date"));
            sql.append(" and QUARTER(r1.create_time) = "+conditions.get("endDate"));
        }else if (3 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())
        		&& conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r1.create_time) = "+conditions.get("date"));
            sql.append(" and month(r1.create_time) = "+conditions.get("endDate"));
        }else if (4 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and DATE_FORMAT(r1.create_time,'%Y-%m-%d') >= '"+conditions.get("date")+"'");
            if(conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())){
            	sql.append(" and DATE_FORMAT(r1.create_time,'%Y-%m-%d') <= '"+conditions.get("endDate")+"'");
            }
        }
		sql.append("     GROUP BY r1.orgId, u1.virtualArchId  ");
		sql.append("  ) t ON t.orgId = r.orgId AND t.virtualArchId = u.virtualArchId  ");
		sql.append("  WHERE 1 = 1 AND r.orgId IS NOT NULL AND r.userId IS NOT NULL AND u.virtualArchId IS NOT NULL   ");
		if (conditions.get("orgId") != null && StringUtils.isNotEmpty(conditions.get("orgId").toString())) {
            sql.append(" and r.orgId = "+conditions.get("orgId"));
        }
		if (conditions.get("virtId") != null && StringUtils.isNotEmpty(conditions.get("virtId").toString())) {
            sql.append(" and v.id = "+conditions.get("virtId"));
        }
		if (1 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
        }else if (2 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString()) 
        		&& conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
            sql.append(" and QUARTER(r.create_time) = "+conditions.get("endDate"));
        }else if (3 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())
        		&& conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
            sql.append(" and month(r.create_time) = "+conditions.get("endDate"));
        }else if (4 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and DATE_FORMAT(r.create_time,'%Y-%m-%d') >= '"+conditions.get("date")+"'");
            if(conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())){
            	sql.append(" and DATE_FORMAT(r.create_time,'%Y-%m-%d') <= '"+conditions.get("endDate")+"'");
            }
        }
		sql.append("  GROUP BY r.orgId, v.id   ");
		sql.append("  ORDER BY r.create_time  DESC   ");
        log.info(sql.toString());
		return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
	}

	@Override
	public Page getWxAmountOrder(Map<String, Object> conditions,int isFree,int type,int pageNo,int pageSize) {
		StringBuilder sql=new StringBuilder("");
		sql.append("  SELECT v.id virtId,v.`name` virtName, ");
		sql.append("  r.`CODE` number,DATE_FORMAT(r.create_time,'%Y-%m-%d %T') createTime,r.repair_user repairUser,r.contact_way contactWay,u.userName,u.userMobile, ");
		sql.append("  ifnull(GROUP_CONCAT(CONCAT(m.material_name,'*',m.amount)),'') material,ifnull(r.repair_cost,0) repairCost ");
		if(conditions.get("dateString") != null && StringUtils.isNotEmpty(conditions.get("dateString").toString())){
			sql.append(" ,'"+conditions.get("dateString")+"' dateInfo ");
		}
		sql.append("  FROM tb_repair_bills r ");
		sql.append("  LEFT JOIN tb_user u ON u.id = r.userId ");
		sql.append("  LEFT JOIN tb_virtualarchitecture v ON v.id = u.virtualArchId AND v.organizationId = r.orgId ");
		sql.append("  LEFT JOIN tb_repair_bill_materials m ON m.bill_id = r.id ");
		sql.append("  WHERE 1 = 1 AND r.orgId IS NOT NULL AND r.userId IS NOT NULL AND u.virtualArchId IS NOT NULL ");
		if(0 == isFree){
			sql.append("  AND r.repair_cost > 0   ");
		}
		if (conditions.get("orgId") != null && StringUtils.isNotEmpty(conditions.get("orgId").toString())) {
            sql.append(" and r.orgId = "+conditions.get("orgId"));
        }
		if (conditions.get("virtId") != null && StringUtils.isNotEmpty(conditions.get("virtId").toString())) {
            sql.append(" and v.id = "+conditions.get("virtId"));
        }
		if (1 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
        }else if (2 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString()) 
        		&& conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
            sql.append(" and QUARTER(r.create_time) = "+conditions.get("endDate"));
        }else if (3 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())
        		&& conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
            sql.append(" and month(r.create_time) = "+conditions.get("endDate"));
        }else if (4 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and DATE_FORMAT(r.create_time,'%Y-%m-%d') >= '"+conditions.get("date")+"'");
            if(conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())){
            	sql.append(" and DATE_FORMAT(r.create_time,'%Y-%m-%d') <= '"+conditions.get("endDate")+"'");
            }
        }
		sql.append("  GROUP BY r.id   ");
		sql.append("  ORDER BY r.create_time  DESC   ");
        log.info(sql.toString());
		return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
	}

	@Override
	public List<Map<String, Object>> getExportAllWxOrder(Map<String, Object> conditions, int type) {
		StringBuilder sql=new StringBuilder("");
		sql.append(" SELECT r.orgId, o.`name` orgName, v.id virtId, v.`name` virtName,  ");
		sql.append(" ifnull(count(r.id), 0) sumCount, ifnull(t.sumCount, 0) amountCount, IFNULL(t.sumAmount,0) sumAmount  ");
		if(conditions.get("dateString") != null && StringUtils.isNotEmpty(conditions.get("dateString").toString())){
			sql.append(" ,'"+conditions.get("dateString")+"' dateInfo ");
		}
		sql.append(" FROM tb_repair_bills r  ");
		sql.append(" LEFT JOIN tb_user u ON r.userId = u.ID  ");
		sql.append(" LEFT JOIN tb_organization o ON o.id = r.orgId  ");
		sql.append(" LEFT JOIN tb_virtualarchitecture v ON v.id = u.virtualArchId AND v.organizationId = o.id   ");
		sql.append(" LEFT JOIN (   ");
		sql.append("     SELECT r1.orgId, u1.virtualArchId, count(r1.id) sumCount, sum(r1.repair_cost) sumAmount  ");
		sql.append("     FROM tb_repair_bills r1 LEFT JOIN tb_user u1 ON r1.userId = u1.ID  ");
		sql.append("     WHERE 1 = 1 AND r1.orgId IS NOT NULL AND r1.userId IS NOT NULL AND r1.repair_cost > 0  ");
		if (1 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and year(r1.create_time) = "+conditions.get("date"));
        }else if (2 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString()) 
        		&& conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r1.create_time) = "+conditions.get("date"));
            sql.append(" and QUARTER(r1.create_time) = "+conditions.get("endDate"));
        }else if (3 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())
        		&& conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r1.create_time) = "+conditions.get("date"));
            sql.append(" and month(r1.create_time) = "+conditions.get("endDate"));
        }else if (4 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and DATE_FORMAT(r1.create_time,'%Y-%m-%d') >= '"+conditions.get("date")+"'");
            if(conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())){
            	sql.append(" and DATE_FORMAT(r1.create_time,'%Y-%m-%d') <= '"+conditions.get("endDate")+"'");
            }
        }
		sql.append("     GROUP BY r1.orgId, u1.virtualArchId  ");
		sql.append("  ) t ON t.orgId = r.orgId AND t.virtualArchId = u.virtualArchId  ");
		sql.append("  WHERE 1 = 1 AND r.orgId IS NOT NULL AND r.userId IS NOT NULL  AND u.virtualArchId IS NOT NULL  ");
		if (conditions.get("orgId") != null && StringUtils.isNotEmpty(conditions.get("orgId").toString())) {
            sql.append(" and r.orgId = "+conditions.get("orgId"));
        }
		if (conditions.get("virtId") != null && StringUtils.isNotEmpty(conditions.get("virtId").toString())) {
            sql.append(" and v.id = "+conditions.get("virtId"));
        }
		if (1 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
        }else if (2 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString()) 
        		&& conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
            sql.append(" and QUARTER(r.create_time) = "+conditions.get("endDate"));
        }else if (3 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())
        		&& conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
            sql.append(" and month(r.create_time) = "+conditions.get("endDate"));
        }else if (4 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and DATE_FORMAT(r.create_time,'%Y-%m-%d') >= '"+conditions.get("date")+"'");
            if(conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())){
            	sql.append(" and DATE_FORMAT(r.create_time,'%Y-%m-%d') <= '"+conditions.get("endDate")+"'");
            }
        }
		sql.append("  GROUP BY r.orgId, v.id   ");
		sql.append("  ORDER BY r.create_time  DESC   ");
        log.info(sql.toString());
		return getJdbcTemplate().queryForList(sql.toString());
	}

    @Override
    public List<Map<String, Object>> getSendUserData(Integer userId) {


        StringBuilder sql=new StringBuilder("");
        sql.append(" SELECT                                                                         ");
        sql.append(" 	GROUP_CONCAT(DISTINCT t.id) sendBillIds,COUNT(DISTINCT t.id) sendCount      ");
        sql.append(" FROM                                                                           ");
        sql.append(" 	tb_repair_bills t                                                           ");
        sql.append(" LEFT JOIN tb_repair_operate_records re ON re.repair_bill_id = t.id             ");
        sql.append(" WHERE                                                                          ");
        sql.append(" 	t.`STATUS` = 3                                                              ");
        sql.append(" AND re.operate_type = 5                                                        ");
        sql.append(" AND re.is_confirm = 0                                                          ");
        sql.append(" AND t.service_user = "+userId+" ");
        log.info(sql.toString());
        return getJdbcTemplate().queryForList(sql.toString());

    }

    @Override
	public List<Map<String, Object>> getExportWxAmountOrder(Map<String, Object> conditions, int isFree, int type) {
		StringBuilder sql=new StringBuilder("");
		sql.append("  SELECT v.id virtId,v.`name` virtName, ");
		sql.append("  r.`CODE` number,DATE_FORMAT(r.create_time,'%Y-%m-%d %T') createTime,r.repair_user repairUser,r.contact_way contactWay,u.userName,u.userMobile, ");
		sql.append("  ifnull(GROUP_CONCAT(CONCAT(m.material_name,'*',m.amount)),'') material,ifnull(r.repair_cost,0) repairCost ");
		if(conditions.get("dateString") != null && StringUtils.isNotEmpty(conditions.get("dateString").toString())){
			sql.append(" ,'"+conditions.get("dateString")+"' dateInfo ");
		}
		sql.append("  FROM tb_repair_bills r ");
		sql.append("  LEFT JOIN tb_user u ON u.id = r.userId ");
		sql.append("  LEFT JOIN tb_virtualarchitecture v ON v.id = u.virtualArchId AND v.organizationId = r.orgId  ");
		sql.append("  LEFT JOIN tb_repair_bill_materials m ON m.bill_id = r.id ");
		sql.append("  WHERE 1 = 1 AND r.orgId IS NOT NULL AND r.userId IS NOT NULL AND u.virtualArchId IS NOT NULL ");
		if(0 == isFree){
			sql.append("  AND r.repair_cost > 0   ");
		}
		if (conditions.get("orgId") != null && StringUtils.isNotEmpty(conditions.get("orgId").toString())) {
            sql.append(" and r.orgId = "+conditions.get("orgId"));
        }
		if (conditions.get("virtId") != null && StringUtils.isNotEmpty(conditions.get("virtId").toString())) {
            sql.append(" and v.id = "+conditions.get("virtId"));
        }
		if (1 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
        }else if (2 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString()) 
        		&& conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
            sql.append(" and QUARTER(r.create_time) = "+conditions.get("endDate"));
        }else if (3 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())
        		&& conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
            sql.append(" and month(r.create_time) = "+conditions.get("endDate"));
        }else if (4 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and DATE_FORMAT(r.create_time,'%Y-%m-%d') >= '"+conditions.get("date")+"'");
            if(conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())){
            	sql.append(" and DATE_FORMAT(r.create_time,'%Y-%m-%d') <= '"+conditions.get("endDate")+"'");
            }
        }
		sql.append("  GROUP BY r.id   ");
		sql.append("  ORDER BY r.create_time  DESC   ");
        log.info(sql.toString());
		return getJdbcTemplate().queryForList(sql.toString());
	}

    @Override
    public Page getPeoplecOrderList(Map<String, Object> conditions, int type,int pageNo, int pageSize) {

        StringBuilder sql=new StringBuilder("");

        sql.append("  SELECT                                                                                                               ");
        sql.append("    dateInfo,                                                                                                               ");
        sql.append("  	centerName,orgName,serverName,                                                                                     ");
        sql.append("  	sum(totalServerNum) totalServerNum,                                                                                ");
        sql.append("  	sum(completeNum) completeNum,                                                                                      ");
        sql.append("  	sum(unFinishedNum) unFinishedNum,                                                                                  ");
        sql.append("  	sum(supportUserNum) supportUserNum,                                                                                ");
        sql.append("  	sum(turnNum) turnNum,                                                                                              ");
        sql.append("  	sum(hangNum) hangNum,                                                                                              ");
        sql.append("    sum(negativeNum)negativeNum,                                                                                       ");
        sql.append("    CONCAT(ROUND(sum(t.completeNum)*100 / sum(t.totalServerNum),2),'%') completeRate ,                                             ");
        sql.append("  	CONCAT(ROUND(sum(t.supportUserNum)*100 / sum(t.totalServerNum),2),'%') supportUserRate,                                       ");
        sql.append("    CONCAT(ROUND(sum(t.turnNum)*100 / sum(t.totalServerNum),2),'%') turnRate,                                                     ");
        sql.append("    CONCAT(ROUND(sum(t.hangNum)*100 / sum(t.totalServerNum),2),'%') hangRate,                                                     ");
        sql.append("    CONCAT(ROUND(sum(t.negativeNum)*100 / sum(t.totalServerNum),2),'%') negativeRate                                              ");
        sql.append("                                                                                                                       ");
        sql.append("   FROM                                                                                                                ");
        sql.append("  (                                                                                                                    ");
        sql.append("                                                                                                                       ");
        sql.append("  	 SELECT                                                                                                            ");

        if(conditions.get("dateString") != null && StringUtils.isNotEmpty(conditions.get("dateString").toString())){
            sql.append(" '"+conditions.get("dateString")+"' dateInfo, ");
        }

        sql.append("  				com.`name` centerName,                                                                                 ");
        sql.append("  				org.name orgName,                                                                                      ");
        sql.append("  				u.id userId,                                                                                           ");
        sql.append("  				u.FULL_NAME serverName,                                                                                ");
        sql.append("  				count(u.id) totalServerNum,                                                                            ");
        sql.append("  				sum(                                                                                                   ");
        sql.append("  					CASE WHEN r. STATUS = 8 THEN 	1 	ELSE 	0 END 	) completeNum,                                 ");
        sql.append("  				sum(                                                                                                   ");
        sql.append("  					CASE WHEN r. STATUS = 3 OR r. STATUS = 4 OR r. STATUS = 5 THEN 1 ELSE 0 END ) unFinishedNum,       ");
        sql.append("  				sum(                                                                                                   ");
        sql.append("  					CASE WHEN su.support_user_id = u.id THEN 1 ELSE 0 END ) supportUserNum,                            ");
        sql.append("  				sum(                                                                                                   ");
        sql.append("  					ifnull(                                                                                            ");
        sql.append("  						(                                                                                              ");
        sql.append("  							SELECT 1 FROM tb_repair_operate_records re  WHERE                                          ");
        sql.append("  								re.operate_type = 7 AND re.repair_bill_id = r.id AND re.creator = u.FULL_NAME          ");
        sql.append("  							LIMIT 1                                                                                    ");
        sql.append("  						),                                                                                             ");
        sql.append("  						0                                                                                              ");
        sql.append("  					)                                                                                                  ");
        sql.append("  				) turnNum,                                                                                             ");
        sql.append("  			 sum(                                                                                                      ");
        sql.append("  					CASE                                                                                               ");
        sql.append("  					WHEN r. STATUS = 4 THEN 1  ELSE 0 END ) hangNum,                                                   ");
        sql.append("  			sum(                                                                                                       ");
        sql.append("  					CASE WHEN c.star  <= 2 THEN 1  ELSE 0 END ) negativeNum                                            ");
        sql.append("  			FROM                                                                                                       ");
        sql.append("  				tb_repair_bills r                                                                                      ");
        sql.append("  			LEFT JOIN tb_app_user u ON r.service_user = u.id                                                           ");
        sql.append("  			LEFT JOIN tb_repair_bill_support_users su ON su.bill_id = r.id                                             ");
        sql.append("  			left join tb_repair_bill_comments c on c.bill_id = r.id                                                    ");
        sql.append("  			LEFT JOIN tb_organization org on org.ID=r.orgId                                                            ");
        sql.append("  			LEFT JOIN tr_company_org co ON co.org_id = r.orgId                                                         ");
        sql.append("  			LEFT JOIN tb_company  com on com.id =  co.company_id                                                       ");
        sql.append("  			                                                                                                           ");
        sql.append("  			WHERE                                                                                                      ");
        sql.append("  				1 = 1                                                                                                  ");
        sql.append("  			and r.`STATUS` != 11                                                                                       ");
        sql.append("  			and u.FULL_NAME is not null                                                                                ");
        //sql.append("  			and year(r.create_time) = 2021                                                                             ");
        //sql.append("  			and r.orgId = 615                                                                                          ");
        //sql.append("  			and com.id = 1                                                                                             ");
        //sql.append("  			#and u.FULL_NAME like '%李四%'                                                                             ");


        if (conditions.get("centerId") != null && StringUtils.isNotEmpty(conditions.get("centerId").toString())) {
            sql.append(" and com.id = "+conditions.get("centerId"));
        }
        if (conditions.get("orgId") != null && StringUtils.isNotEmpty(conditions.get("orgId").toString())) {
            sql.append(" and r.orgId = "+conditions.get("orgId"));
        }
        if (conditions.get("name") != null && StringUtils.isNotEmpty(conditions.get("name").toString())) {
            sql.append(" and u.FULL_NAME like '%" + conditions.get("name") + "%'");
        }

        if (1 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
        }else if (2 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())
                && conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
            sql.append(" and QUARTER(r.create_time) = "+conditions.get("endDate"));
        }else if (3 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())
                && conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
            sql.append(" and month(r.create_time) = "+conditions.get("endDate"));
        }else if (4 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and DATE_FORMAT(r.create_time,'%Y-%m-%d') >= '"+conditions.get("date")+"'");
            if(conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())){
                sql.append(" and DATE_FORMAT(r.create_time,'%Y-%m-%d') <= '"+conditions.get("endDate")+"'");
            }
        }




        sql.append("  			GROUP BY                                                                                                   ");
        sql.append("  				u.id                                                                                                   ");
        sql.append("                                                                                                                       ");
        sql.append("  UNION ALL                                                                                                            ");
        sql.append("                                                                                                                       ");
        sql.append("  	 SELECT                                                                                                            ");

        if(conditions.get("dateString") != null && StringUtils.isNotEmpty(conditions.get("dateString").toString())){
            sql.append(" '"+conditions.get("dateString")+"' dateInfo, ");
        }

        sql.append("  				com.`name` centerName,                                                                                 ");
        sql.append("  				org.name orgName,                                                                                      ");
        sql.append("  				suu.id userId,                                                                                         ");
        sql.append("  				suu.FULL_NAME serverName,                                                                              ");
        sql.append("  				count(u.id) totalServerNum,                                                                            ");
        sql.append("  				0 completeNum,                                                                                         ");
        sql.append("  				0 unFinishedNum,                                                                                       ");
        sql.append("  				0 supportUserNum,                                                                                      ");
        sql.append("  				0 turnNum,                                                                                             ");
        sql.append("  				0 hangNum,                                                                                             ");
        sql.append("  				sum(                                                                                                   ");
        sql.append("  					CASE WHEN c.star  <= 2 THEN 1  ELSE 0 END ) negativeNum                                            ");
        sql.append("  			FROM                                                                                                       ");
        sql.append("  				tb_repair_bills r                                                                                      ");
        sql.append("  			LEFT JOIN tb_app_user u ON r.service_user = u.id                                                           ");
        sql.append("  			LEFT JOIN tb_repair_bill_support_users su ON su.bill_id = r.id                                             ");
        sql.append("  			LEFT JOIN tb_app_user suu ON suu.id = su.support_user_id                                        ");
        sql.append("  			left join tb_repair_bill_comments c on c.bill_id = r.id                                                    ");
        sql.append("  			LEFT JOIN tb_organization org on org.ID=r.orgId                                                            ");
        sql.append("  			LEFT JOIN tr_company_org co ON co.org_id = r.orgId                                                         ");
        sql.append("  			LEFT JOIN tb_company  com on com.id =  co.company_id                                                       ");
        sql.append("  			                                                                                                           ");
        sql.append("  			WHERE                                                                                                      ");
        sql.append("  				1 = 1                                                                                                  ");
        sql.append("  			and r.`STATUS` != 11                                                                                       ");
        sql.append("  			and u.FULL_NAME is not null                                                                                ");
        //sql.append("  			and year(r.create_time) = 2021                                                                             ");
        //sql.append("  			and r.orgId = 615                                                                                          ");
        //sql.append("  			and com.id = 1                                                                                             ");
        //sql.append("  			#and u.FULL_NAME like '%李四%'                                                                             ");
        sql.append("  			and su.support_user_id  is not null                                                                        ");
        sql.append("  			and u.id != su.support_user_id                                                         ");


        if (conditions.get("centerId") != null && StringUtils.isNotEmpty(conditions.get("centerId").toString())) {
            sql.append(" and com.id = "+conditions.get("centerId"));
        }
        if (conditions.get("orgId") != null && StringUtils.isNotEmpty(conditions.get("orgId").toString())) {
            sql.append(" and r.orgId = "+conditions.get("orgId"));
        }
        if (conditions.get("name") != null && StringUtils.isNotEmpty(conditions.get("name").toString())) {
            sql.append(" and suu.FULL_NAME like '%" + conditions.get("name") + "%'");
        }

        if (1 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
        }else if (2 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())
                && conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
            sql.append(" and QUARTER(r.create_time) = "+conditions.get("endDate"));
        }else if (3 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())
                && conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(r.create_time) = "+conditions.get("date"));
            sql.append(" and month(r.create_time) = "+conditions.get("endDate"));
        }else if (4 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and DATE_FORMAT(r.create_time,'%Y-%m-%d') >= '"+conditions.get("date")+"'");
            if(conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())){
                sql.append(" and DATE_FORMAT(r.create_time,'%Y-%m-%d') <= '"+conditions.get("endDate")+"'");
            }
        }



        sql.append("  			GROUP BY                                                                                                   ");
        sql.append("  				u.id                                                                                                   ");
        sql.append("  ) t                                                                                                                  ");
        sql.append("  GROUP BY t.centerName,t.orgName,t.userId                                                                             ");

        if (conditions.get("sortFieldName") != null && StringUtils.isNotEmpty(conditions.get("sortFieldName").toString())) {
            sql.append(" ORDER BY  "+conditions.get("sortFieldName") + " " + conditions.get("sortType"));
        }

        log.info(sql.toString());
        return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
    }

    @Override
    public List<Integer> getAutomaticHighPraiseRepairData() {

        StringBuilder sql=new StringBuilder("");
        sql.append("  SELECT id FROM tb_repair_bills WHERE `STATUS` = 8 and has_comment = 1 and TIMESTAMPDIFF(HOUR,end_time,NOW()) >= 168 ");

        log.info(sql.toString());
        return getJdbcTemplate().queryForList(sql.toString(), Integer.class);
    }


    @Override
    public Page getBillCommentList(Map<String, Object> conditions,int type,int pageNo, int pageSize) {

        StringBuilder sql=new StringBuilder("");

        sql.append(" SELECT                                                                      ");
        if(conditions.get("dateString") != null && StringUtils.isNotEmpty(conditions.get("dateString").toString())){
            sql.append(" '"+conditions.get("dateString")+"' dateInfo, ");
        }
        sql.append(" 	com.`name` centerName,                                                              ");
        sql.append(" 	  orgId,org.`name` orgName,                                                      ");
        sql.append(" 	ROUND(AVG(IF(IFNULL(c.star,0) > IFNULL(rd.star,0),c.star,rd.star)),2) avgStar,                                               ");
        sql.append(" 	    sum(CASE WHEN IF(IFNULL(c.star,0) > IFNULL(rd.star,0),c.star,rd.star) = 1  THEN 	1 	ELSE 	0 END 	) oneStar,       ");
        sql.append(" 		sum(CASE WHEN IF(IFNULL(c.star,0) > IFNULL(rd.star,0),c.star,rd.star) = 2  THEN 	1 	ELSE 	0 END 	) twoStar,       ");
        sql.append(" 		sum(CASE WHEN IF(IFNULL(c.star,0) > IFNULL(rd.star,0),c.star,rd.star) = 3  THEN 	1 	ELSE 	0 END 	) threeStar,     ");
        sql.append(" 		sum(CASE WHEN IF(IFNULL(c.star,0) > IFNULL(rd.star,0),c.star,rd.star) = 4  THEN 	1 	ELSE 	0 END 	) fourStar,      ");
        sql.append(" 		sum(CASE WHEN IF(IFNULL(c.star,0) > IFNULL(rd.star,0),c.star,rd.star) = 5  THEN 	1 	ELSE 	0 END 	) fiveStar       ");
        sql.append(" FROM                                                                        ");
        sql.append(" 	tb_repair_bills t                                                        ");
        sql.append(" LEFT JOIN tb_repair_bill_comments c on c.bill_id = t.id                     ");
        sql.append(" LEFT JOIN tb_repair_return_visits rd on rd.bill_id =  t.id                  ");
        sql.append(" LEFT JOIN tb_organization org on org.ID=t.orgId                             ");
        sql.append(" LEFT JOIN tr_company_org co ON co.org_id = t.orgId                          ");
        sql.append(" LEFT JOIN tb_company  com on com.id =  co.company_id                        ");
        sql.append(" WHERE 1=1 and c.star is not null                                            ");




        if (conditions.get("centerId") != null && StringUtils.isNotEmpty(conditions.get("centerId").toString())) {
            sql.append(" and com.id = "+conditions.get("centerId"));
        }
        if (conditions.get("orgId") != null && StringUtils.isNotEmpty(conditions.get("orgId").toString())) {
            sql.append(" and t.orgId = "+conditions.get("orgId"));
        }

        if (1 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and year(t.create_time) = "+conditions.get("date"));
        }else if (2 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())
                && conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(t.create_time) = "+conditions.get("date"));
            sql.append(" and QUARTER(t.create_time) = "+conditions.get("endDate"));
        }else if (3 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())
                && conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())) {
            sql.append(" and year(t.create_time) = "+conditions.get("date"));
            sql.append(" and month(t.create_time) = "+conditions.get("endDate"));
        }else if (4 == type && conditions.get("date") != null && StringUtils.isNotEmpty(conditions.get("date").toString())) {
            sql.append(" and DATE_FORMAT(t.create_time,'%Y-%m-%d') >= '"+conditions.get("date")+"'");
            if(conditions.get("endDate") != null && StringUtils.isNotEmpty(conditions.get("endDate").toString())){
                sql.append(" and DATE_FORMAT(t.create_time,'%Y-%m-%d') <= '"+conditions.get("endDate")+"'");
            }
        }


        sql.append(" GROUP BY orgId  ");

        log.info(sql.toString());
        return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
    }


}
