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

import cn.com.ctop.common.module.annotation.AutoLog;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.common.module.utils.QueryGenerator;
import cn.com.ctop.kuaishou.modules.report.entity.KuaiShouDailyAgent;
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.IKuaiShouDailyAgentService;
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 com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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.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.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 代理商报表
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-08-18
 */
@Slf4j
@Api(tags = "代理商报表")
@RestController
@RequestMapping("/agent/kuaiShouDailyAgent")
public class KuaiShouDailyAgentController {
    @Autowired
    private IKuaiShouDailyAgentService kuaiShouDailyAgentService;

    /**
     * 分页列表查询
     *
     * @param kuaiShouDailyAgent
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "代理商报表-分页列表查询")
    @ApiOperation(value = "代理商报表-分页列表查询", notes = "代理商报表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<KuaiShouDailyAgent>> queryPageList(KuaiShouDailyAgent kuaiShouDailyAgent,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        Result<IPage<KuaiShouDailyAgent>> result = new Result<>();

        String accountName = kuaiShouDailyAgent.getAccountName();
        kuaiShouDailyAgent.setAccountName(null);

        String corporationName = kuaiShouDailyAgent.getCorporationName();
        kuaiShouDailyAgent.setCorporationName(null);

        QueryWrapper<KuaiShouDailyAgent> queryWrapper = QueryGenerator.initQueryWrapper(kuaiShouDailyAgent, req.getParameterMap());
        if (!Check.isNull(accountName)) {
            queryWrapper.like("account_name", accountName);
        }

        if (!Check.isNull(corporationName)) {
            queryWrapper.like("corporation_name", corporationName);
        }

        Page<KuaiShouDailyAgent> page = new Page<KuaiShouDailyAgent>(pageNo, pageSize);
        IPage<KuaiShouDailyAgent> pageList = kuaiShouDailyAgentService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 代理商报表
     *
     * @param dto
     * @return
     */

    @AutoLog(value = "公司报表")
    @ApiOperation(value = "公司报表", notes = "公司报表")
    @PostMapping(value = "/companyReport")
    public Result<PageInfo<KuaishouReportDailyAgentSum>> companyReport(@RequestBody ParamsDTO dto) {
        Result<PageInfo<KuaishouReportDailyAgentSum>> result = new Result<>();
        String startDate = dto.getStartDate();
        String endDate = dto.getEndDate();
        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
            result.setSuccess(false);
            result.setMessage("时间不能为空");
        }
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<KuaishouReportDailyAgentSum> kuaishouReportDailyAgentSumList = kuaiShouDailyAgentService.companyReport(startDate, endDate);
        PageInfo<KuaishouReportDailyAgentSum> pageInfo = new PageInfo<>(kuaishouReportDailyAgentSumList);
        result.setResult(pageInfo);
        result.setSuccess(true);
        result.setMessage("success");

        return result;
    }


    /**
     * @param dto
     * @return
     */
    @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 = kuaiShouDailyAgentService.companyReportSum(startDate, endDate);
        result.setResult(kuaishouReportDailyAgentSum);
        result.setSuccess(true);
        result.setMessage("success");

        return result;
    }


    /**
     * 按天查看明细
     *
     * @param dto
     * @return
     */
    @PostMapping(value = "/companyReportAccountDetailList")
    public Result<PageInfo<KuaishouReportDailyAgent>> companyReportAccountDetailList(@RequestBody ParamsDTO dto) {
        Result<PageInfo<KuaishouReportDailyAgent>> result = new Result<>();
        String advertiserName = dto.getAdvertiserName();
        String date = dto.getDate();
        if (StringUtils.isBlank(date)) {
            result.setSuccess(false);
            result.setMessage("时间不能为空");
            return result;
        }
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<KuaishouReportDailyAgent> kuaishouReportDailyAgentList = kuaiShouDailyAgentService.companyReportAccountDetailList(date, advertiserName, dto.getIsExportNullData());
        PageInfo<KuaishouReportDailyAgent> pageInfo = new PageInfo<>(kuaishouReportDailyAgentList);

        result.setResult(pageInfo);
        result.setSuccess(true);
        result.setMessage("success");

        return result;
    }


    @PostMapping(value = "/companyReportExportExcel")
    public void companyReportExportExcel(@RequestBody ParamsDTO dto,
                                         HttpServletRequest request,
                                         HttpServletResponse response) throws Exception {
        Result result = new Result<>();
        result.setSuccess(true);
        result.setMessage("success");

        //公司报表
        List<KuaishouReportDailyAgentSum> kuaishouReportDailyAgentSumList = kuaiShouDailyAgentService.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(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());  //行为数
                BigDecimal fengmianClickRate = sum.getFengmianClickRate();
                if (!Check.isNull(fengmianClickRate) && fengmianClickRate.compareTo(new BigDecimal(0)) != 0) {
                    BigDecimal bigDecimal = fengmianClickRate.multiply(new BigDecimal(100)).setScale(3, BigDecimal.ROUND_HALF_UP);
                    kuaishouReportDailyAgentSum.add(bigDecimal + "%");
                }


                BigDecimal convertClickRate = sum.getConvertClickRate();
                if (!Check.isNull(convertClickRate) && convertClickRate.compareTo(new BigDecimal(0)) != 0) {
                    BigDecimal bigDecimal2 = convertClickRate.multiply(new BigDecimal(100)).setScale(3, BigDecimal.ROUND_HALF_UP);
                    kuaishouReportDailyAgentSum.add(bigDecimal2 + "%"); //转化点击率
                }
                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 = kuaiShouDailyAgentService.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(agent.getDate());  //日期
                kuaishouReportDailyAgentSum.add(agent.getKid());  //快手id
                kuaishouReportDailyAgentSum.add(agent.getAdvertiserName());  //广告主名称
                kuaishouReportDailyAgentSum.add(agent.getAccountId());  //账户id
                kuaishouReportDailyAgentSum.add(agent.getAccountName());  //账户名称
                // kuaishouReportDailyAgentSum.add(DateUtils.formatDate(agent.getAdvertiserCreateTime()));  //广告主创建时间
                kuaishouReportDailyAgentSum.add(agent.getCostCampaignCount());  //有消费计划数量
                kuaishouReportDailyAgentSum.add(agent.getBalance());  //总余额
                kuaishouReportDailyAgentSum.add(agent.getCost());  //总消耗
                kuaishouReportDailyAgentSum.add(agent.getChargeDayOnDayPercent());  //消耗环比

                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());  //转化点击率
                kuaishouReportDailyAgentSum.add(agent.getIndustry()); // 一级行业
                kuaishouReportDailyAgentSum.add(agent.getSecondIndustry()); // 二级行业
                group.add(kuaishouReportDailyAgentSum);
            }
        }

        String[] groupHeaders = {"日期", "快手id", "广告主名称", "广告主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();
        }
    }


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

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<KuaiShouDailyAgent> pageList = kuaiShouDailyAgentService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "代理商报表列表");
        mv.addObject(NormalExcelConstants.CLASS, KuaiShouDailyAgent.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<KuaiShouDailyAgent> listKuaiShouDailyAgents = ExcelImportUtil.importExcel(file.getInputStream(), KuaiShouDailyAgent.class, params);
                kuaiShouDailyAgentService.saveBatch(listKuaiShouDailyAgents);
                return Result.ok("文件导入成功！数据行数:" + listKuaiShouDailyAgents.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("文件导入失败！");
    }

}
