package com.qunzhixinxi.hnqz.admin.controller;

import cn.hutool.core.collection.CollUtil;
import com.qunzhixinxi.hnqz.admin.api.constant.UpmsType;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.api.entity.WmTaskSubmissionRule;
import com.qunzhixinxi.hnqz.admin.service.SysDeptService;
import com.qunzhixinxi.hnqz.admin.service.WmTaskSubmissionRuleService;
import com.qunzhixinxi.hnqz.common.core.util.R;
import lombok.AllArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 任务提交规则前段控制器
 *
 * @author jimmy
 * @version 1.0.0
 * @date 2022-08-15 18:35
 */
@RestController
@AllArgsConstructor
@RequestMapping(value = "/task/submission/rule", produces = MediaType.APPLICATION_JSON_VALUE)
public class WmTaskSubmissionRuleController {

	private final WmTaskSubmissionRuleService taskSubmissionRuleService;
	private final SysDeptService deptService;


	/**
	 * 获取企业的限制
	 *
	 * @return 限制信息
	 */
	@GetMapping
	public R<Map<UpmsType.TaskCategory, List<WmTaskSubmissionRule>>> listDeptTaskSubmissionRules(@RequestParam(value = "deptId") Integer deptId) {

		return R.ok(taskSubmissionRuleService.listDeptTaskSubmissionRules(deptId));
	}

	/**
	 * 初始化企业限制
	 *
	 * @return 初始结果
	 */
	@PostMapping(value = "/init")
	public R<Boolean> initDeptTaskSubmissionRule() {

		List<SysDept> deptList = deptService.list();

		Set<Integer> deptIds = deptList.stream().map(SysDept::getDeptId).filter(id -> id != 1).collect(Collectors.toSet());

		if (CollUtil.isEmpty(deptIds)) {
			return R.failed(Boolean.FALSE);
		}

		return R.ok(taskSubmissionRuleService.initDeptTaskSubmissionRule(deptIds));

	}

	/**
	 * 更新企业的限制信息
	 *
	 * @return 更新结果
	 */
	@PutMapping
	@Transactional(rollbackFor = Exception.class)
	public R<Boolean> modifyDeptTaskSubmissionRule(@RequestBody List<WmTaskSubmissionRule> rules) {

		return R.ok(taskSubmissionRuleService.updateBatchById(rules));

	}

}
