package com.crm.manager.controller;

import com.crm.manager.dto.export.CustomFollowUpExportDto;
import com.crm.manager.service.CustomReportFeignService;
import com.crm.rely.backend.core.dto.base.BaseResultWithPagerDto;
import com.crm.rely.backend.core.dto.custom.report.CustomFollowUpListDto;
import com.crm.rely.backend.core.entity.base.BaseIbReportListEntity;
import com.crm.rely.backend.util.ExportUtil;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ClassName CustomReportController
 * @Description
 * @Author y
 * @Date 2022/10/12 10:56
 */
@RestController
@RequestMapping("/custom/report")
public class CustomReportController {

    @Autowired
    private CustomReportFeignService customReportFeignService;

    @PostMapping("/follow/up")
    public BaseResultWithPagerDto<List<CustomFollowUpListDto>> followUp(@RequestBody BaseIbReportListEntity entity) throws Exception {
        return customReportFeignService.followUp(entity);
    }

    @GetMapping("/follow/up/export")
    public void tradeHistoryExport(
            @RequestParam(name = "startDate") String startDate,
            @RequestParam(name = "endDate") String endDate, HttpServletResponse response) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        BaseIbReportListEntity entity = new BaseIbReportListEntity();
        entity.setStartDate(startDate == null ? new Date() : simpleDateFormat.parse(startDate));
        entity.setEndDate(endDate == null ? new Date() : simpleDateFormat.parse(endDate));

        List<CustomFollowUpListDto> listDtos = customReportFeignService.followUpExport(entity);
        if (!CollectionUtils.isEmpty(listDtos)) {
            List<CustomFollowUpExportDto> exportDtos = Lists.newArrayList();
            for (CustomFollowUpListDto listDto : listDtos) {
                CustomFollowUpExportDto exportDto = new CustomFollowUpExportDto();
                BeanUtils.copyProperties(listDto, exportDto);
                exportDto.setCID(listDto.getCId());
                exportDtos.add(exportDto);
            }
            ExportUtil.transferToResponse("CUSTOM_FOLLOW_UP_"+System.currentTimeMillis()+".xls", exportDtos, CustomFollowUpExportDto.class, response);
        }
    }

}
