package com.yifu.cloud.plus.v1.permission.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.permission.mapper.SysMenuMapper;
import com.yifu.cloud.plus.v1.permission.service.SysMenuService;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.permission.entity.SysMenu;
import com.yifu.cloud.plus.v1.yifu.permission.vo.SysMenuSearchVo;
import com.yifu.cloud.plus.v1.yifu.permission.vo.SysTaxVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 新权限-菜单表
 *
 * @author hyc
 * @date 2023-08-29 14:49:40
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

	/**
	 * 新权限-菜单表简单分页查询
	 *
	 * @param sysMenu 新权限-菜单表
	 * @return
	 */
	@Override
	public IPage<SysMenu> getSysMenuPage(Page<SysMenu> page, SysMenuSearchVo sysMenu) {
		return baseMapper.getSysMenuPage(page, sysMenu);
	}

	@Override
	public IPage<SysTaxVo> getSysTaxVoPage(Page<SysTaxVo> page, SysTaxVo vo) {
		return baseMapper.getSysTaxVoPage(page, vo);
	}

	/**
	 * 新增菜单表
	 *
	 * @param menu 新权限-菜单表
	 * @return
	 */
	@Override
	public R<Boolean> saveMenu(SysMenu menu) {
		if (Common.isEmpty(menu.getModelId())) {
			return R.failed("表单ID不可为空");
		}
		//判断表单id是否填写正确
		long menuIdCount = baseMapper.selectMenuId(menu.getModelId());
		if (menuIdCount < 1) {
			return R.failed("表单ID填写错误，请确认");
		}
		//判断view id是否填写正确并且要属于modeleID
		long viewIdCount = baseMapper.selectViewId(menu.getViewId(),menu.getModelId());
		if (viewIdCount < 1) {
			return R.failed("视图ID不存在或者不属于填写的表单id，请确认");
		}
		//唯一性校验--视图ID唯一
		long modelCount = baseMapper.selectCount(Wrappers.<SysMenu>query().lambda()
				.eq(SysMenu::getViewId, menu.getViewId())
				.eq(SysMenu::getDeleteStatus, CommonConstants.ONE_STRING));
		if (modelCount > 0) {
			return R.failed("已存在对应菜单的权限维度");
		}
		//是否开关为是的话，modelId只能有一个
		boolean errorFlag = isOpenCheck(menu);
		if (errorFlag) {
			return R.failed("只能存在一个开关状态为开的表单ID");
		}
		//判断菜单是否为一级菜单
		if (Common.isNotNull(menu.getMenuName()) && Common.isEmpty(menu.getMenuNameParent())) {
			//一级菜单的上级菜单id为0
			menu.setMenuParentId(CommonConstants.ZERO_STRING);
		}
		//错误信息
		StringBuilder errorStr = new StringBuilder();
		//权限维度
		StringBuilder permissionType = new StringBuilder();
		this.check(menu,errorStr,permissionType);
		//权限维度的控件id填写错误的话统一返回
		if (errorStr.length() > 0) {
			return R.failed(errorStr.substring(0, errorStr.lastIndexOf(";")));
		}
		menu.setPermissionType(permissionType.substring(0, permissionType.lastIndexOf("、")));
		int res = baseMapper.insert(menu);
		if (res <= CommonConstants.ZERO_INT) {
			return R.failed();
		}
		return R.ok();
	}

	@Override
	public R<Boolean> updateMenu(SysMenu menu) {
		//是否开关为是的话，modelId只能有一个
		boolean errorFlag = isOpenCheck(menu);
		if (errorFlag) {
			return R.failed("只能存在一个开关状态为开的表单ID");
		}
		//错误信息
		StringBuilder errorStr = new StringBuilder();
		//权限维度
		StringBuilder permissionType = new StringBuilder();
		this.check(menu,errorStr,permissionType);
		//权限维度的控件id填写错误的话统一返回
		if (errorStr.length() > 0) {
			return R.failed(errorStr.substring(0, errorStr.lastIndexOf(";")));
		}
		menu.setPermissionType(permissionType.substring(0, permissionType.lastIndexOf("、")));
		baseMapper.updateById(menu);
		return R.ok();
	}

	public void check(SysMenu menu,StringBuilder errorStr,StringBuilder permissionType) {
		//权限类型
		String name;
		//判断填写的控件id 是否属于表单的字段
		List<String> list = baseMapper.selectColumnList(menu.getModelId());
		if (!menu.getColumnIdList().isEmpty()) {
			for (String columnId : menu.getColumnIdList()) {
				name = columnId.substring(0, columnId.indexOf(";"));
				permissionType.append(name).append("、");
				//label为控件id；columnId格式为【客户权限;fd_3ae495ff53c560】
				String label = columnId.substring(columnId.indexOf(";") + 1);
				if (list.stream().noneMatch(e -> e.equals(label))) {
					errorStr.append(name).append("的控件id填写有误;");
				}
			}
		}
	}

	public boolean isOpenCheck(SysMenu menu) {
		if (Common.isNotNull(menu.getIsOpen()) && CommonConstants.ZERO_STRING.equals(menu.getIsOpen())) {
			if (Common.isNotNull(menu.getId())) {
				long modelCount = baseMapper.selectCount(Wrappers.<SysMenu>query().lambda()
						.eq(SysMenu::getModelId, menu.getModelId())
						.eq(SysMenu::getDeleteStatus, CommonConstants.ONE_STRING)
						.eq(SysMenu::getIsOpen, CommonConstants.ZERO_STRING)
						.ne(SysMenu::getId, menu.getId()));
				return modelCount > 0;
			}else {
				long modelCount = baseMapper.selectCount(Wrappers.<SysMenu>query().lambda()
						.eq(SysMenu::getModelId, menu.getModelId())
						.eq(SysMenu::getDeleteStatus, CommonConstants.ONE_STRING)
						.eq(SysMenu::getIsOpen, CommonConstants.ZERO_STRING));
				return modelCount > 0;
			}
		} else {
			return false;
		}
	}

}
