package com.sifang.modules.task;


import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.quality.dao.CrmInspectionRatioSetDao;
import com.sifang.modules.quality.service.CrmEntryQualityAcceptanceService;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class QualityAcceptanceCreateTask {

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


    @Autowired
    CrmInspectionRatioSetDao ratioSetDao;

    @Autowired
    CrmEntryQualityAcceptanceService acceptanceService;

    //每个月安装验收通过电站作为基数（之前做过巡检的电站剔除），随机抽取每个代理商20%的比例，每个月1号到待派单内，后台人员进行人工派单；
    //每月1号凌晨1点35分执行 ,生成巡检单
     @Scheduled(cron = "0 35 1 1 * ?")
    void monthCheckIfQualityAcceptanceCreate(){
        logger.info(">>>>>>>>monthCheckIfQualityAcceptanceCreate  定时任务开始:{}", DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
        long begin = System.currentTimeMillis();
        Record ratioSet=ratioSetDao.getRatioSet();
        if(ratioSet==null){
            return;
        }
        logger.info(">>>>monthCheckIfQualityAcceptanceCreate cycle:{} ",ratioSet.getStr("ratio"));
        //统计出哪些代理商电站
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT  COUNT(e.id) as totalCount,q.trader_id,e.province,e.city,e.area,e.trader_name ");
        sb.append(" FROM crm_entry_quality_seek_entry q  ");
        sb.append(" LEFT JOIN crm_customer_entry e  ON e.id=q.entry_id ");
        sb.append(" where q.if_sample='0' ");
        sb.append(" GROUP BY q.trader_id,e.area ");
        List<Record> listTraders= Db.find(sb.toString());
        logger.info(">>monthCheckIfQualityAcceptanceCreate  monthCheckIfQualityAcceptanceCreate.size:{}",listTraders.size());

        Date date=new Date();
        StringBuilder sb2=new StringBuilder();
        sb2.append("  SELECT s.id,e.trader_name, s.entry_id,s.check_accept_time,s.finish_accept_count,e.power_station_code,e.tenant_name,e.create_trader_id ");
        sb2.append(" ,e.province,e.city,e.area ");
        sb2.append(" FROM crm_entry_quality_seek_entry s  ");
        sb2.append(" LEFT JOIN crm_customer_entry e ON s.entry_id=e.id ");
        sb2.append("  WHERE s.trader_id=? AND e.province=? AND e.city=? AND e.area=?  AND s.if_sample='0' ORDER BY s.check_accept_time ASC limit ?");
        for(Record r:listTraders){
            //根据比例算出抽检数量
            BigDecimal ratioB=new BigDecimal(ratioSet.getStr("ratio"));//抽检比例
            //抽检的数量
            BigDecimal chouCount=(ratioB.multiply(new BigDecimal(r.getLong("totalCount")))).divide(new BigDecimal(100),0,BigDecimal.ROUND_UP);
            Integer sampleCount=Integer.valueOf(String.valueOf(chouCount));

            List<Record> entryList=Db.find(sb2.toString(),r.getStr("trader_id"),r.getStr("province"),r.getStr("city"),r.getStr("area"),sampleCount);
            if(entryList.isEmpty()){
                continue;
            }
            logger.info(">>>>>monthCheckIfQualityAcceptanceCreate  entryList.size:{},traderId:{},province:{},city:{},area:{} ",entryList.size(),r.getStr("trader_id"),r.getStr("province"),r.getStr("city"),r.getStr("area"));
            acceptanceService.saveXjdAcceptance(r,entryList,date,sampleCount);
            //改变crm_entry_quality_seek_entry 里面的状态
            List<String> ids=entryList.stream().map(re -> re.getStr("id")).collect(Collectors.toList());
            int successCot=Db.update("UPDATE  crm_entry_quality_seek_entry SET sample_time=NOW(),if_sample=1 WHERE id IN("+StringUtil.joinInSql(ids)+") ");
            logger.info(".everyDayCheckIfQualityAcceptanceCreate  successCot:{}",successCot);
        }

        long end = System.currentTimeMillis();
        logger.info("monthCheckIfQualityAcceptanceCreate 定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
    }


}
