package com.zhgd.xmgl.modules.basicdata.controller.admin;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhgd.annotation.OperLog;
import com.zhgd.jeecg.common.api.vo.Result;
import com.zhgd.xmgl.modules.basicdata.entity.ModuleTemplate;
import com.zhgd.xmgl.modules.basicdata.service.IModuleTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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


/**
 * @Title: Controller
 * @Description: 所属政务模块模板
 * @author： pds
 * @date：   2023-02-17
 * @version： V1.0
 */
@RestController
@RequestMapping("/xmgl/moduleTemplate")
@Slf4j
@Api(tags = "jxj设置政务所属模块模板")
public class ModuleTemplateController {
	@Autowired
	private IModuleTemplateService moduleTemplateService;


	
	/**
	  *   批量添加/修改
	 * @param moduleTemplates
	 * @return
	 */
	@OperLog(operModul = "政务模块模板管理", operType = "批量新增", operDesc = "批量添加/修改所属政务模块模板信息")
	@ApiOperation(value = " 批量添加/修改所属政务模块模板信息", notes = "批量添加所属政务模块模板信息" , httpMethod="POST")
	@PostMapping(value = "/saveOrUpdate")
	public Result<ModuleTemplate> saveOrUpdate(@RequestBody List<ModuleTemplate> moduleTemplates) {
		Result<ModuleTemplate> result = new Result<ModuleTemplate>();
		if (moduleTemplates == null || moduleTemplates.size() == 0) {
			result.error500("参数不可为空");
			return result;
		}
		String governmentSn = moduleTemplates.get(0).getGovernmentSn();
		List<Long> newIds = moduleTemplates.stream().map(m -> m.getModuleId()).collect(Collectors.toList());
		List<Long> oldIds = moduleTemplateService.list(Wrappers.<ModuleTemplate>lambdaQuery()
				.eq(ModuleTemplate::getGovernmentSn, governmentSn))
				.stream().map(m -> m.getModuleId()).collect(Collectors.toList());
		List<Long> addIds = new ArrayList<>();
		List<Long> delIds = new ArrayList<>();
		for (Long newId : newIds) {
			if (!oldIds.contains(newId)) {
				addIds.add(newId);
			}
		}
		for (Long oldId : oldIds) {
			if (!newIds.contains(oldId)) {
				delIds.add(oldId);
			}
		}
		if (delIds.size() > 0) {
			moduleTemplateService.remove(Wrappers.<ModuleTemplate>lambdaQuery()
					.eq(ModuleTemplate::getGovernmentSn, governmentSn)
					.in(ModuleTemplate::getModuleId, delIds));
		}
		if (addIds.size() > 0) {
			moduleTemplateService.saveBatch(moduleTemplates.stream().filter(m -> addIds.contains(m.getModuleId())).collect(Collectors.toList()));
		}
		result.success("操作成功！");
		return result;
	}
}
