package com.aliyun.odps.spark.examples.makedata

import org.apache.spark.sql.SparkSession
import com.aliyun.odps.TableSchema
import com.aliyun.odps.data.Record
import com.aliyun.odps.spark.examples.myUtils.{MyDateUtils, MyHdfsUtils, ParamUtils, env}
import examples.dataloader.RequestContextOffline
import examples.dataloader.OfflineVlogShareLRFeatureExtractor
import org.apache.hadoop.io.compress.GzipCodec

import scala.collection.JavaConversions._

object makedata_01_readtable2hdfs {
  def main(args: Array[String]) {
    val spark = SparkSession
      .builder()
      .appName(this.getClass.getName)
      .getOrCreate()
    val sc = spark.sparkContext

    // 1 读取参数
    val param = ParamUtils.parseArgs(args)
    val partitionPrefix = param.getOrElse("partitionPrefix", "dt=")
    val tablePart = param.getOrElse("tablePart", "64").toInt
    val beginStr = param.getOrElse("beginStr", "20230101")
    val endStr = param.getOrElse("endStr", "20230101")
    val savePath = param.getOrElse("savePath", "")
    // /dw/recommend/model/share_ratio_samples/


    // 2 读取odps+表信息
    val odpsOps = env.getODPS(sc)
    val project = "loghubods"
    val table = "alg_recsys_view_sample"

    // 3 循环执行数据生产
    val dateRange = MyDateUtils.getDateRange(beginStr, endStr)
    for (date <- dateRange) {
      val partition = partitionPrefix + date
      println("执行partiton:" + partition)
      val odpsData = odpsOps.readTable(project = project,
        table = table,
        partition = partition,
        transfer = func,
        numPartition = tablePart)
      val hdfsPath = savePath + "/" + partition
      if (hdfsPath.nonEmpty && hdfsPath.startsWith("/dw/recommend/model/")){
        MyHdfsUtils.delete_hdfs_path(hdfsPath)
        odpsData.saveAsTextFile(hdfsPath, classOf[GzipCodec])
        println("数据写入完成:" + hdfsPath)
        println("数据量:" + odpsData.count())
      }else{
        println("路径不合法， 无法写入:" + hdfsPath)
      }

    }
  }

  def func(record: Record, schema: TableSchema): String = {
    singleParse(record)
  }

  def singleParse(record: Record): String = {
    //1 处理标签
    val label: String = record.getString("share_ornot")
    val newLabel = if ("1".equals(label)) "0" else "1"
    //2 处理特征
    val reqContext: RequestContextOffline = new RequestContextOffline()
    reqContext.putUserFeature(record)
    reqContext.putItemFeature(record)
    reqContext.putSceneFeature(record)
    val bytesFeatureExtractor = new OfflineVlogShareLRFeatureExtractor()
    bytesFeatureExtractor.makeFeature(reqContext.featureMap)
    val featureMap = bytesFeatureExtractor.featureMap
    newLabel + "\t" + featureMap.entries().map(r => r.getValue.getIdentifier + ":1").mkString("\t")
  }


}