package com.qunzhixinxi.hnqz.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qunzhixinxi.hnqz.admin.api.constant.UpmsType;
import com.qunzhixinxi.hnqz.admin.api.entity.WmTaskSubmissionRule;
import com.qunzhixinxi.hnqz.admin.mapper.WmTaskSubmissionRuleMapper;
import com.qunzhixinxi.hnqz.admin.service.WmTaskSubmissionRuleService;
import com.qunzhixinxi.hnqz.common.core.constant.CommonConstants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 任务提交规则服务实现
 *
 * @author jimmy
 * @version 1.0.0
 * @date 2022-08-15 18:07
 */
@Slf4j
@Service
@AllArgsConstructor
public class WmTaskSubmissionRuleServiceImpl extends ServiceImpl<WmTaskSubmissionRuleMapper, WmTaskSubmissionRule> implements WmTaskSubmissionRuleService {


	/**
	 * 获取部门限制信息
	 *
	 * @param deptId 部门id
	 * @return 限制信息
	 */
	@Override
	public Map<UpmsType.TaskCategory, List<WmTaskSubmissionRule>> listDeptTaskSubmissionRules(Integer deptId) {

		List<WmTaskSubmissionRule> rules = this.list(Wrappers.<WmTaskSubmissionRule>lambdaQuery().eq(WmTaskSubmissionRule::getDeptId, deptId));

		return rules.stream().collect(Collectors.groupingBy(rule -> rule.getSubCategory().getCategory()));
	}

	/**
	 * 初始化企业限制信息
	 *
	 * @param deptIds 企业id
	 * @return 初始化结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean initDeptTaskSubmissionRule(Collection<Integer> deptIds) {

		// 查询平台的配置
		List<WmTaskSubmissionRule> platformRules = this.list(Wrappers.<WmTaskSubmissionRule>lambdaQuery().eq(WmTaskSubmissionRule::getDeptId, CommonConstants.TENANT_ID_1));


		if (CollUtil.isEmpty(platformRules)) {
			return Boolean.FALSE;
		}


		List<WmTaskSubmissionRule> deptRules = new ArrayList<>(deptIds.size() * platformRules.size());


		deptIds.forEach(deptId -> {
			platformRules.forEach(r -> {
				WmTaskSubmissionRule deptRule = new WmTaskSubmissionRule();
				deptRule.setRule(r.getRule());
				deptRule.setDeptId(deptId);
				deptRule.setOptFlag(r.getOptFlag());
				deptRule.setSubCategory(r.getSubCategory());
				deptRules.add(deptRule);
			});

		});

		return this.saveBatch(deptRules);
	}
}
