package com.tofly.xrtygis.custom.service.dma.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.xrtygis.custom.mapper.TableCountMapper;
import com.tofly.xrtygis.custom.service.dma.TableCountService;
import com.tofly.xrtygis.em.Constant;
import com.tofly.xrtygis.em.ExcelExportFileTypeEnum;
import com.tofly.xrtygis.strategy.ExcelStrategyContext;
import com.tofly.xrtygis.util.ExcelUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author 20126
 */
@Service
@AllArgsConstructor
public class TableCountSericeImpl implements TableCountService {

    private final TableCountMapper tableCountMapper;
    private final ExcelStrategyContext excelStrategyContext;
    /**
     * 获取分区信息
     *
     * @param page
     * @return page
     */
    @Override
    public Page getPartition(Page page) {
        return tableCountMapper.getPartition(page);
    }

    /**
     * 获取分区详细信息
     *
     * @param page     page
     * @param dmaId    dmaid
     * @param isExport 是否导出
     * @return page
     */
    @Override
    public Page viewPartition(HttpServletResponse response,Page page, String dmaId, String isExport) {
        if ("0".equals(isExport)){
            return tableCountMapper.getPartitionInfo(page, dmaId);
        }else {
            List<Map> mapList = tableCountMapper.viewPartitionInfo(dmaId);
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("exportTableCountService", "1");
            if (null == excelExportFileTypeEnum) {
                throw new ToflyDeniedException("导出失败");
            }
            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
            String resultListToString = JSONArray.toJSONString(mapList);
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("exportTableCountService", "1", resultListToString);
            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            return null;
        }
    }
}
