package com.nokia.tsl_data.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

/**
 * tsl_data.avg_duration_v3 表
 */
@Mapper
public interface AvgDurationMapperV3 {

    /**
     * 插入上月的平均处理时长
     */
    @Insert("with t1 as (select sdd.real_name,kfsn, (extract(epoch from to_timestamp(kf_file_time, 'YYYY-MM-DD HH24:MI:SS'))"
            + " - extract(epoch from to_timestamp(kd_accept_time, 'YYYY-MM-DD HH24:MI:SS'))) / 3600 as cost_time\n"
            + "from tsl_data.work_flow_basic_data wfbd, tsl_data.sys_data_dictionary sdd \n" + //
            " where wfbd.city_id = sdd.nick_code and kf_file_time is not null" +
            " and re_is_status_id != '06678b79185349b5bf0c24490a978fbb'\n"
            + "and to_timestamp(wfbd.kf_file_time, 'yyyy-mm-dd hh24:mi:ss') >= to_timestamp(concat(#{month_id}, '01000000'), 'yyyymmddhh24miss') "
            + " and to_timestamp(wfbd.kf_file_time, 'yyyy-mm-dd hh24:mi:ss') <= " +
            " (to_timestamp(concat(#{month_id}, '01000000'), 'yyyymmddhh24miss') + interval '1 month'))," +
            " t2 as (select real_name as city, avg(cost_time) as avg_duration\n" + //
            " from t1 group by real_name order by real_name), " +
            " t3 as (select '全省' as city, avg(cost_time) as avg_duration from t1)\n" + //
            " insert into tsl_data.avg_duration_v3 (month_id, city_name, avg_duration) " +
            " select #{month_id} as month_id, city as city_name, avg_duration from t2" +
            " union select #{month_id} as month_id, city as city_name, avg_duration from t3")
    void insertOldTsDurationForMonth(String monthId);

    /**
     * 查询历史处理时长
     */
    @Select("select city_name, avg_duration from tsl_data.avg_duration_v3 where month_id = #{monthId}")
    List<Map<String, Object>> selectOldTsDurationForMonth(String monthId);
}
