package com.zcxk.charge.xxl.jobs;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zcxk.charge.api.vo.MeterCountVo;
import com.zcxk.charge.api.vo.MonthRevenueEntityVo;
import com.zcxk.charge.core.dao.RevenueMapper;
import com.zcxk.charge.core.entity.MonthRevenueEntity;
import com.zcxk.core.common.util.BeanCopyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Calendar;

/**
 * @author Administrator
 * @create 2020-05-06
 */
@Slf4j
@Component
public  class SyncMeterCountJob implements Serializable {

    private static final long serialVersionUID = 3336891083300321324L;

    @Resource
    private RevenueMapper revenueMapper;

    @Resource
    private RestTemplate restTemplate;

    @Value("${http_pool.meterRequesturl}")
    private  String meterRequestUrl;

    @XxlJob("syncMeterCountJob")
    public ReturnT<String> execute(String string) {
        try{
            log.info("同步水表数量执行开始");
            syncMeterCount();
            log.info("同步水表数量执行结束");
        }catch (Exception e){
            e.printStackTrace();
            log.info("同步水表数量执行异常，{}", e.getMessage());
        }
        return ReturnT.SUCCESS;
    }

    public void syncMeterCount() {
        MeterCountVo meterCountDto = restTemplate.getForObject(meterRequestUrl, MeterCountVo.class);
        if (meterCountDto.getStatus() == 0) {
            for (MonthRevenueEntityVo monthRevenueEntity : meterCountDto.getData()) {
                // 查询当月是否有数据 有就更新 没有就插入
                Integer count =revenueMapper.isExistThisMonthRevenue(monthRevenueEntity.getTenantId());
                if (count==0) {
                    Calendar thisMonthFirstDateCal = Calendar.getInstance();
                    thisMonthFirstDateCal.set(Calendar.DAY_OF_MONTH, 1);
                    monthRevenueEntity.setCollectDate(thisMonthFirstDateCal.getTime());
                    monthRevenueEntity.setCompanyOrgId(revenueMapper.selectCompanyIdByTenant(monthRevenueEntity.getTenantId()));
                    MonthRevenueEntity entity = new MonthRevenueEntity();
                    BeanCopyUtils.copyProperties(monthRevenueEntity, entity, MonthRevenueEntity.class);
                    revenueMapper.insert(entity);
                } else {
                    MonthRevenueEntity entity = new MonthRevenueEntity();
                    BeanCopyUtils.copyProperties(monthRevenueEntity, entity, MonthRevenueEntity.class);
                    revenueMapper.update(entity);
                }
            }
        }
    }

}