package mobvista.dmp.datasource.age.mapreduce;

import com.google.common.collect.Maps;
import mobvista.dmp.util.MRUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.GzipCodec;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * Created by liushaui on 2017/2/16 0016.
 */
public class CalcPackageAgeMR {
    public static void main(String[] args) throws ClassNotFoundException, IOException, InterruptedException {

        Configuration conf = new Configuration();
        conf.set("mapreduce.map.speculative", "true");
        conf.set("mapreduce.reduce.speculative", "true");
        conf.set("mapreduce.task.io.sort.mb", "500");
        conf.set("mapreduce.reduce.java.opts", "-Xmx1536m");
        conf.set("mapreduce.reduce.memory.mb", "2048");
        conf.set("mapreduce.reduce.shuffle.parallelcopies", "50");
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();

        Job job = Job.getInstance(conf, "CalcPackageAgeMR");
        FileOutputFormat.setCompressOutput(job, true);
        FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class);
        job.setJarByClass(CalcPackageAgeMR.class);

        job.setMapperClass(CalcPackageYearMapper.class);

        job.setReducerClass(CalcPackageYearReducer.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
        FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));

        System.exit(job.waitForCompletion(true) ? 0 : 1);

    }

    public static class CalcPackageYearMapper extends Mapper<LongWritable, Text, Text, Text> {
        Text outKey = new Text();
        Text outValue = new Text();

        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] fields = MRUtils.SPLITTER.split(line, -1);
            if (fields.length != 4) {
                return;
            }
            String[] packages = Util.wellSplit.split(fields[1], -1);//#
            String[] sex = Util.dollarSplit.split(fields[2], -1);//$
            for (String pack : packages) {
                if (pack.length() == 0) {
                    continue;
                }
                for (String x : sex) {
                    outKey.set(pack);
                    outValue.set(x);
                    context.write(outKey, outValue);
                }
            }
        }
    }

    public static class CalcPackageYearReducer extends Reducer<Text, Text, Text, Text> {

        Text outValue = new Text();

        public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            StringBuilder value = new StringBuilder();
            Map<String, Integer> ageNum = Maps.newHashMap();
            int inNum = 0;  //总的数量
            int valid = 0;  //有年龄标签的数量
            double maxRatio = 0.0;
            for (Text val : values) {
                String line = val.toString();
                String pack = Util.wellSplit.split(line, -1)[0];//#

                Integer sum = ageNum.get(pack);
                if (sum == null) {
                    sum = 0;
                }
                ageNum.put(pack, sum + 1);
                if (!pack.equals("null")) {
                    valid += 1;//有年龄标签就+1
                }
                inNum += 1;//不管有没有年龄标签都+1
            }

            Set<String> set = ageNum.keySet();
            for (String name : set) {
                if (name.equals("null")) {
                    continue;
                }
                int num = ageNum.get(name);
                double abnRatio = 0.0;
                if (valid != 0) {
                    abnRatio = (double) num / valid;
                }
                if (abnRatio > maxRatio) {
                    maxRatio = abnRatio;
                }
                value.append("|"); //每个包下的年龄标签拼接
                value.append(name);
                value.append(":");
                value.append(abnRatio);
            }
            if (value.length() == 0) {//当没有年龄标签时
                value.append("0.0");
            }
            outValue.set(MRUtils.JOINER.join(inNum,//总人数
                    valid,//有年龄标签的人数
                    maxRatio,//各个年龄段最大的比例
                    value//年龄段与比例
            ));
            context.write(key, outValue);
        }

    }
}


