package com.reyun.controller.manage;

import com.reyun.dic.ConfigEnumType;
import com.reyun.exception.TipException;
import com.reyun.service.ConfigParamService;
import com.reyun.service.IOpenApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * description:
 *
 * @author nolan
 * @date 13/09/2017
 */
@Controller
@RequestMapping("openapi")
public class MngOpenApiController
{
    @Autowired
    private IOpenApiService iOpenApiService;

    @Autowired
    private ConfigParamService configParamService;

    @RequestMapping(value = "/toutiao", method = RequestMethod.GET)
    public ResponseEntity<String> toutiaoDetail(@RequestParam String ds, @RequestParam String token)
    {
        String tokenValue = configParamService.getConfigParamByKey(ConfigEnumType.OPENAPI_TOKEN.getKey());
        if (!tokenValue.equals(token)) {
            throw new TipException("请求权限有误");
        }

        final List<Object[]> content = iOpenApiService.listInfo4Toutiao(ds);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("日期,渠道ID,点击量,真实激活数,付费设备数\n");
        for (Object[] objs : content) {
            stringBuffer.append(ds).append(",")
                    .append(objs[0]).append(",")
                    .append(objs[1]).append(",")
                    .append(objs[2]).append(",")
                    .append(objs[3]).append("\n");
        }

        HttpHeaders headers = new HttpHeaders();
        final String fileName = "export_" + ds + ".csv";
        headers.set("filename", fileName);
        headers.add("content-disposition", "attachment; filename=" + fileName);
        headers.add("Content-Type", "text/csv");
        return new ResponseEntity<String>(stringBuffer.toString(), headers, HttpStatus.OK);
    }
}
