package com.sifang.modules.task;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.Service.CustomerService;
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.List;

@Component
public class SendMergeMsgTask {
    private static final Logger logger = LoggerFactory.getLogger(SendMergeMsgTask.class);
    @Autowired
    private CustomerService customerService;

    @Scheduled(cron = "0 18 10 * * ?")//每天上午十点18分执行
    public void sendMergeMsg() {
        logger.info("SendMergeMsgTask is running...");
        List<Record> records = Db.find(" SELECT e.id,e.power_station_code ,e.mobile ,e.tenant_name as name , concat(e.province,e.city,e.area,e.address) as address" +
                " ,e.component_spec as spec,e.actual_capacity as total ,b.material_model as model , (e.actual_capacity /  e.component_spec) as num " +
                "from crm_customer_entry e " +
                "INNER JOIN crm_plan_material_entry m on e.id = m.entry_id " +
                "LEFT JOIN crm_supply_material b ON m.material_id = b.id "+
                "where e.`status` != 'b' and e.is_send_merge_msg = '0' and e.first_generation_time is not null  GROUP BY e.id ");
        logger.info("SendMergeMsgTask records size is {}", records.size());
        for (Record record : records) {
            try {
                String code = customerService.sendBwMsg(record.getStr("mobile"), record.getStr("name"), record.getStr("address"),
                        BigDecimal.valueOf(record.getDouble("num")).stripTrailingZeros().toPlainString(), record.getStr("spec"), record.getStr("model"), record.getBigDecimal("total").stripTrailingZeros().toPlainString());
                if ("200".equals(code)){
                    Db.update("update crm_customer_entry set is_send_merge_msg = '1' where id = ?", record.getStr("id"));
                }
            }catch (Exception e){
                logger.error("SendMergeMsgTask is error:{},powerStationCode:{}",e.getMessage(),record.getStr("power_station_code"));
            }
        }
        logger.info("SendMergeMsgTask is finished");
    }

}
