package cn.com.ctop.kuaishou.modules.report.controller;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportDailyAgent;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportDailyAgentSum;
import cn.com.ctop.kuaishou.modules.report.entity.ParamsDTO;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouReportDailyAgentSumService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
* 代理商日汇总表
* @author jeecg-boot
* @date   2019-12-13
* @version V1.0
*/
@Slf4j
@Api(tags="代理商日汇总表")
@RestController
@RequestMapping("/report/kuaishouReportDailyAgentSum")
public class KuaishouReportDailyAgentSumController {
   @Autowired
   private IKuaishouReportDailyAgentSumService kuaishouReportDailyAgentSumService;

   /**
     * 分页列表查询
    * @param kuaishouReportDailyAgentSum
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "代理商日汇总表-分页列表查询")
   @ApiOperation(value="代理商日汇总表-分页列表查询", notes="代理商日汇总表-分页列表查询")
   @GetMapping(value = "/list")
   public Result<IPage<KuaishouReportDailyAgentSum>> queryPageList(KuaishouReportDailyAgentSum kuaishouReportDailyAgentSum,
                                     @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                     @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                     HttpServletRequest req) {
       Result<IPage<KuaishouReportDailyAgentSum>> result = new Result<IPage<KuaishouReportDailyAgentSum>>();
       QueryWrapper<KuaishouReportDailyAgentSum> queryWrapper = QueryGenerator.initQueryWrapper(kuaishouReportDailyAgentSum, req.getParameterMap());
       Page<KuaishouReportDailyAgentSum> page = new Page<KuaishouReportDailyAgentSum>(pageNo, pageSize);
       IPage<KuaishouReportDailyAgentSum> pageList = kuaishouReportDailyAgentSumService.page(page, queryWrapper);
       result.setSuccess(true);
       result.setResult(pageList);
       return result;
   }

   /**
     *   添加
    * @param kuaishouReportDailyAgentSum
    * @return
    */
   @AutoLog(value = "代理商日汇总表-添加")
   @ApiOperation(value="代理商日汇总表-添加", notes="代理商日汇总表-添加")
   @PostMapping(value = "/add")
   public Result<KuaishouReportDailyAgentSum> add(@RequestBody KuaishouReportDailyAgentSum kuaishouReportDailyAgentSum) {
       Result<KuaishouReportDailyAgentSum> result = new Result<KuaishouReportDailyAgentSum>();
       try {
           kuaishouReportDailyAgentSumService.save(kuaishouReportDailyAgentSum);
           result.success("添加成功！");
       } catch (Exception e) {
           log.error(e.getMessage(),e);
           result.error500("操作失败");
       }
       return result;
   }

   /**
     *  批量删除
    * @param ids
    * @return
    */
   @AutoLog(value = "代理商日汇总表-批量删除")
   @ApiOperation(value="代理商日汇总表-批量删除", notes="代理商日汇总表-批量删除")
   @DeleteMapping(value = "/deleteBatch")
   public Result<KuaishouReportDailyAgentSum> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       Result<KuaishouReportDailyAgentSum> result = new Result<KuaishouReportDailyAgentSum>();
       if(ids==null || "".equals(ids.trim())) {
           result.error500("参数不识别！");
       }else {
           this.kuaishouReportDailyAgentSumService.removeByIds(Arrays.asList(ids.split(",")));
           result.success("删除成功!");
       }
       return result;
   }

   /**
     * 通过id查询
    * @param id
    * @return
    */
   @AutoLog(value = "代理商日汇总表-通过id查询")
   @ApiOperation(value="代理商日汇总表-通过id查询", notes="代理商日汇总表-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<KuaishouReportDailyAgentSum> queryById(@RequestParam(name="id",required=true) String id) {
       Result<KuaishouReportDailyAgentSum> result = new Result<KuaishouReportDailyAgentSum>();
       KuaishouReportDailyAgentSum kuaishouReportDailyAgentSum = kuaishouReportDailyAgentSumService.getById(id);
       if(kuaishouReportDailyAgentSum==null) {
           result.error500("未找到对应实体");
       }else {
           result.setResult(kuaishouReportDailyAgentSum);
           result.setSuccess(true);
       }
       return result;
   }

 /**
     * 导出excel
  *
  * @param request
  * @param response
  */
 @RequestMapping(value = "/exportXls")
 public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
     // Step.1 组装查询条件
     QueryWrapper<KuaishouReportDailyAgentSum> queryWrapper = null;
     try {
         String paramsStr = request.getParameter("paramsStr");
         if (oConvertUtils.isNotEmpty(paramsStr)) {
             String deString = URLDecoder.decode(paramsStr, "UTF-8");
             KuaishouReportDailyAgentSum kuaishouReportDailyAgentSum = JSON.parseObject(deString, KuaishouReportDailyAgentSum.class);
             queryWrapper = QueryGenerator.initQueryWrapper(kuaishouReportDailyAgentSum, request.getParameterMap());
         }
     } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
     }

     //Step.2 AutoPoi 导出Excel
     ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
     List<KuaishouReportDailyAgentSum> pageList = kuaishouReportDailyAgentSumService.list(queryWrapper);
     //导出文件名称
     mv.addObject(NormalExcelConstants.FILE_NAME, "代理商日汇总表列表");
     mv.addObject(NormalExcelConstants.CLASS, KuaishouReportDailyAgentSum.class);
     mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("代理商日汇总表列表数据", "导出人:Jeecg", "导出信息"));
     mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
     return mv;
 }

 /**
     * 通过excel导入数据
  *
  * @param request
  * @param response
  * @return
  */
 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
     MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
     Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
     for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
         MultipartFile file = entity.getValue();
         ImportParams params = new ImportParams();
         params.setTitleRows(2);
         params.setHeadRows(1);
         params.setNeedSave(true);
         try {
             List<KuaishouReportDailyAgentSum> listKuaishouReportDailyAgentSums = ExcelImportUtil.importExcel(file.getInputStream(), KuaishouReportDailyAgentSum.class, params);
             kuaishouReportDailyAgentSumService.saveBatch(listKuaishouReportDailyAgentSums);
             return Result.ok("文件导入成功！数据行数:" + listKuaishouReportDailyAgentSums.size());
         } catch (Exception e) {
             log.error(e.getMessage(),e);
             return Result.error("文件导入失败:"+e.getMessage());
         } finally {
             try {
                 file.getInputStream().close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
     return Result.ok("文件导入失败！");
 }

    /**
     * @param dto
     * @return Result<List<KuaishouReportDailyAgentSum>>
     */
    @AutoLog(value = "公司报表")
    @ApiOperation(value="公司报表", notes="公司报表")
    @PostMapping(value = "/companyReport")
    public Result<List<KuaishouReportDailyAgentSum>> companyReport(@RequestBody ParamsDTO dto) {
       Result<List<KuaishouReportDailyAgentSum>> result = new Result<>();
        String startDate = dto.getStartDate();
        String endDate = dto.getEndDate();
        if(StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
           result.setSuccess(false);
           result.setMessage("时间不能为空");
        }

       List<KuaishouReportDailyAgentSum> kuaishouReportDailyAgentSumList = kuaishouReportDailyAgentSumService.companyReport(startDate,endDate);
        result.setResult(kuaishouReportDailyAgentSumList);
        result.setSuccess(true);
        result.setMessage("success");

        return result;
    }

    /**
     * @param dto
     * @return Result<KuaishouReportDailyAgentSum>
     */
    @AutoLog(value = "公司报表按时间汇总")
    @ApiOperation(value="公司报表按时间汇总", notes="公司报表按时间汇总")
    @PostMapping(value = "/companyReportSum")
    public Result<KuaishouReportDailyAgentSum> companyReportSum(@RequestBody ParamsDTO dto) {
        Result<KuaishouReportDailyAgentSum> result = new Result<>();
        String startDate = dto.getStartDate();
        String endDate = dto.getEndDate();
        if(StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
            result.setSuccess(false);
            result.setMessage("时间不能为空");
            return result;
        }

        KuaishouReportDailyAgentSum kuaishouReportDailyAgentSum = kuaishouReportDailyAgentSumService.companyReportSum(startDate,endDate);
        result.setResult(kuaishouReportDailyAgentSum);
        result.setSuccess(true);
        result.setMessage("success");

        return result;
    }

    /**
     * @param dto
     * @return Result<KuaishouReportDailyAgentSum>
     */
    @AutoLog(value = "公司报表按天明细")
    @ApiOperation(value="公司报表按天明细", notes="公司报表按天明细")
    @PostMapping(value = "/companyReportAccountDetailList")
    public Result<List<KuaishouReportDailyAgent>> companyReportAccountDetailList(@RequestBody ParamsDTO dto) {
        Result<List<KuaishouReportDailyAgent>> result = new Result<>();
        String advertiserName = dto.getAdvertiserName();
        String date = dto.getDate();
        if(StringUtils.isBlank(date)){
            result.setSuccess(false);
            result.setMessage("时间不能为空");
            return result;
        }

        List<KuaishouReportDailyAgent> kuaishouReportDailyAgentList = kuaishouReportDailyAgentSumService.companyReportAccountDetailList(date, advertiserName, null);
        result.setResult(kuaishouReportDailyAgentList);
        result.setSuccess(true);
        result.setMessage("success");

        return result;
    }

    @AutoLog(value = "公司报表按天导出Excel")
    @ApiOperation(value="公司报表按天导出Excel", notes="公司报表按天导出Excel")
    @PostMapping(value = "/companyReportExportExcel")
    public void companyReportExportExcel( @RequestBody ParamsDTO dto,
                                          //@RequestParam("startDate")String startDate,
                                          //@RequestParam("endDate")String endDate,
                                          HttpServletRequest request,
                                          HttpServletResponse response) throws Exception{
        Result result = new Result<>();
        result.setSuccess(true);
        result.setMessage("success");

        //公司报表
        List<KuaishouReportDailyAgentSum> kuaishouReportDailyAgentSumList = kuaishouReportDailyAgentSumService.companyReport(dto.getStartDate(),dto.getEndDate());

        //导出excel
        List<List<Object>> group = new ArrayList<>();
        if (!Check.isNull(kuaishouReportDailyAgentSumList)) {
            for (KuaishouReportDailyAgentSum sum : kuaishouReportDailyAgentSumList) {
                List<Object> kuaishouReportDailyAgentSum = new ArrayList();
                kuaishouReportDailyAgentSum.add(DateUtils.formatDate(sum.getDate()));  //日期
                kuaishouReportDailyAgentSum.add(sum.getCostCampaignCount() );  //有消费计划数
                kuaishouReportDailyAgentSum.add(sum.getBalance());  //总余额
                kuaishouReportDailyAgentSum.add(sum.getCost());  //总消耗
                kuaishouReportDailyAgentSum.add(sum.getXianjinCost());  //现金消耗
                kuaishouReportDailyAgentSum.add(sum.getFandianCost());  //后返消耗
                kuaishouReportDailyAgentSum.add(sum.getKuangfanCost());  //框返消耗
                kuaishouReportDailyAgentSum.add(sum.getJiliCost());  //激励账户消耗
                kuaishouReportDailyAgentSum.add(sum.getXinyongCost());  //信用账户消耗
                kuaishouReportDailyAgentSum.add(sum.getFengmianShowCount());  //封面曝光数
                kuaishouReportDailyAgentSum.add(sum.getFengmianClickCount());  //封面点击数
                kuaishouReportDailyAgentSum.add(sum.getSucaiShowCount());  //素材曝光数
                kuaishouReportDailyAgentSum.add(sum.getConvertCount());  //行为数
                kuaishouReportDailyAgentSum.add(sum.getFengmianClickCount());  //封面点击率
                kuaishouReportDailyAgentSum.add(sum.getConvertClickRate());  //转化点击率
                group.add(kuaishouReportDailyAgentSum);
            }
        }

        String[] groupHeaders = {"日期", "有消费计划数", "总余额", "总消耗", "现金消耗", "后返消耗", "框返消耗", "激励账户消耗", "信用账户消耗", "封面曝光数", "封面点击数", "素材曝光数", "行为数", "封面点击率", "转化点击率"};
        OutputStream os = response.getOutputStream();
        ExportExcelUtils eeu = new ExportExcelUtils();
        XSSFWorkbook workbook = new XSSFWorkbook();
        eeu.exportExcel(workbook, 0, "公司日报表", groupHeaders, group);
        this.setResponseHeader(response, "公司日报表.xlsx");
        workbook.write(os);
        os.flush();
        os.close();

    }

    @AutoLog(value = "公司日报明细表按天导出Excel")
    @ApiOperation(value="公司日报明细表按天导出Excel", notes="公司报表按天导出Excel")
    @PostMapping(value = "/companyReportAccountDetailListExportExcel")
    public void companyReportAccountDetailListExportExcel( @RequestBody ParamsDTO dto,
                                          //@RequestParam("date")String date,
                                          HttpServletRequest request,
                                          HttpServletResponse response) throws Exception{
        Result result = new Result<>();
        result.setSuccess(true);
        result.setMessage("success");

        //公司报表按天明细
        List<KuaishouReportDailyAgent> kuaishouReportDailyAgentList = kuaishouReportDailyAgentSumService.companyReportAccountDetailList(dto.getDate(), dto.getAdvertiserName(), dto.getIsExportNullData());

        //导出excel
        List<List<Object>> group = new ArrayList<>();
        if (!Check.isNull(kuaishouReportDailyAgentList)) {
            for (KuaishouReportDailyAgent agent : kuaishouReportDailyAgentList) {
                List<Object> kuaishouReportDailyAgentSum = new ArrayList();
                kuaishouReportDailyAgentSum.add(DateUtils.formatDate(agent.getDate()));  //日期
                kuaishouReportDailyAgentSum.add(agent.getKid());  //快手id
                kuaishouReportDailyAgentSum.add(agent.getAdvertiserName());  //广告主名称
                kuaishouReportDailyAgentSum.add(DateUtils.formatDate(agent.getAdvertiserCreateTime()));  //广告主创建时间
                kuaishouReportDailyAgentSum.add(agent.getCostCampaignCount());  //有消费计划数量
                kuaishouReportDailyAgentSum.add(agent.getBalance());  //总余额
                kuaishouReportDailyAgentSum.add(agent.getCost());  //总消耗
                kuaishouReportDailyAgentSum.add(agent.getXianjinCost());  //现金消耗
                kuaishouReportDailyAgentSum.add(agent.getFandianCost());  //后返消耗
                kuaishouReportDailyAgentSum.add(agent.getKuangfanCost());  //框返消耗
                kuaishouReportDailyAgentSum.add(agent.getJiliCost());  //激励账户消耗
                kuaishouReportDailyAgentSum.add(agent.getXinyongCost());  //信用账户消耗
                kuaishouReportDailyAgentSum.add(agent.getFengmianShowCount());  //封面曝光数
                kuaishouReportDailyAgentSum.add(agent.getFengmianClickCount());  //封面点击数
                kuaishouReportDailyAgentSum.add(agent.getSucaiShowCount());  //素材曝光数
                kuaishouReportDailyAgentSum.add(agent.getConvertCount());  //行为数
                kuaishouReportDailyAgentSum.add(agent.getFengmianClickRate());  //封面点击率
                kuaishouReportDailyAgentSum.add(agent.getConvertClickRate());  //转化点击率
                group.add(kuaishouReportDailyAgentSum);
            }
        }

        String[] groupHeaders = {"日期", "快手id", "广告主名称", "广告主创建时间", "有消费计划数量", "总余额", "总消耗", "现金消耗", "后返消耗", "框返消耗", "激励账户消耗", "信用账户消耗", "封面曝光数", "封面点击数", "素材曝光数", "行为数", "封面点击率", "转化点击率"};
        OutputStream os = response.getOutputStream();
        ExportExcelUtils eeu = new ExportExcelUtils();
        XSSFWorkbook workbook = new XSSFWorkbook();
        eeu.exportExcel(workbook, 0, "公司日报明细表", groupHeaders, group);
        this.setResponseHeader(response, "公司日报明细表.xlsx");
        workbook.write(os);
        os.flush();
        os.close();
    }


    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
