package org.jeecg.modules.ctop.controller;

import cn.com.ctop.common.module.entity.Product;
import cn.com.ctop.common.module.entity.SysCompany;
import cn.com.ctop.common.module.service.ISysCompanyService;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.common.module.utils.HttpUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.ctop.service.IMediaReportService;
 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *  Created by JQ.bi on 2020.6.30
 */
@Slf4j
@RestController
@RequestMapping("ctop/media/report")
public class MediaReportCtrl {

    @Autowired
    ISysCompanyService sysCompanyService;

    @Autowired
    IMediaReportService mediaReportService;

    @GetMapping("/getCompany")
    public Result<List<SysCompany>> getCompany(){

        Result<List<SysCompany>> result=new Result<>();
        //TODO 没有维护渠道的信息暂时不能再库里加，会影响到绩效等其他接口查询公司的接口
        List<SysCompany> list=sysCompanyService.list();
        //SysCompany sysCompany = new SysCompany();
        //sysCompany.setId(4L);
        //sysCompany.setCompanyId("6weq589875c040119adst08751712368");
        //sysCompany.setCompanyCode("A04");
        //sysCompany.setCompanyName("渠道");
        //sysCompany.setArea("渠道");
        //list.add(sysCompany);
        result.setSuccess(true);
        result.setResult(list);
        return result;

    }

    @GetMapping("/getAdvertiser")
    public Result<List<JSONObject>> getAdvertiser(String companyId){
        Result<List<JSONObject>> result=new Result<>();
        result.setSuccess(true);
        result.setResult(mediaReportService.queryAdvertiserNameByCompanyId(companyId));
        return result;
    }

    @GetMapping("/getProject")
    public Result<List<JSONObject>> getProject(String advertiserId){
        Result<List<JSONObject>> result=new Result<>();
        result.setSuccess(true);
        result.setResult(mediaReportService.queryProjectNameByAdvertiserId(advertiserId));
        return result;
    }

    //获取所有产品
    @ResponseBody
    @RequestMapping(value = "/getAllProductList")
    public Result<List<Product>> getAllProductList(@RequestBody JSONObject requestBody,
                                                   HttpServletRequest request, HttpServletResponse response){
        log.info("/ctop/product/getAllProductList 方法开始");
        Result<List<Product>> result = new Result();

        try {
            List<Product> allProductList = mediaReportService.getAllProductList(requestBody.getInteger("mediaType"), requestBody.getString("advertiserId"));
            result.setResult(allProductList);
        }catch (Exception e){
            log.error(e.getMessage());
            result.setSuccess(false);
            result.setMessage("error");
        }finally{
            log.info("/ctop/product/getAllProductList 方法结束");
        }

        return result;
    }


    @PostMapping("/{pageNo}/{pageSize}")
    public Result<PageInfo<JSONObject>> getReport(@PathVariable int pageNo,
                                                  @PathVariable int pageSize,
                                                  @RequestBody JSONObject requestBody){
        Result<PageInfo<JSONObject>> result = new Result<>();
        if(requestBody.isEmpty()){
            log.error("requestBody is null");
            result.setSuccess(false);
            return result;
        }
        PageInfo<JSONObject> pageInfo;
        if(requestBody.getString("companyId").isEmpty()){
            pageInfo =mediaReportService.queryAllReportByCondition(pageNo,pageSize,requestBody);
        }else {
            pageInfo =mediaReportService.queryReportByCondition(pageNo,pageSize,requestBody);
        }
        result.setResult(pageInfo);
        result.setSuccess(true);
        return result;
    }
    /**
     *  导出数据
     * @param requestBody
     * @param request
     * @param response
     */
    @PostMapping("/excel")
    public void getExcelReport(@RequestBody JSONObject requestBody,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        List<JSONObject> excelData;
        if(requestBody.getString("companyId").isEmpty()){
            excelData = mediaReportService.queryAllByCondition(requestBody);
        }else {
            excelData =mediaReportService.queryReportByCondition(requestBody);
        }
        if(excelData.isEmpty()){
            return;
        }
        List<List<Object>> excelList= new ArrayList<>();
        excelData.forEach(data->{
            List<Object> temp= new ArrayList<>();
            temp.add(data.get("mediaType")==null?"-":data.get("mediaType"));
            temp.add(data.get("advertiserId")==null?"-":data.get("advertiserId"));
            temp.add(data.get("advertiserName")==null?"-":data.get("advertiserName"));
            temp.add(data.get("projectName")==null?"-":data.get("projectName"));
            temp.add(data.get("operatorManger")==null?"-":data.get("operatorManger"));
            temp.add(data.get("operator")==null?"-":data.get("operator"));
            temp.add(data.get("sale")==null?"-":data.get("sale"));
            temp.add(data.get("plan")==null?"-":data.get("plan"));
            temp.add(data.get("shot")==null?"-":data.get("shot"));
            temp.add(data.get("clip")==null?"-":data.get("clip"));
            temp.add(data.get("todayCost"));
            temp.add(data.get("yesterdayCost"));
            temp.add(data.get("diffCost"));
            excelList.add(temp);
        });
        try{
            String[] headers = {"媒体类型","广告主Id","广告主","项目","运营负责人","运营","销售","策划","拍摄","剪辑",requestBody.getString("todayDate"),requestBody.getString("yesterdayDate"),"消耗差"};
            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            eeu.exportExcel(workbook, 0, "媒介报表", headers, excelList);
            HttpUtils.setResponseHeader(response, "媒介报表.xlsx");
            workbook.write(os);
            os.flush();
            os.close();
        }catch (IOException e){
            log.error(e.getMessage());
        }
    }

    @PostMapping("/mediaReport/{pageNum}/{pageSize}")
    public Result<PageInfo<JSONObject>> mediaReport(@PathVariable int pageNum,
                                                  @PathVariable int pageSize,
                                                  @RequestBody JSONObject requestBody){
        Result<PageInfo<JSONObject>> result = new Result<>();
        if(StringUtils.isBlank(requestBody.getString("todayDate")) || requestBody.getInteger("mediaType") ==null){
            result.setSuccess(false);
            result.setMessage("参数有误");
        }

        if(requestBody.isEmpty()){
            log.error("requestBody is null");
            result.setSuccess(false);
            return result;
        }
        PageInfo<JSONObject> pageInfo = mediaReportService.mediaReport(pageNum,pageSize,requestBody);

        result.setResult(pageInfo);
        result.setSuccess(true);
        return result;
    }

    /**
     *  导出数据
     * @param requestBody
     * @param request
     * @param response
     */
    @PostMapping("/exportMediaReportExcel")
    public void exportMediaReportExcel(@RequestBody JSONObject requestBody,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        String today = requestBody.getString("todayDate");
        Date todayDate = DateUtils.parseDate(today, "yyyy-MM-dd");
        Date yesterdayDate = DateUtils.addDay(todayDate, -1);
        String yesterday = DateUtils.formatDate(yesterdayDate);

        List<JSONObject> excelData = mediaReportService.exportMediaReportExcel(requestBody);

        List<List<Object>> excelList= new ArrayList<>();
        excelData.forEach(data->{
            List<Object> temp= new ArrayList<>();
            temp.add(data.get("mediaType")==null?"-":(data.getInteger("mediaType")==1?"头条":"快手"));
            temp.add(data.get("advertiserName")==null?"-":data.get("advertiserName"));
            temp.add(data.get("productName")==null?"-":data.get("productName"));
            temp.add(data.get("operator")==null?"-":data.get("operator"));
            temp.add(data.get("sale")==null?"-":data.get("sale"));
            temp.add(data.get("todayCost"));
            temp.add(data.get("yesterdayCost"));
            temp.add(data.get("diffCost"));
            temp.add(data.get("companyName"));
            excelList.add(temp);
        });
        try{
            String[] headers = {"媒体类型","广告主","产品","运营","销售",requestBody.getString("todayDate"),yesterday,"消耗差","区域"};
            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            eeu.exportExcelForMediaReport(workbook, 0, "媒介报表", headers, excelList);
            HttpUtils.setResponseHeader(response, "媒介报表.xlsx");
            workbook.write(os);
            os.flush();
            os.close();
        }catch (IOException e){
            log.error(e.getMessage());
        }

    }










}
