package com.sifang.modules.task;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.dao.CrmCustomerEntryDailyRecordDao;
import com.sifang.modules.customer.dao.CrmCustomerEntryProvinceLeaderInfoDao;
import com.sifang.modules.customer.entity.CrmCustomerEntryDailyRecord;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.SqlBuilder;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class DailyRecordTask {

    private static final Logger logger = LoggerFactory.getLogger(DailyRecordTask.class);
    @Autowired
    private CrmCustomerEntryProvinceLeaderInfoDao provinceLeaderInfoDao;
    @Autowired
    private CrmCustomerEntryDailyRecordDao dailyRecordDao;


    //删除指定日期的数据
    public void deleteDailyDateByDate(String date){
        Db.update(" delete from crm_customer_entry_daily_record where creat_time = ? ",date);
    }

    //统计日报数据  每日1点13分定时任务生成前一天的报表数据；
    @Scheduled(cron = "0 13 1 * * ?") //每天0点13分执行
    public void initDailyRecordList(){
        //获取前一天使日期
        Date newDate = new Date();
        String date = DateUtils.dateChangeDays(newDate, -1,"yyyy-MM-dd");
        String minDate = date+" 00:00:00";
        String maxDate = date+" 23:59:59";
        //获取本月日期
        String dateMonth = DateUtils.dateChangeDays(newDate, -1,"yyyy-MM");
        String dateMonthMin = dateMonth + "-01 00:00:00";
        String dateMonthMax = maxDate;
        //获取统计日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(newDate);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date previousDay = calendar.getTime();
        //先删除
        deleteDailyDateByDate(date);
        //统计每个省下面的数据
        logger.info("开始统计每个省下面的日报数据，统计日期:{}", date);
        initRecords(previousDay,minDate,maxDate,dateMonthMin,dateMonthMax);
    }
    //同步指定日期的日报
    public void syncDailyRecord(Date newDate){
        String date = DateUtils.formatDate(newDate, "yyyy-MM-dd");
        String minDate = date+" 00:00:00";
        String maxDate = date+" 23:59:59";
        //获取本月日期
        String dateMonth = DateUtils.formatDate(newDate,"yyyy-MM");
        String dateMonthMin = dateMonth + "-01 00:00:00";
        String dateMonthMax = maxDate;
        //先删除
        deleteDailyDateByDate(date);
        //统计每个省下面的数据
        logger.info("开始统计每个省下面的日报数据，统计日期:{}", date);
        initRecords(newDate, minDate, maxDate, dateMonthMin, dateMonthMax);
    }
    //统计数据
    public void initRecords(Date newDate, String minDate ,String maxDate ,String dateMonthMin ,String dateMonthMax){
//        List<Record> list = provinceLeaderInfoDao.findList();
        List<Record> list = Db.find(" select * from crm_customer_entry_province_leader_info ");
        for (Record record : list) {
            CrmCustomerEntryDailyRecord dailyRecord = new CrmCustomerEntryDailyRecord();
            String id = record.getStr("id");
            String province = record.getStr("province");
            dailyRecord.setProvinceRelId(id);
            dailyRecord.setCreatTime(newDate);
            //当日签约数量 signedCntDay
            BigDecimal signedCntDay = new BigDecimal(Db.queryLong("select count(1) from crm_trader where  status = '0' and province = ? and create_time >= ? and  create_time <= ? ", province, minDate, maxDate));
            dailyRecord.setSignedCntDay(signedCntDay);
            // 累计签约数量 cumSignedCnt
            BigDecimal cumSignedCnt = new BigDecimal(Db.queryLong("select count(1) from crm_trader where  status = '0' and province = ? ", province));
            dailyRecord.setCumSignedCnt(cumSignedCnt);
            // 有进件的签约数量signedCntWithApp  通过是否有进件时间来判断
            BigDecimal signedCntWithApp = new BigDecimal(Db.queryLong(" select count(1) from (select e.distributor_id from  crm_customer_entry e   LEFT JOIN crm_trader t on t.id = e.distributor_id " +
                    " where e.status <> 'b' and t.status = '0' and t.province = ?   and e.in_coming_time is not null GROUP BY e.distributor_id )m  ",province));
            dailyRecord.setSignedCntWithApp(signedCntWithApp);
            // 当日发货量shippedCntDay
            BigDecimal shippedCntDay = BigDecimal.ZERO;
            BigDecimal shippedCntDayNum = Db.queryBigDecimal("  SELECT sum(o.predict_amount)/1500000 as shippedCntDay from crm_supply_material_deliver_order o   left JOIN crm_trader t on t.id = o.trader_id  " +
                    " where o.`status` <> '0' and t.status = '0' and o.type in ('1','2','4','5') and t.province = ? and o.deliver_time >= ? and  o.deliver_time <= ? ", province, minDate, maxDate);
            if (shippedCntDayNum!=null){
                shippedCntDay = shippedCntDayNum;
            }
            dailyRecord.setShippedCntDay(shippedCntDay);
            // 本月发货量shippedCntMonth
            BigDecimal shippedCntMonth = BigDecimal.ZERO;
            BigDecimal shippedCntMonthNum = Db.queryBigDecimal("  SELECT sum(o.predict_amount)/1500000 as shippedCntDay from crm_supply_material_deliver_order o   left JOIN crm_trader t on t.id = o.trader_id  " +
                    " where o.`status` <> '0' and t.status = '0' and o.type in ('1','2','4','5') and t.province = ? and o.deliver_time >= ? and  o.deliver_time <= ? ", province, dateMonthMin, dateMonthMax);
            if (shippedCntMonthNum!=null){
                shippedCntMonth = shippedCntMonthNum;
            }
            dailyRecord.setShippedCntMonth(shippedCntMonth);
            // 当日进件数量appCntDay
            BigDecimal appCntDay = new BigDecimal(Db.queryLong(" SELECT COUNT(1) from crm_customer_entry e LEFT JOIN crm_trader t on t.id = e.distributor_id where e.status <> 'b' and t.status = '0' " +
                    " and t.province = ? and e.in_coming_time >= ? and  e.in_coming_time <= ? ", province, minDate, maxDate));
            dailyRecord.setAppCntDay(appCntDay);
            // 本月进件数量appCntMonth
            BigDecimal appCntMonth = new BigDecimal(Db.queryLong(" SELECT COUNT(1) from crm_customer_entry e LEFT JOIN crm_trader t on t.id = e.distributor_id where e.status <> 'b' and t.status = '0' " +
                    " and t.province = ? and e.in_coming_time >= ? and  e.in_coming_time <= ? ", province, dateMonthMin, dateMonthMax));
            dailyRecord.setAppCntMonth(appCntMonth);
            // 提交验工验收 当日安装量submittedDay 通过安装提交验收时间来统计
            BigDecimal submittedDay = BigDecimal.ZERO;
            BigDecimal submittedDayNum = Db.queryBigDecimal(" SELECT sum(e.actual_capacity)/1000000 as submittedDay from crm_customer_entry e LEFT JOIN crm_trader t on t.id = e.distributor_id where e.status <> 'b' and t.status = '0' " +
                    " and t.province = ? and e.install_audit_finish_time >= ? and  e.install_audit_finish_time <= ? ", province, minDate, maxDate);
            if (submittedDayNum!=null){
                submittedDay = submittedDayNum;
            }
            dailyRecord.setSubmittedDay(submittedDay);
            // 提交验工验收 本月安装量submittedMonth 通过安装提交验收时间来统计
            BigDecimal submittedMonth =BigDecimal.ZERO;
            BigDecimal submittedMonthNum = Db.queryBigDecimal(" SELECT sum(e.actual_capacity)/1000000 as submittedMonth  from crm_customer_entry e LEFT JOIN crm_trader t on t.id = e.distributor_id where e.status <> 'b' and t.status = '0' " +
                    " and t.province = ? and e.install_audit_finish_time >= ? and  e.install_audit_finish_time <= ? ", province, dateMonthMin, dateMonthMax);
            if (submittedMonthNum!=null){
                submittedMonth = submittedMonthNum;
            }
            dailyRecord.setSubmittedMonth(submittedMonth);
            // 终审通过 当日安装量finalApprovedDay 通过安装验收时间来统计
            BigDecimal finalApprovedDay = BigDecimal.ZERO;
            BigDecimal finalApprovedDayNum = Db.queryBigDecimal("  SELECT sum(e.actual_capacity)/1000000 as  finalApprovedDay  from crm_customer_entry e  LEFT JOIN crm_trader t on t.id = e.distributor_id  " +
                    " where e.status <> 'b' and t.status = '0'   and t.province = ? and e.install_accept_time >= ? and  e.install_accept_time <= ? ",province, minDate, maxDate);
            if (finalApprovedDayNum != null){
                finalApprovedDay =  finalApprovedDayNum;
            }
            dailyRecord.setFinalApprovedDay(finalApprovedDay);
            // 终审通过 本月安装量finalApprovedMonth 通过安装验收时间来统计
            BigDecimal finalApprovedMonth = BigDecimal.ZERO;
            BigDecimal finalApprovedMonthNum = Db.queryBigDecimal("  SELECT sum(e.actual_capacity)/1000000 as  finalApprovedMonth  from crm_customer_entry e  LEFT JOIN crm_trader t on t.id = e.distributor_id " +
                    " where e.status <> 'b' and t.status = '0'   and t.province = ? and e.install_accept_time >= ? and  e.install_accept_time <= ? ",province, dateMonthMin, dateMonthMax);
            if (finalApprovedMonthNum != null){
                finalApprovedMonth = finalApprovedMonthNum;
            }
            dailyRecord.setFinalApprovedMonth(finalApprovedMonth);
            // 并网量 终审通过 当日并网量gridConnectedDay  通过投放通过时间来统计
            BigDecimal gridConnectedDay = BigDecimal.ZERO;
            BigDecimal gridConnectedDayNum = Db.queryBigDecimal(" SELECT sum(e.actual_capacity)/1000000 as  gridConnectedDay  from crm_customer_entry e   LEFT JOIN crm_trader t on t.id = e.distributor_id " +
                    " left join crm_customer_incoming_application a on a.entry_id = e.id and a.if_delete = '0'  where e.status <> 'b' and t.status = '0' and t.province = ? " +
                    " and a.payment_finish_time >= ? and  a.payment_finish_time <= ?   ", province, minDate, maxDate);
            if (gridConnectedDayNum != null){
                gridConnectedDay = gridConnectedDayNum;
            }
            dailyRecord.setGridConnectedDay(gridConnectedDay);
            // 并网量 终审通过 本月并网量gridConnectedMonth
            BigDecimal gridConnectedMonth = BigDecimal.ZERO;
            BigDecimal gridConnectedMonthNum = Db.queryBigDecimal(" SELECT sum(e.actual_capacity)/1000000 as  gridConnectedDay  from crm_customer_entry e   LEFT JOIN crm_trader t on t.id = e.distributor_id " +
                    " left join crm_customer_incoming_application a on a.entry_id = e.id and a.if_delete = '0'  where e.status <> 'b' and t.status = '0' and t.province = ? " +
                    " and a.payment_finish_time >= ? and  a.payment_finish_time <= ?   ", province, dateMonthMin, dateMonthMax);
            if (gridConnectedMonthNum != null){
                gridConnectedMonth = gridConnectedMonthNum;
            }
            dailyRecord.setGridConnectedMonth(gridConnectedMonth);

            Db.update("INSERT INTO `crm_customer_entry_daily_record`(`id`, `province_rel_id`, `creat_time`, `signed_cnt_day`, `cum_signed_cnt`, `signed_cnt_with_app`, `shipped_cnt_day`, `shipped_cnt_month`, `app_cnt_day`, `app_cnt_month`, `submitted_day`, `submitted_month`, `final_approved_day`, `final_approved_month`, `grid_connected_day`, `grid_connected_month`) " +
                    " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); ",IdGen.uuid(),id,newDate,signedCntDay,cumSignedCnt,signedCntWithApp,shippedCntDay,shippedCntMonth,appCntDay,appCntMonth,submittedDay,submittedMonth,finalApprovedDay,finalApprovedMonth,gridConnectedDay,gridConnectedMonth);
//            dailyRecordDao.saveRecord(dailyRecord);
        }


    }

}
