package com.zcxk.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcxk.common.EasyExcelUtil;
import com.zcxk.dto.OperateLogDto;
import com.zcxk.entity.OperateLogEntity;
import com.zcxk.model.*;
import com.zcxk.service.OperateLogService;
import com.zcxk.util.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description
 * @auto wangli
 * @data 2020-10-27 9:19
 */
@RestController
@RequestMapping("/operateLog")
@Api(tags = "操作日志管理")
@Slf4j
public class OperateLogController {

    @Autowired
    private OperateLogService operateLogService;
    @Value("${UMIS.sys_excel_path}")
    private String baseDir;
    /**
     * 通过主键查询单条数据
     *
     * @param id
     * @return 单条数据
     */
    @RequestMapping(value = "get", method = RequestMethod.POST)
    @ApiOperation(value = "根据id查询操作日志")
    public AjaxMessage<OperateLogDto> selectOne(
            @ApiParam(value = "操作日志信息", required = true) @RequestParam Integer id) {
        OperateLogDto result = operateLogService.selectById(id);

        return new AjaxMessage<>(ResultStatus.OK, result);
    }

    /**
     * 查询操作日志信息
     *
     * @param operateLogDto 参数对象
     * @return 多条数据
     */
    @RequestMapping(value = "selectList", method = RequestMethod.POST)
    @ApiOperation(value = "查询操作日志信息")
    public AjaxMessage<List<OperateLogDto>> selectList(
            @ApiParam(value = "操作日志信息", required = true) @RequestBody OperateLogDto operateLogDto) {
        List<OperateLogDto> result = operateLogService.selectList(operateLogDto);

        return new AjaxMessage<>(ResultStatus.OK, result);
    }


    /**
     * 新增一条数据
     *
     * @param operateLogEntity 实体类
     * @return Response对象
     */
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    @ApiOperation(value = "插入操作日志信息")
    public AjaxMessage<Integer> insert(@ApiParam(value = "操作日志信息", required = true) @RequestBody OperateLogEntity operateLogEntity) {
        int result = operateLogService.insert(operateLogEntity);

        return new AjaxMessage<>(ResultStatus.OK, result);
    }

    /**
     * 修改一条数据
     *
     * @param operateLogEntity 实体类
     * @return Response对象
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ApiOperation(value = "修改操作日志信息")
    public AjaxMessage<Integer> update(@ApiParam(value = "操作日志信息", required = true) @RequestBody OperateLogEntity operateLogEntity) {
        int result = operateLogService.update(operateLogEntity);
        return new AjaxMessage<>(ResultStatus.OK, result);

    }

    /**
     * 单条删除数据
     *
     * @param id
     * @return Response对象
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ApiOperation(value = "删除操作日志信息")
    public AjaxMessage<Integer> delete(@ApiParam(value = "操作日志信息", required = true) @RequestParam Integer id) {
        int result = operateLogService.deleteById(id);
        return new AjaxMessage<>(ResultStatus.OK, result);
    }


    /**
     * 分页查询
     *
     * @return Response对象
     */
    @RequestMapping(value = "selectPage", method = RequestMethod.POST)
    @ApiOperation(value = "查询操作日志信息列表")
    public AjaxMessage<Pagination<OperateLogDto>> selectPage(
            @ApiParam(value = "查询条件（用户名/手机号）") @RequestParam(required = false) String condition,
            @ApiParam(value = "部门id") @RequestParam(required = false) Integer departmentId,
            @ApiParam(value = "开始时间yyyy-MM-dd") @RequestParam(required = false) String beginTime,
            @ApiParam(value = "结束时间yyyy-MM-dd") @RequestParam(required = false) String endTime,
            @ApiParam(value = "页数,非必传，默认第一页",  defaultValue = "1") @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @ApiParam(value = "条数，非必传，默认10条",  defaultValue = "10") @RequestParam(required = false, defaultValue = "10") Integer pageSize



    ) {
        LoginUser loginUser = UserUtil.getCurrentUser();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        OperateLogDto operateLogDto = new OperateLogDto();
        operateLogDto.setTenantId(loginUser.getTenantId());
        operateLogDto.setCondition(condition);
        operateLogDto.setDepartmentId(departmentId);
        operateLogDto.setPermissonType(loginUser.getPermissonType());
        //系统管理员不过滤权限，数据为null的去掉
        if((!loginUser.getType().equals("-9999")) && !loginUser.getType().equals("-999")   ){
            operateLogDto.setProgramItems(loginUser.getProgramItemList().stream().filter(p -> p.getOrgId() != null).collect(Collectors.toList()));
        }

        try {
            if(StringUtils.isNotBlank(beginTime)){
                operateLogDto.setBeginTime(f.parse(beginTime));
            }
            if(StringUtils.isNotBlank(endTime)){
                operateLogDto.setEndTime(f.parse(endTime));
            }
        }catch (ParseException e){
            log.error("操作日志查询时间转换错误，原数据：beginTime：{}，endTime：{}，异常信息：{}",beginTime,endTime,e.getMessage());
            operateLogDto.setBeginTime(new Date());
            operateLogDto.setEndTime(new Date());
        }
        IPage<OperateLogDto> iPage = new Page<>(pageNum, pageSize);
        if(iPage.orders().size() == 0){
            OrderItem orderItem =new OrderItem();
            orderItem.setAsc(false);
            orderItem.setColumn("a.create_time");
            iPage.orders().add(orderItem);
        }
        iPage = operateLogService.selectPage(iPage, operateLogDto);

        Pagination<OperateLogDto> pages = new Pagination<>(iPage);

        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    @RequestMapping(value = "/exportExcel", method = RequestMethod.POST)
    @ApiOperation(value = "操作日志导出")
    public AjaxMessage<String> exportExcel(@ApiParam(value = "日志IDS", required = true) @RequestParam Long[] ids) {
        List<OperateLogDto> result = operateLogService.selectListByIds(ids);
        String filePath = EasyExcelUtil.excelWrite(baseDir, OperateLogDto.class, "操作日志", result);
        return new AjaxMessage<>(ResultStatus.OK, filePath);
    }
}
