package com.sifang.modules.quality.dao;

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

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

@Repository
public class CrmEntryQualityAcceptanceDao extends BaseDao<CrmEntryQualityAcceptance> {

    public List<Record> entryQualityData(Map<String,String> param, LayuiPage<Record> page){
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line("  SELECT  a.id,a.type,a.number,a.trader_name,a.region_province,a.region_city,a.region_area,a.status,a.create_method ");
        sqlBuilder.line("  ,a.total_count, a.sample_count,a.quality_emp_name,a.create_time,a.finish_time,a.finish_count,a.quality_emp_user_id  ");
        sqlBuilder.line(" ,a.type ");
        sqlBuilder.line("  FROM crm_entry_quality_acceptance a ");
        sqlBuilder.line("  WHERE a.status<>'0'  ");
        getCommonCondition(param,sqlBuilder);
        sqlBuilder.line(" ORDER BY a.create_time DESC ");
        if (page != null) {
            sqlBuilder.limit(page.getPage(), page.getLimit());
        }
        return Db.find(sqlBuilder.build(),sqlBuilder.params());
    }

    public Long getListCont(Map<String,String> param){
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line("  SELECT COUNT(a.id) FROM crm_entry_quality_acceptance a ");
        sqlBuilder.line("  WHERE a.status<>'0' ");
        getCommonCondition(param,sqlBuilder);
        return Db.queryLong(sqlBuilder.build(),sqlBuilder.params());
    }

    public void getCommonCondition(Map<String,String> param,SqlBuilder builder){
        if (StringUtil.checkParamsValid(param.get("powerStationCode"))) {
            builder.line(" AND EXISTS (SELECT id FROM `crm_entry_quality_acceptance_detail` d WHERE d.`main_id`=a.id AND d.power_station_code LIKE '%"+param.get("powerStationCode")+"%')  ");
        }
        if (StringUtil.checkParamsValid(param.get("tenantName"))) {
            builder.line(" AND EXISTS (SELECT id FROM `crm_entry_quality_acceptance_detail` d WHERE d.`main_id`=a.id AND d.tenant_name LIKE '%"+param.get("tenantName")+"%')  ");
        }
        if (StringUtil.checkParamsValid(param.get("qualityEmpId"))) {
            builder.line("and a.quality_emp_id =? ", param.get("qualityEmpId"));
        }
        if (StringUtil.checkParamsValid(param.get("type"))) {
            builder.line("and a.type =? ", param.get("type"));
        }
        if (StringUtil.checkParamsValid(param.get("traderId"))) {
            builder.line("and a.trader_id = ?", param.get("traderId"));
        }
        if (StringUtil.checkParamsValid(param.get("createTimeSta"))) {
            builder.line(" and a.finish_time >= '" + param.get("createTimeSta") + " 00:00:00' ");
        }
        if (StringUtil.checkParamsValid(param.get("createTimeEnd"))) {
            builder.line(" and a.finish_time <= '" + param.get("createTimeEnd") + " 23:59:59' ");
        }
        if(StringUtil.checkParamsValid(param.get("number"))){
            builder.like(" AND a.number like ? ",param.get("number"));
        }
        if(StringUtil.checkParamsValid(param.get("smallCondition"))){
            builder.like(" AND a.number like ? ",param.get("smallCondition"));
        }
        if(StringUtil.checkParamsValid(param.get("status"))){
            builder.inst("and a.status in ", param.get("status").split(","));
        }
    }


    public List<String> getSettleList(String settleIds){
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT DISTINCT(s.entry_id) as entry_id");
        sb.append(" FROM crm_trader_account_settle_detail s ");
        sb.append(" WHERE s.id IN ( "+StringUtil.joinInSql(settleIds.split(","))+") ");
        return Db.query(sb.toString());
    }

    public long countByDate(Date date) {
        return Db.queryLong("select count(*) from crm_entry_quality_acceptance where create_time>=?", DateUtils.dayStr(date));
    }

    public List<Record> getDispatchEmpData(Map<String,String> param){
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT  e.id,e.name,e.mobile,COUNT(q.id) AS waitCount,IFNULL(SUM(q.sample_count-q.finish_count),0) AS waitEntryCount ");
        sb.append(" FROM crm_platform_employee e ");
        sb.append(" LEFT JOIN crm_entry_quality_acceptance q ON q.quality_emp_id=e.id AND q.status='2'");
        sb.append(" WHERE e.status='0' ");
        if(StringUtil.checkParamsValid(param.get("empName"))){
          sb.append(" and e.name like '%"+param.get("empName")+"%' ");
        }
        sb.append(" GROUP BY e.id ORDER BY e.create_time ASC ");
        return Db.find(sb.toString());
    }

    //质检单详情
    public Record getOrderDetail(String id){
        StringBuilder sb=new StringBuilder();
        sb.append("  SELECT a.id ,a.number,a.trader_id,a.trader_name,a.region_province,a.region_city,a.region_area,a.status ");
        sb.append("  ,a.quality_emp_id,a.quality_emp_name,a.total_count,a.finish_count ,a.type ");
        sb.append("  ,DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s')AS createTime,DATE_FORMAT(a.dispatch_time,'%Y-%m-%d %H:%i:%s')AS dispatchTime  ");
        sb.append(" FROM crm_entry_quality_acceptance a ");
        sb.append("  WHERE a.id=? ");
        return Db.findFirst(sb.toString(),id);
    }
    //质检单抽检的关联的电站信息  status=1,2,3抽检的  status=0 未抽检的  status=null所有的
    public List<Record> getOrderRelateEntryList(String id,String status,String tenantName){
        StringBuilder sb=new StringBuilder();
        sb.append("  SELECT d.id,d.entry_id,d.power_station_code,d.accept_status,CONCAT(e.province,e.city,e.area,e.address) AS entryAddress ");
        sb.append("   ,r.component_num,r.capacity,e.tenant_name,d.status,e.tenant_type,e.longitude,e.latitude ");
        sb.append(" FROM crm_entry_quality_acceptance_detail d ");
        sb.append("  LEFT JOIN crm_customer_entry e ON e.id=d.entry_id ");
        sb.append("  LEFT JOIN crm_accepting_report r ON r.id=e.receiving_report_id ");
        sb.append(" WHERE d.main_id=? ");
        if(StringUtil.isNotBlank(status)){
            sb.append(" and d.status in ("+StringUtil.joinInSql(status.split(","))+") ");
        }
        if(StringUtil.isNotBlank(tenantName)){
            sb.append(" and ( d.tenant_name like '%"+tenantName+"%' ");
            sb.append(" or d.power_station_code like '%"+tenantName+"%')");
        }
        sb.append("  ORDER BY e.create_time DESC ");
        return Db.find(sb.toString(),id);
    }

    public List<Record> getQualityStatisticsList(Map<String, String> map, LayuiPage page) {
        SqlBuilder sb=new SqlBuilder();
        sb.line("select a.quality_emp_name,SUM(CASE WHEN d.status <> 0 THEN 1 ELSE 0 END) as zjNum ,SUM(CASE WHEN d.accept_status <> 1 and d.status <> 3 THEN 1 ELSE 0 END) as zjzNum ");
        sb.line(",SUM(CASE WHEN accept_status = 1 THEN 1 END) as zjwcNum,SUM(CASE WHEN d.status = 3 THEN 1 END) as wfysNum ");
//        sb.line(",(select actual_capacity from crm_customer_entry where id in(CASE WHEN d.status <> 0 THEN d.entry_id ELSE 0 END))/1000 as zjCapacity ");
//        sb.line(",(select actual_capacity from crm_customer_entry where id in(CASE WHEN d.accept_status <> 1 and d.status <> 3 THEN d.entry_id ELSE 0 END))/1000 as zjzCapacity ");
//        sb.line(",(select actual_capacity from crm_customer_entry where id in(CASE WHEN d.accept_status = 1 THEN d.entry_id ELSE 0 END))/1000 as zjwcCapacity");
//        sb.line(",(select actual_capacity from crm_customer_entry where id in(CASE WHEN  d.status = 3 THEN d.entry_id ELSE 0 END))/1000 as wfysCapacity");
        sb.line(",concat(ROUND(count(CASE WHEN d.status = 3 THEN 1 END) * 100 / COUNT(d.id)),'%') AS prop ");
        sb.line(",DATE_FORMAT(d.dispatch_time,'%Y-%m') as dispatch_time from crm_entry_quality_acceptance_detail d ");
        sb.line(" LEFT JOIN crm_entry_quality_acceptance a on a.id = d.main_id");
        sb.line("where d.status <> 0 and (d.emp_user_id is not null or d.emp_user_id <> '') and a.type = ?",map.get("type"));
        getCommonPageCondition(map,sb);
        sb.line("GROUP BY d.emp_user_id ");
        if (page != null) {
            sb.limit(page.getPage(), page.getLimit());
        }
//        return Db.find(sb.build(), sb.params());
        List<Record> records = Db.find(sb.build(), sb.params());
        SqlBuilder zjCapacitySb=new SqlBuilder();
        zjCapacitySb.line("select a.quality_emp_name,ROUND(sum(e.actual_capacity)/1000,3) as capacity from crm_entry_quality_acceptance_detail d");
        zjCapacitySb.line(" LEFT JOIN crm_entry_quality_acceptance a on a.id = d.main_id");
        zjCapacitySb.line(" LEFT JOIN crm_customer_entry e on e.id = d.entry_id ");
        zjCapacitySb.line("where d.status <> 0 and (d.emp_user_id is not null or d.emp_user_id <> '') and a.type = ?",map.get("type"));
        getCommonPageCondition(map,zjCapacitySb);
        zjCapacitySb.line("GROUP BY d.emp_user_id ");
        if (page != null) {
            zjCapacitySb.limit(page.getPage(), page.getLimit());
        }
        List<Record> recordsZj = Db.find(zjCapacitySb.build(), zjCapacitySb.params());
        SqlBuilder zjzCapacitySb=new SqlBuilder();
        zjzCapacitySb.line("select a.quality_emp_name,ROUND(sum(e.actual_capacity)/1000,3) as capacity from crm_entry_quality_acceptance_detail d");
        zjzCapacitySb.line(" LEFT JOIN crm_entry_quality_acceptance a on a.id = d.main_id");
        zjzCapacitySb.line(" LEFT JOIN crm_customer_entry e on e.id = d.entry_id ");
        zjzCapacitySb.line("where  d.accept_status <> 1 and d.status not in('0','3') and (d.emp_user_id is not null or d.emp_user_id <> '') and a.type = ?",map.get("type"));
        getCommonPageCondition(map,zjzCapacitySb);
        zjzCapacitySb.line("GROUP BY d.emp_user_id ");
        if (page != null) {
            zjzCapacitySb.limit(page.getPage(), page.getLimit());
        }
        List<Record> recordsZjz = Db.find(zjzCapacitySb.build(), zjzCapacitySb.params());
        SqlBuilder zjwcCapacitySb=new SqlBuilder();
        zjwcCapacitySb.line("select a.quality_emp_name,ROUND(sum(e.actual_capacity)/1000,3) as capacity from crm_entry_quality_acceptance_detail d");
        zjwcCapacitySb.line(" LEFT JOIN crm_entry_quality_acceptance a on a.id = d.main_id");
        zjwcCapacitySb.line(" LEFT JOIN crm_customer_entry e on e.id = d.entry_id ");
        zjwcCapacitySb.line("where d.accept_status = 1 and d.status <> 0 and (d.emp_user_id is not null or d.emp_user_id <> '') and a.type = ?",map.get("type"));
        getCommonPageCondition(map,zjwcCapacitySb);
        zjwcCapacitySb.line("GROUP BY d.emp_user_id ");
        if (page != null) {
            zjwcCapacitySb.limit(page.getPage(), page.getLimit());
        }
        List<Record> recordsZjwc= Db.find(zjwcCapacitySb.build(), zjwcCapacitySb.params());
        SqlBuilder wfysCapacitySb=new SqlBuilder();
        wfysCapacitySb.line("select a.quality_emp_name,ROUND(sum(e.actual_capacity)/1000,3) as capacity from crm_entry_quality_acceptance_detail d");
        wfysCapacitySb.line(" LEFT JOIN crm_entry_quality_acceptance a on a.id = d.main_id");
        wfysCapacitySb.line(" LEFT JOIN crm_customer_entry e on e.id = d.entry_id ");
        wfysCapacitySb.line("where  d.status = 3 and (d.emp_user_id is not null or d.emp_user_id <> '') and a.type = ?",map.get("type"));
        getCommonPageCondition(map,wfysCapacitySb);
        wfysCapacitySb.line("GROUP BY d.emp_user_id ");
        if (page != null) {
            wfysCapacitySb.limit(page.getPage(), page.getLimit());
        }
        List<Record> recordsWfys= Db.find(wfysCapacitySb.build(), wfysCapacitySb.params());
        records.forEach(record -> {
            recordsZj.forEach(recordZj -> {
                if(record.getStr("quality_emp_name").equals(recordZj.getStr("quality_emp_name"))){
                    record.set("zjCapacity",recordZj.getBigDecimal("capacity"));
                }
            });
            recordsZjz.forEach(recordZj -> {
                if(record.getStr("quality_emp_name").equals(recordZj.getStr("quality_emp_name"))){
                    record.set("zjzCapacity",recordZj.getBigDecimal("capacity"));
                }
            });
            recordsZjwc.forEach(recordZj -> {
                if(record.getStr("quality_emp_name").equals(recordZj.getStr("quality_emp_name"))){
                    record.set("zjwcCapacity",recordZj.getBigDecimal("capacity"));
                }
            });
            recordsWfys.forEach(recordZj -> {
                if(record.getStr("quality_emp_name").equals(recordZj.getStr("quality_emp_name"))){
                    record.set("wfysCapacity",recordZj.getBigDecimal("capacity"));
                }
            });
        });
        return records;
    }

    public void getCommonPageCondition(Map<String,String> param,SqlBuilder builder){
        if (StringUtil.checkParamsValid(param.get("qualityEmpId"))) {
            builder.line(" and a.quality_emp_id = ?", param.get("qualityEmpId"));
        }
        if (StringUtil.checkParamsValid(param.get("dispatchTime"))) {
            builder.line(" and d.dispatch_time like '%" + param.get("dispatchTime") + "%'");
        }else {
            builder.line(" and d.dispatch_time like '%" + DateUtils.getYear()+"-"+DateUtils.getMonth() + "%'");
        }
    }

    public Long getQualityStatisticsListCount(Map<String, String> map) {
        SqlBuilder sb=new SqlBuilder();
        sb.line("select COUNT(DISTINCT d.emp_user_id) from crm_entry_quality_acceptance_detail d ");
        sb.line(" LEFT JOIN crm_entry_quality_acceptance a on a.id = d.main_id");
        sb.line("where d.status <> 0 and (d.emp_user_id is not null or d.emp_user_id <> '') and a.type = ?",map.get("type"));
        getCommonPageCondition(map,sb);
        return Db.queryLong(sb.build(),sb.params());
    }

    public List<Record> getEntryNoQualityByEntryIds(List<String> entryIds){
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT e.id AS entry_id,e.power_station_code,e.trader_name,e.distributor_id AS trader_id,e.tenant_name,e.province,e.city,e.area ,e.trader_name,e.create_trader_id ");
        sb.append(" FROM crm_customer_entry e ");
        sb.append(" WHERE e.id IN ("+StringUtil.joinInSql(entryIds)+") ");
        sb.append(" AND NOT EXISTS(SELECT d.id FROM crm_entry_quality_acceptance_detail d LEFT JOIN crm_entry_quality_acceptance a ON d.main_id=a.id AND a.type='1' WHERE d.entry_id=e.id ) ");
        return Db.find(sb.toString());
    }


}
