package com.sifang.modules.task;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class WeeklyRecordTask {

    private static final Logger logger = LoggerFactory.getLogger(WeeklyRecordTask.class);


    //删除指定日期的数据
    public void deleteWeeklyDateByDate(String startDate,String endDate){
        Db.update(" delete from crm_customer_entry_weekly_record where creat_time_sta = ? and creat_time_end = ? ",startDate,endDate);
    }

    //统计周报数据  每周一1点15分统计上周的报表数据
    @Scheduled(cron = "0 15 1 * * 1")//每周一1点15分执行
    public void initWeeklyRecordList(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY); // 设置每周的第一天为星期一
        calendar.add(Calendar.WEEK_OF_YEAR, -1); // 减去一周
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 设置为星期一
        Date lastWeekStartDate = calendar.getTime();
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // 设置为星期日
        Date lastWeekEndDate = calendar.getTime();
        String sta = sdf.format(lastWeekStartDate);
        String end = sdf.format(lastWeekEndDate);
        String minDate = sta +" 00:00:00";
        String maxDate = end+" 23:59:59";
        //获取本月日期
        String dateMonth = DateUtils.formatDate(lastWeekEndDate,"yyyy-MM");
        String dateMonthMin = dateMonth + "-01 00:00:00";
        String dateMonthMax = maxDate;
        //获取年度日期
        String dateYear = DateUtils.formatDate(lastWeekEndDate,"yyyy");
        String dateYearMin = dateYear + "-01-01 00:00:00";
        String dateYearMax = maxDate;
        //先删除
        deleteWeeklyDateByDate(sta,end);
        //统计每个省下面的数据
        logger.info("开始统计周报数据，统计日期：{} ,统计月份：{},统计年份：{}", minDate+"~"+maxDate ,dateMonthMin+"~"+dateMonthMax,dateYearMin+"~"+dateYearMax);
        initRecords(minDate,maxDate,dateMonthMin,dateMonthMax,dateYearMin,dateYearMax);
    }
    //同步指定日期的周报
    public void syncWeeklyRecord(String startDate,String endDate){
        String minDate = startDate+" 00:00:00";
        String maxDate = endDate+" 23:59:59";
        //获取本月日期
        Date date = DateUtils.parseDate(endDate);
        String dateMonth = DateUtils.formatDate(date,"yyyy-MM");
        String dateMonthMin = dateMonth + "-01 00:00:00";
        String dateMonthMax = maxDate;
        //获取年度日期
        String dateYear = DateUtils.formatDate(date,"yyyy");
        String dateYearMin = dateYear + "-01-01 00:00:00";
        String dateYearMax = maxDate;
        //先删除
        deleteWeeklyDateByDate(startDate,endDate);
        //统计每个省下面的数据
        logger.info("同步指定日期的周报，统计日期:{}，统计月份：{},统计年份：{}",  minDate+"~"+maxDate, dateMonthMin+"~"+dateMonthMax,dateYearMin+"~"+dateYearMax);
        initRecords(minDate, maxDate, dateMonthMin, dateMonthMax, dateYearMin, dateYearMax);
    }
    //统计数据
    public void initRecords(String minDate ,String maxDate ,String dateMonthMin ,String dateMonthMax,String dateYearMin,String dateYearMax){
        List<Record> list = Db.find("  select * from crm_customer_entry_province_leader_info ");
        for (Record record : list ) {
            String id = record.getStr("id");
            String province = record.getStr("province");
            //上周完成数量 signedCntWeek
            BigDecimal signedCntWeek = new BigDecimal(Db.queryLong("select count(1) from crm_trader where  status = '0' and province = ? and create_time >= ? and  create_time <= ? ", province, minDate, maxDate));
            // 累计数量 cumSignedCnt
            BigDecimal cumSignedCnt = new BigDecimal(Db.queryLong("select count(1) from crm_trader where  status = '0' and province = ? ", province));
            //上周目标  shippedCntWeekTarget
            BigDecimal  shippedCntWeekTarget = null;
            // 上周已发 shippedCntWeek
            BigDecimal shippedCntWeek = BigDecimal.ZERO;
            BigDecimal shippedCntWeekNum = Db.queryBigDecimal("  SELECT sum(o.predict_amount)/1500000 as shippedCntWeek 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 (shippedCntWeekNum!=null){
                shippedCntWeek = shippedCntWeekNum;
            }
            //推进率 shippedCntWeekPropRate
            BigDecimal shippedCntWeekPropRate = null;
            // 本月发货量shippedCntMonth
            BigDecimal shippedCntMonth = BigDecimal.ZERO;
            BigDecimal shippedCntMonthNum = Db.queryBigDecimal("  SELECT sum(o.predict_amount)/1500000 as shippedCntMonth 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;
            }
            // 年度发货量 shippedCntYear
            BigDecimal shippedCntYear = BigDecimal.ZERO;
            BigDecimal shippedCntYearNum = Db.queryBigDecimal("  SELECT sum(o.predict_amount)/1500000 as shippedCntYear 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, dateYearMin, dateYearMax);
            if (shippedCntYearNum!=null){
                shippedCntYear = shippedCntYearNum;
            }
            // 上周进件数量appCntWeek
            BigDecimal appCntWeek = 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));
            // 本月进件数量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));
            //年度进件量 appCntYear
            BigDecimal appCntYear = 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, dateYearMin, dateYearMax));
            // 提交验工验收 上周安装量submittedWeek 通过安装提交验收时间来统计
            BigDecimal submittedWeek = BigDecimal.ZERO;
            BigDecimal submittedWeekNum = Db.queryBigDecimal(" SELECT sum(e.actual_capacity)/1000000 as submittedWeek 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 (submittedWeekNum!=null){
                submittedWeek = submittedWeekNum;
            }
            //提交验工验收 本月目标 submittedMonthTarget
            BigDecimal submittedMonthTarget = null;
            // 提交验工验收 本月安装量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;
            }
            // 提交验工验收 推进率 submittedMonthPropRate
            BigDecimal submittedMonthPropRate = null;
            // 提交验工验收 年度安装量 submittedYear
            BigDecimal submittedYear =BigDecimal.ZERO;
            BigDecimal submittedYearNum = Db.queryBigDecimal(" SELECT sum(e.actual_capacity)/1000000 as submittedYear  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, dateYearMin, dateYearMax);
            if (submittedYearNum!=null){
                submittedYear = submittedYearNum;
            }
            // 终审通过 上周安装量finalApprovedWeek 通过安装验收时间来统计
            BigDecimal finalApprovedWeek = BigDecimal.ZERO;
            BigDecimal finalApprovedWeekNum = Db.queryBigDecimal("  SELECT sum(e.actual_capacity)/1000000 as  finalApprovedWeek  from crm_customer_entry e  LEFT JOIN crm_trader t on t.id = e.distributor_id  LEFT JOIN crm_accepting_report p on p.id = e.receiving_report_id " +
                    " where e.status <> 'b' and t.status = '0'   and t.province = ? and p.fix_accept_time >= ? and  p.fix_accept_time <= ? ",province, minDate, maxDate);
            if (finalApprovedWeekNum != null){
                finalApprovedWeek =  finalApprovedWeekNum;
            }
            // 终审通过 本月安装量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  LEFT JOIN crm_accepting_report p on p.id = e.receiving_report_id " +
                    " where e.status <> 'b' and t.status = '0'   and t.province = ? and p.fix_accept_time >= ? and  p.fix_accept_time <= ? ",province, dateMonthMin, dateMonthMax);
            if (finalApprovedMonthNum != null){
                finalApprovedMonth = finalApprovedMonthNum;
            }
            // 终审通过 年度安装量 finalApprovedYear 通过安装验收时间来统计
            BigDecimal finalApprovedYear = BigDecimal.ZERO;
            BigDecimal finalApprovedYearNum = Db.queryBigDecimal("  SELECT sum(e.actual_capacity)/1000000 as  finalApprovedYear  from crm_customer_entry e  LEFT JOIN crm_trader t on t.id = e.distributor_id  LEFT JOIN crm_accepting_report p on p.id = e.receiving_report_id " +
                    " where e.status <> 'b' and t.status = '0'   and t.province = ? and p.fix_accept_time >= ? and  p.fix_accept_time <= ? ",province, dateYearMin, dateYearMax);
            if (finalApprovedYearNum != null){
                finalApprovedYear = finalApprovedYearNum;
            }
            // 并网量 终审通过 本周并网量gridConnectedWeek  通过投放通过时间来统计
            BigDecimal gridConnectedWeek = BigDecimal.ZERO;
            BigDecimal gridConnectedWeekNum = Db.queryBigDecimal(" SELECT sum(e.actual_capacity)/1000000 as  gridConnectedWeek  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 (gridConnectedWeekNum != null){
                gridConnectedWeek = gridConnectedWeekNum;
            }
            // 并网量 终审通过 本月并网量gridConnectedMonth
            BigDecimal gridConnectedMonth = BigDecimal.ZERO;
            BigDecimal gridConnectedMonthNum = Db.queryBigDecimal(" SELECT sum(e.actual_capacity)/1000000 as  gridConnectedMonth  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;
            }
            // 并网量 终审通过 年度并网量 gridConnectedYear
            BigDecimal gridConnectedYear = BigDecimal.ZERO;
            BigDecimal gridConnectedYearNum = Db.queryBigDecimal(" SELECT sum(e.actual_capacity)/1000000 as  gridConnectedYear  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, dateYearMin, dateYearMax);
            if (gridConnectedYearNum != null){
                gridConnectedYear = gridConnectedYearNum;
            }
            Db.update(" INSERT INTO `crm_customer_entry_weekly_record`(`id`, `province_rel_id`, `creat_time_sta`, `creat_time_end`, `signed_cnt_week`, `cum_signed_cnt`, `shipped_cnt_week`, `shipped_cnt_week_target`, " +
                    " `shipped_cnt_week_prop_rate`, `shipped_cnt_month`, `shipped_cnt_year`, `app_cnt_week`, `app_cnt_month`, `app_cnt_year`, `submitted_week`, `submitted_month_target`, `submitted_month`, `submitted_month_prop_rate`, " +
                    " `submitted_year`, `final_approved_week`, `final_approved_month`, `final_approved_year`, `grid_connected_week`, `grid_connected_month`, `grid_connected_year`) " +
                    "  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " ,IdGen.uuid(),id,minDate,maxDate,signedCntWeek,cumSignedCnt,shippedCntWeek,null,
                    null,shippedCntMonth,shippedCntYear,appCntWeek,appCntMonth,appCntYear,submittedWeek,null,submittedMonth,null,
                    submittedYear,finalApprovedWeek,finalApprovedMonth,finalApprovedYear,gridConnectedWeek,gridConnectedMonth,gridConnectedYear);
        }
    }

}
