package cn.estsh.i3plus.core.apiservice.controller.busi;

import cn.estsh.i3plus.core.api.iservice.busi.ISysConfigService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysDictionaryService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysFileService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysLogExceptionService;
import cn.estsh.i3plus.core.apiservice.util.ExcelUtil;
import cn.estsh.i3plus.core.apiservice.util.FileUtil;
import cn.estsh.i3plus.core.apiservice.util.ZipUtil;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.platform.platbean.SysLogException;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.fastdfs.FastDFSClient;
import cn.estsh.impp.framework.boot.util.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description : 系统异常日志服务
 * @Reference :
 * @Author : yunhao
 * @CreateDate : 2018-11-19 18:42
 * @Modify:
 **/
@RestController
@Api(description = "系统异常日志服务")
@RequestMapping(PlatformConstWords.BASE_URL + "/sys-log-exception")
public class SysLogExceptionController extends CoreBaseController {
    public static final Logger LOGGER = LoggerFactory.getLogger(SysLogExceptionController.class);

    @Autowired
    private ISysLogExceptionService sysLogExceptionService;

    @Autowired
    private ISysDictionaryService sysDictionaryService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysFileService sysFileService;

    @GetMapping(value = "/query")
    @ApiOperation(value = "异常日志复杂查询，分页，排序",notes = "异常日志复杂查询，分页，排序")
    public ResultBean querySysLogExceptionByPager(SysLogException sysLogException, Pager pager){
        try {
            ListPager logExceptionList = sysLogExceptionService.querySysLogExceptionByPager(sysLogException, pager);
            return ResultBean.success("查询成功").setListPager(logExceptionList).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping("/get-col")
    @ApiOperation(value = "获取系统操作日志字段")
    public ResultBean getSysLogExceptionCol(){
        try {
            return  ResultBean.success("导出成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultMap(ExcelUtil.getColName(SysLogException.class));
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/export")
    @ApiOperation(value = "导出系统异常日志")
    public ResultBean exportSysLogException(SysLogException sysLogException, String[] colName, int pageSize,boolean isZip) {
        ListPager listPager;
        List result = new ArrayList();
        File zipFile = null;
        File excelDir = null;
        File excelFile;
        try {
            Pager pager = new Pager();
            pager.setCurrentPage(1);
            // 判断是否超过excel最大导出数量设定值
            int maxPageSize = Integer.parseInt(sysConfigService.getSysConfigByCode(PlatformConstWords.EXCEL_EXPORT_MAX_ROW).getConfigValue());
            if (pageSize == 0 || pageSize >= maxPageSize) {
                pager.setPageSize(maxPageSize);
            } else {
                pager.setPageSize(pageSize);
            }

            // 数据校验
            if(colName==null || colName.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.IMPP.getCode())
                        .setErrorCode(ImppExceptionEnum.BUSINESS_EXCEPTION_DATA_ERROR.getCode())
                        .setErrorDetail("导出列不能为空")
                        .build();
            }

            excelDir = new File(System.getProperty("java.io.tmpdir") + File.separator + new Date().getTime());
            excelDir.mkdir();
            do {
                listPager = sysLogExceptionService.querySysLogExceptionByPager(sysLogException, pager);
                pager = listPager.getObjectPager();

                // 将excel导出至临时文件夹并上传
                excelFile = new File(excelDir + File.separator + SysLogException.class.getSimpleName() + pager.getCurrentPage() + ".xls");
                excelFile.createNewFile();

                ExcelUtil.exportData(excelFile, listPager.getObjectList(), SysLogException.class, colName);
                result.add(sysFileService.uploadFile(excelFile));

                pager.setCurrentPage(pager.getCurrentPage() + 1);
            } while (pager.getCurrentPage() <= pager.getTotalPages());

            // 将所有excel文件打包
            if(isZip){
                zipFile = ZipUtil.zipFile(null, excelDir);
                result.add(sysFileService.uploadFile(zipFile));
                ExcelUtil.sendStationLetter(result,getSessionUser().getUser().getId());
                return ResultBean.success("导出成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(result);
            } else {
                return ResultBean.success("导出成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(result);
            }
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        } finally {
            // 清理临时文件文件
            if (zipFile != null) {
                FileUtil.deletefile(zipFile.getPath());
            }
            FileUtil.deletefile(excelDir.getPath());
        }
    }
}
