package com.sqx.modules.exportExecl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jcraft.jsch.SftpException;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.common.utils.SftpUtil;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.datacentre.query.RankListQuery;
import com.sqx.modules.datacentre.query.ShopCenterQuery;
import com.sqx.modules.exportExecl.dto.AccountEntry;
import com.sqx.modules.exportExecl.mapper.ExportJobMapper;
import com.sqx.modules.exportExecl.model.ExportJob;
import com.sqx.modules.exportExecl.service.ExportJobService;
import com.sqx.modules.order.dao.AppOrderDao;
import com.sqx.modules.order.dto.OrderQueryDto;
import com.sqx.modules.pay.controller.query.CashOutQueryDTO;
import com.sqx.modules.pay.controller.query.WalletDetailQuery;
import com.sqx.modules.reconciliation.model.PlatformBillDto;
import com.sqx.modules.riderStation.entity.RiderStation;
import com.sqx.modules.riderStation.service.RiderStationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Slf4j
@Api(tags={"管理端-导出"})
@RestController
@RequestMapping("/admin/export")
@RequiredArgsConstructor
public class ExportExeclController {

    private final AppOrderDao appOrderDao;
    private final ExportJobService exportJobService;
    private final CommonInfoService commonInfoService;
    private final RiderStationService riderStationService;
    private final SftpUtil sftpUtil;

    @GetMapping("excelOrder")
    @ApiOperation("导出订单列表")
    public Result excelOrder(OrderQueryDto queryDto) throws Exception{
//        log.info("导出订单参数"+queryDto);
        if(!StringUtils.hasText(queryDto.getUserId())){
            return Result.error("用户id不能为空");
        }
        Integer size = appOrderDao.excelAllOrderAdminCount(queryDto);
        //可导出最大数量
        String count=commonInfoService.findOne(431).getValue();
        if(size>Integer.parseInt(count)){
            return Result.error("导出总数不能超过"+Integer.parseInt(count)+",请添加筛选条件");
        }
        String strMessage=queryDto.toStrMessage();
        if(queryDto.getRiderStationId()!=null){
            RiderStation riderStation=riderStationService.getById(queryDto.getRiderStationId());
            if(riderStation!=null){
                strMessage=strMessage+"站点："+riderStation.getStationName()+";";
            }
        }
        ExportJob exportJob =this.buildExportJob("订单列表.xlsx","order", queryDto.getUserId(),strMessage,queryDto.toStrCode());

        boolean a=exportJobService.save(exportJob);
        if (a){
            return Result.success("新增导出计划成功");
        }else{
            return Result.error("新增导出计划失败");
        }
    }
    @GetMapping("excelRecharge")
    @ApiOperation("导出充值记录")
    public Result excelRecharge(String rechargeOrder, String acount,String userId) throws Exception{
        if(!StringUtils.hasText(userId)){
            return Result.error("用户id不能为空");
        }
        StringBuilder stringBuffer=new StringBuilder();
        if(rechargeOrder!=null&&rechargeOrder!=""){stringBuffer.append("充值订单号："+rechargeOrder+";");}
        if(acount!=null&&acount!=""){stringBuffer.append("被充值账号："+acount+";");}

        ExportJob exportJob =this.buildExportJob("充值记录.xlsx","recharge", userId,stringBuffer.toString(),","+rechargeOrder+","+acount);
        boolean a=exportJobService.save(exportJob);
        if (a){
            return Result.success("新增导出计划成功");
        }else{
            return Result.error("新增导出计划失败");
        }
    }

    @GetMapping("excelPayouts")
    @ApiOperation("提现管理导出")
    public Result excelPayouts(CashOutQueryDTO queryDTO) throws Exception{
        if(queryDTO.getUserId()==null){
            return Result.error("用户id不能为空");
        }
        String strMessage=queryDTO.toStrMessage();
        if(StringUtils.hasText(queryDTO.getRiderStationId())){
            RiderStation riderStation=riderStationService.getById(queryDTO.getRiderStationId());
            if(riderStation!=null){
                strMessage=strMessage+"站点："+riderStation.getStationName()+";";
            }
        }
        ExportJob exportJob =this.buildExportJob("提现管理.xlsx","payouts", String.valueOf(queryDTO.getUserId()),strMessage,queryDTO.toStrCode());
        boolean a=exportJobService.save(exportJob);
        if (a){
            return Result.success("新增提现管理导出计划成功");
        }else{
            return Result.error("新增提现管理导出计划失败");
        }
    }

    @GetMapping("excelDeposit")
    @ApiOperation("导出保证金记录")
    public Result excelDeposit(WalletDetailQuery queryDTO) throws Exception{
        if(!StringUtils.hasText(queryDTO.getUserId())){
            return Result.error("用户id不能为空");
        }
        ExportJob exportJob =this.buildExportJob("保证金记录.xlsx","deposit",queryDTO.getUserId(),queryDTO.toStrMessage(),queryDTO.toStrCode());
        boolean a=exportJobService.save(exportJob);
        if (a){
            return Result.success("新增保证金记录导出计划成功");
        }else{
            return Result.error("新增保证金记录导出计划失败");
        }
    }
    //    任意文件读取/下载
    @ApiOperation(value = "查询下载列表")
    @GetMapping("listByUser")
    public Result List(String userId,String state,String startTime,String endTime,Integer curretPage,Integer pageSize) throws IOException {

        QueryWrapper queryWrapper=new QueryWrapper<ExportJob>();

        queryWrapper.eq("user_id",userId);
        if(StringUtils.hasText(state)){
            queryWrapper.eq("flag",state);
        }
        if(StringUtils.hasText(startTime)){
            queryWrapper.ge("create_time",startTime);
        }
        if(StringUtils.hasText(endTime)){
            queryWrapper.le("create_time",endTime);
        }
        queryWrapper.orderByDesc("create_time");
        IPage<ExportJob> iPage=exportJobService.page(new Page<>(curretPage,pageSize),queryWrapper);
        PageUtils pageUtils = new PageUtils(iPage);
        return Result.success().put("data", pageUtils);
    }

    //    任意文件读取/下载
    @ApiOperation(value = "文件下载")
    @GetMapping("readBuffer")
    public void readbuffer(String filename,HttpServletResponse response) throws IOException {
        if(filename.contains("..") || filename.contains("/")){
            throw new IOException("文件名异常");
        }
        String value=commonInfoService.findOne(430).getValue()==null?"":commonInfoService.findOne(430).getValue();
        sftpUtil.login();
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            // 下载文件的默认名称
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
            sftpUtil.downloadStream(value,filename,response.getOutputStream());
            log.info("文件下载成功");
        }catch (IOException | SftpException e){
            log.error(e.getMessage());
            log.error("文件下载失败");
        }finally {
            if (sftpUtil.isConnected()){
                sftpUtil.logout();
            }
        }
    }



    //构建导出对象
    private ExportJob buildExportJob(String fileName,String fileType,String userId,String condDetail,String condCode){
        ExportJob exportJob=new ExportJob();
        //设置为待导出
        exportJob.setFlag(0);
        exportJob.setFileType(fileType);
        exportJob.setConditionDetail(condDetail);
        exportJob.setConditions(condCode);
        LocalDateTime localDateTime = LocalDateTime.now();
        String time=localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        exportJob.setFileName(time+(int)(Math.random() * 100)+fileName);
        exportJob.setCreateTime(new Date());
        exportJob.setUpdateTime(new Date());
        exportJob.setUserId(userId);
        return exportJob;
    }

    @GetMapping("excelShopCenter")
    @ApiOperation("导出商户收益统计")
    public Result excelShopCenter(ShopCenterQuery queryDTO) throws Exception{
        if(!StringUtils.hasText(queryDTO.getUserId())){
            return Result.error("用户id不能为空");
        }
        ExportJob exportJob =this.buildExportJob("商铺收益排行.xlsx","shopCenter",queryDTO.getUserId(),queryDTO.toStrMessage(),queryDTO.toStrCode());
        boolean a=exportJobService.save(exportJob);
        if (a){
            return Result.success("新增商铺收益排行导出计划成功");
        }else{
            return Result.error("新增商铺收益排行导出计划失败");
        }
    }

    @GetMapping("excelAccountEntry")
    @ApiOperation("导出入账管理")
    public Result excelAccountEntry(AccountEntry queryDTO) throws Exception{
        if(!StringUtils.hasText(queryDTO.getUserId())){
            return Result.error("用户id不能为空");
        }
        ExportJob exportJob =this.buildExportJob("入账管理.xlsx","accountEntry",queryDTO.getUserId(),queryDTO.toStrMessage(),queryDTO.toStrCode());
        boolean a=exportJobService.save(exportJob);
        if (a){
            return Result.success("新增入账管理导出计划成功");
        }else{
            return Result.error("新增入账管理导出计划失败");
        }
    }
    @GetMapping("excelRankList")
    @ApiOperation("导出骑手排行")
    public Result excelRankList(RankListQuery queryDTO) throws Exception{
        if(!StringUtils.hasText(queryDTO.getUserId())){
            return Result.error("用户id不能为空");
        }
        String strMessage=queryDTO.toStrMessage();
        if(StringUtils.hasText(queryDTO.getRiderStationId())){
            RiderStation riderStation=riderStationService.getById(queryDTO.getRiderStationId());
            if(riderStation!=null){
                strMessage=strMessage+"站点："+riderStation.getStationName()+";";
            }
        }
        ExportJob exportJob =this.buildExportJob("骑手排行.xlsx","rankList",queryDTO.getUserId(),strMessage,queryDTO.toStrCode());
        boolean a=exportJobService.save(exportJob);
        if (a){
            return Result.success("新增骑手排行导出计划成功");
        }else{
            return Result.error("新增骑手排行导出计划失败");
        }
    }
    @GetMapping("excelRiderBill")
    @ApiOperation("导出骑手对账")
    public Result excelRiderBill(PlatformBillDto  queryDTO) throws Exception{
        return getBill(queryDTO,"骑手对账.xlsx","riderBill");
    }
    @GetMapping("excelShopBill")
    @ApiOperation("导出商户对账")
    public Result excelShopBill(PlatformBillDto  queryDTO) throws Exception{
        return getBill(queryDTO,"商户对账.xlsx","shopBill");
    }
    @GetMapping("excelPlatformBill")
    @ApiOperation("导出平台对账")
    public Result excelPlatformBill(PlatformBillDto  queryDTO) throws Exception{
        return getBill(queryDTO,"平台对账.xlsx","platformBill");
    }

    private @NotNull Result getBill(PlatformBillDto queryDTO,String excelName,String fileType) {
        if(!StringUtils.hasText(queryDTO.getUserId())){
            return Result.error("用户id不能为空");
        }
        String strMessage= queryDTO.toStrMessage();
        if(StringUtils.hasText(queryDTO.getRiderStation())){
            RiderStation riderStation=riderStationService.getById(queryDTO.getRiderStation());
            if(riderStation!=null){
                strMessage=strMessage+"站点："+riderStation.getStationName()+";";
            }
        }
        ExportJob exportJob =this.buildExportJob(excelName,fileType, queryDTO.getUserId(),strMessage, queryDTO.toStrCode());
        boolean a=exportJobService.save(exportJob);
        if (a){
            return Result.success("新增对账导出计划成功");
        }else{
            return Result.error("新增对账导出计划失败");
        }
    }
}
