package com.gyee.frame.service;

import com.gyee.frame.common.spring.InitialRunner;
import com.gyee.frame.model.custom.DataVo;
import com.gyee.frame.util.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

@Service
public class MttrAndMtbfService {

    @Resource
    private JdbcTemplate jdbcTemplate;
    public String queryMMCurrentMonth(String wpid) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");

        Calendar cal = Calendar.getInstance();

        String rq = sdf.format(cal.getTime());

        int day = cal.get(Calendar.DAY_OF_MONTH);


        DataVo vo = queryStopDataCurrentMonth(rq,wpid);
        int count = vo.getIvalue1();
        double gzsj = vo.getDvalue1();

        int fjnum =0;
        if(wpid.equals("0"))
        {
             fjnum = InitialRunner.wtls.size();
        }else if(InitialRunner.wp_wtmap.containsKey(wpid))
        {
            fjnum = InitialRunner.wp_wtmap.get(wpid).size();
        }


        // 日历小时
        double dayhours = day * 24;

        double mtbf = count == 0 ? 0 : dayhours * fjnum / count;// 平均间隔时间
        double mttr = count == 0 ? 0 : gzsj / count;

        return StringUtils.round(mtbf,2) + "_" + StringUtils.round(mttr,2);
    }

    private DataVo queryStopDataCurrentMonth(String rq,String wpid) {
        StringBuilder sb = new StringBuilder();
        sb.append("select sum(cs) cs,sum(sssj) sj from MTTRMTBF where rq='");
        sb.append(rq).append("'");
        if(StringUtils.isNotEmpty(wpid) && !wpid.equals("0"))
        {
            sb.append(" and windpowerstationid='").append(wpid).append("'");
        }

        List<DataVo> list = jdbcTemplate.query(String.valueOf(sb),
                new RowMapper<DataVo>() {

                    @Override
                    public DataVo mapRow(ResultSet rs, int arg1)
                            throws SQLException {
                        DataVo vo = new DataVo();
                        vo.setIvalue1(rs.getInt("cs"));//
                        vo.setDvalue1(rs.getDouble("sj"));
                        return vo;
                    }

                });
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }
}
