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.ISysLogOperateService;
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.SysLogOperate;
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 javax.websocket.server.PathParam;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

    @Autowired
    private ISysLogOperateService logOperateService;

    @Autowired
    private ISysDictionaryService sysDictionaryService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysFileService sysFileService;

    @PostMapping(value = "/insert")
    @ApiOperation(value = "添加操作日志",notes = "添加操作日志")
    public ResultBean insertSysLogOperateController(SysLogOperate logOperate){
        try {
            logOperateService.insertSysLogOperate(logOperate);
            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 = "根据id删除操作日志",notes = "根据id删除操作日志")
    public ResultBean deleteSysLogOperateById(String id){
        try {
            // 条件验证
            ValidatorBean.checkNotNull(id,"id不能为空！");

            logOperateService.deleteSysLogOperateById(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 findSysLogOperateAll(){
        try {
            List logOperateList = logOperateService.listSysLogOperate();
            return ResultBean.success("操作成功").setResultList(logOperateList).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/get/{id}")
    @ApiOperation(value = "根据id查询操作日志",notes = "根据id查询操作日志")
    public ResultBean getSysLogOperateById(@PathParam("id") String id){
        try{
            SysLogOperate logOperate = logOperateService.getSysLogOperateById(Long.parseLong(id));
            if (logOperate != null) {
                return ResultBean.success("操作成功")
                        .setResultObject(logOperate)
                        .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }else {
                return ResultBean.fail("操作日志不存在")
                        .setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/query")
    @ApiOperation(value = "操作日志复杂查询，分页，排序",notes = "操作日志复杂查询，分页，排序")
    public ResultBean querySysLogOperateByPager(SysLogOperate logOperate, Pager pager){
        try {
            ListPager logSystemList = logOperateService.querySysLogOperateByPager(logOperate, 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 getSysLogOperateCol(){
        try {
            return  ResultBean.success("导出成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultMap(ExcelUtil.getColName(SysLogOperate.class));
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/export")
    @ApiOperation(value = "导出操作日志")
    public ResultBean exportSysLogOperate(SysLogOperate sysLogOperate, 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 = logOperateService.querySysLogOperateByPager(sysLogOperate, pager);
                pager = listPager.getObjectPager();

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

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