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.ISysLogSystemService;
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.SysLogSystem;
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 cn.estsh.impp.framework.boot.util.ValidatorBean;
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.*;

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

/**
 * @Description : 系统日志服务
 * @Reference :
 * @Author : yunhao
 * @Date : 2018-10-25 10:50
 * @Modify :
 **/
@RestController
@Api(description = "系统日志服务")
@RequestMapping(PlatformConstWords.BASE_URL +"/sys-log-system")
public class SysLogSystemController extends CoreBaseController{
    public static final Logger LOGGER = LoggerFactory.getLogger(SysLogSystemController.class);

    @Autowired
    private ISysLogSystemService logSystemService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysFileService sysFileService;

    @PostMapping(value = "/insert")
    @ApiOperation(value="新增系统日志",notes = "新增系统日志")
    public ResultBean insertSysLogSystem(SysLogSystem logSystem) {
        try {
            logSystemService.insertSysLogSystem(logSystem);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/delete")
    @ApiOperation(value = "删除系统日志",notes = "删除系统日志")
    public ResultBean deleteSysLogSystemById(String id) {
        try {
            // 条件校验
            ValidatorBean.checkNotNull(id,"id不能为空");

            logSystemService.deleteSysLogSystemById(Long.parseLong(id));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "查询全部系统日志",notes = "查询全部系统日志")
    public ResultBean findSysLogSystemAll(){
        try {
            List<SysLogSystem> logSystemList = logSystemService.listSysLogSystem();
            return ResultBean.success("操作成功").setResultList(logSystemList).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/get")
    @ApiOperation(value = "根据id查询系统日志",notes = "根据id查询系统日志")
    public ResultBean getSysLogSystemById(String id){
        try {
            SysLogSystem logSystem = logSystemService.getSysLogSystemById(Long.parseLong(id));
            return ResultBean.success("操作成功").setResultObject(logSystem).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    /**
     * 系统日志分页复杂查询
     * @param logSystem
     * @param pager
     * @return
     */
    @GetMapping("/query")
    @ApiOperation(value = "系统日志分页复杂查询",notes = "系统日志分页复杂查询")
    public ResultBean querySysLogSystemByPager(SysLogSystem logSystem, Pager pager){
        try {
            ListPager logSystemList = logSystemService.querySysLogSystemByPager(logSystem, pager);
            return ResultBean.success("操作成功").setListPager(logSystemList).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 getSysLogSystem(){
        try {
            return  ResultBean.success("导出成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultMap(ExcelUtil.getColName(SysLogSystem.class));
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/export")
    @ApiOperation(value = "导出系统异常日志")
    public ResultBean exportSysLogSystem(SysLogSystem sysLogSystem, 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 = logSystemService.querySysLogSystemByPager(sysLogSystem, pager);
                pager = listPager.getObjectPager();

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

                ExcelUtil.exportData(excelFile, listPager.getObjectList(), SysLogSystem.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());
        }
    }
}
