/*
 * Copyright 2015-2020 All rights reserved.
 */
package com.scm.contract.web.common;

import com.set.direwolf.core.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.set.direwolf.core.mybatis.Page;
import com.set.direwolf.core.utils.IDUtil;
import com.set.direwolf.core.utils.UserUtils;
import com.set.direwolf.core.web.BaseController;
import com.set.direwolf.core.web.OperationResult;
import org.apache.commons.lang3.StringUtils;
import com.set.direwolf.security.component.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.scm.api.contract.entity.common.TOperatingLog;
import com.scm.contract.service.common.TOperatingLogService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * ----auto generated-------
 * 日志信息接口Controller
 * </pre>
 *
 * @author wangning
 * @version 2020-04-29 09:58:09
 */

@Controller
@RequestMapping("${adminPath}/contract/common/tOperatingLog")
public class TOperatingLogController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(TOperatingLogController.class);
    private final TOperatingLogService entityService;
    private final PermissionService permissionService;

    @Autowired
    public TOperatingLogController(TOperatingLogService entityService, PermissionService permissionService) {
        this.entityService = entityService;
        this.permissionService = permissionService;
    }

    /**
     * 检查用户是否有访问日志信息页面的权限
     *
     * @return OperationResult
     */
    @ApiOperation(value = "根据高度，预测时间（那天预测的）获取预测数据(小时数据)", notes = "根据高度，预测时间（那天预测的）获取预测数据(小时数据)", produces = "application/json")
    @GetMapping("/checkTOperatingLogListPermission")
    public @ResponseBody
    OperationResult checkTOperatingLogListPermission() {
        User currentUser = UserUtils.getUser();
        String id = currentUser.getId();
        String userName = currentUser.getUserName();
        boolean result = permissionService.hasPermission("contract:common:tOperatingLog:list");
        return OperationResult.buildSuccessResult("校验用户权限成功", result);
    }

    /**
     * 检查用户是否有访问日志信息明细页面的权限
     *
     * @return OperationResult
     */
    @GetMapping("/checkTOperatingLogFormPermission")
    public @ResponseBody
    OperationResult checkTOperatingLogFormPermission() {
        boolean result = permissionService.hasPermission("contract:common:tOperatingLog:add")
                || permissionService.hasPermission("contract:common:tOperatingLog:edit")
                || permissionService.hasPermission("contract:common:tOperatingLog:view");
        return OperationResult.buildSuccessResult("校验用户权限成功", result);
    }

    /**
     * 日志信息获取
     *
     * @param entity 参数实体
     * @return OperationResult
     */
    @PreAuthorize("@pms.hasPermission('contract:common:tOperatingLog:add') or @pms.hasPermission('contract:common:tOperatingLog:edit') or @pms.hasPermission('contract:common:tOperatingLog:view')")
    @GetMapping("getEntity")
    public @ResponseBody
    OperationResult getEntity(TOperatingLog entity) {
        return OperationResult.buildSuccessResult("获取日志信息成功", entityService.get(entity));
    }

    /**
     * 日志信息列表数据获取
     *
     * @param entity   参数实体
     * @param request  请求
     * @param response 响应
     * @return Page
     */
    @PreAuthorize("@pms.hasPermission('contract:common:tOperatingLog:list')")
    @GetMapping("getTOperatingLogList")
    public @ResponseBody
    Page<TOperatingLog> list(TOperatingLog entity, HttpServletRequest request, HttpServletResponse response) {
        Page<TOperatingLog> page = Page.bootstrapPage(request, response);
        String defaultOrder = page.getOrderBy();
		if (StringUtils.isEmpty(defaultOrder)){
			page.setOrderBy("oper_time desc");
		}
        page = entityService.findPage(page, entity);
        return page;
    }

    /**
     * 保存日志信息
     *
     * @param entity 参数实体
     * @return OperationResult
     */
    @PreAuthorize("@pms.hasPermission('contract:common:tOperatingLog:add') or @pms.hasPermission('contract:common:tOperatingLog:edit')")
    @PostMapping("save")
    public @ResponseBody
    OperationResult save(@RequestBody TOperatingLog entity) {
        User currentUser = UserUtils.getUser();
        if (currentUser == null) {
            return OperationResult.buildFailureResult("保存日志信息失败，获取当前登录用户信息失败");
        }
        String userId = currentUser.getId();
        String id = entity.getId();
        try{
            if (StringUtils.isNotBlank(id)) {
                // 非新增记录与数据库记录合并后保存
                TOperatingLog t = entityService.get(id);
                this.copyBeanNotNull2Bean(entity, t);
                entity = t;
            } else {
                // 新增记录设置主键及默认属性后保存
                entity.setNewRecord(true);
                entity.setId(IDUtil.createUUID());
            }
            OperationResult result = beanValidator(entity);
            if (OperationResult.FAILURE.equals(result.getType())) {
                return result;
            }
            entity.setOperTime(new Date());
            entityService.save(entity, userId);
        } catch (OptimisticLockingFailureException e) {
            logger.error("乐观锁更新数据失败", e);
            return OperationResult.buildFailureResult("保存日志信息失败，数据已被他人更新，请刷新页面再操作");
        } catch (Exception e) {
            logger.error("保存日志信息失败", e);
            return OperationResult.buildFailureResult("保存日志信息异常");
        }
        return OperationResult.buildSuccessResult("保存日志信息成功");
    }

    /**
     * 删除数据
     *
     * @param entity 参数实体
     * @return OperationResult
     */
    @PreAuthorize("@pms.hasPermission('contract:common:tOperatingLog:del')")
    @PostMapping("delete")
    public @ResponseBody OperationResult delete(@RequestBody TOperatingLog entity) {
        try {
            entityService.delete(entity.getId());
        } catch (Exception e) {
            logger.error("删除日志信息失败", e);
            return OperationResult.buildFailureResult("删除日志信息失败");
        }
        return OperationResult.buildSuccessResult("删除日志信息成功");
    }

    /**
     * 批量删除数据
     *
     * @param ids 主键字符串
     * @return OperationResult
     */
    @PreAuthorize("@pms.hasPermission('contract:common:tOperatingLog:del')")
    @PostMapping("deleteAll")
    public @ResponseBody OperationResult deleteAll(@RequestBody List<String> ids) {
        List<String> deleteList = new ArrayList<>();
        for (String id : ids) {
            deleteList.add(id);
        }
        try {
            entityService.deleteBatch(deleteList);
        } catch (Exception e) {
            logger.error("批量删除日志信息失败", e);
            return OperationResult.buildFailureResult("批量删除日志信息失败");
        }
        return OperationResult.buildSuccessResult("批量删除日志信息成功");
    }
}
