package com.infoepoch.pms.dispatchassistant.controller.system;

import com.infoepoch.pms.dispatchassistant.common.component.BaseController;
import com.infoepoch.pms.dispatchassistant.common.component.Result;
import com.infoepoch.pms.dispatchassistant.common.exception.NotLoginException;
import com.infoepoch.pms.dispatchassistant.common.exception.ValidationException;
import com.infoepoch.pms.dispatchassistant.controller.basic.Auth;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.User;
import com.infoepoch.pms.dispatchassistant.domain.system.moaLog.IMoaLogRepository;
import com.infoepoch.pms.dispatchassistant.domain.system.moaLog.MoaLog;
import com.infoepoch.pms.dispatchassistant.domain.system.moaLog.MoaLogCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * MOA日志记录表Controller
 **/
@RestController
@RequestMapping("/api/moa-log")
public class MoaLogController extends BaseController {

    @Autowired
    private Auth auth;

    @Autowired
    private IMoaLogRepository repository;

    /**
     * 初始化
     **/
    @GetMapping("/init")
    public Result init() {
        return Result.success();
    }

    /**
     * 根据条件查询列表（可分页）
     **/
    @PostMapping("/list")
    public Result queryList(@RequestBody MoaLogCriteria criteria) {
        if (criteria.byPage()) {
            List<MoaLog> list = repository.selectCriteriaByPage(criteria, criteria.getPageIndex(), criteria.getPageSize());
            int totalCount = repository.selectCountByCriteria(criteria);
            Map<String, Object> map = new HashMap<>();
            map.put("totalCount", totalCount);
            map.put("list", list);
            return Result.successData(map);
        } else {
            if (!criteria.hasCriteria())
                throw new ValidationException("请输入查询条件。");
            return Result.successData(repository.selectByCriteria(criteria));
        }
    }

    /**
     * 新增MOA日志
     *
     * @param moaLog
     * @return
     */
    @PostMapping("/add-log")
    public Result addLog(@RequestBody MoaLog moaLog) throws NotLoginException {
        // 基础校验
        moaLog.verify();
        if (moaLog.getActionFlag() == null) {
            moaLog.setActionFlag(false);
        }
        User user = auth.getUserReq();
        moaLog.add(user.getId(), user.getDisplayName());
        MoaLogCriteria criteria = new MoaLogCriteria();
        criteria.setBusinessModule(moaLog.getBusinessModule());
        criteria.setDomainId(moaLog.getDomainId());
        criteria.setUserId(moaLog.getUserId());
        criteria.setStage(moaLog.getStage());
        MoaLog old = repository.selectOneByCriteria(criteria);
        if (old == null)
            repository.insert(moaLog);
        return Result.success();
    }

}
