package com.dk.mdm.service.core;

import com.dk.common.infrastructure.annotaiton.Pagination;
import com.dk.common.mapper.BaseMapper;
import com.dk.common.model.pojo.PageList;
import com.dk.common.response.ResponseCodeEnum;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.common.service.BaseService;
import com.dk.mdm.infrastructure.convert.core.OrganizationConvert;
import com.dk.mdm.mapper.core.OrganizationMapper;
import com.dk.mdm.model.pojo.core.Organization;
import com.dk.mdm.model.query.core.OrganizationQuery;
import com.dk.mdm.model.response.core.OrganizationResponse;
import com.dk.mdm.model.vo.core.OrganizationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class OrganizationService extends BaseService<Organization> {

	@Override
	public BaseMapper<Organization> getRepository() {
		return organizationMapper;
	}

	@Autowired
	private OrganizationMapper organizationMapper;

	@Autowired
	private OrganizationConvert organizationConvert;

	/**
	 * @desc   : 重写主键
	 * @author : 姜宁
	 * @date   : 2023/1/10 17:15
	 */
	@Override
	public String getPrimaryKey() {
		return "org_id";
	}

	/**
	 * @desc   : 条件查询
	 * @author : 姜宁
	 * @date   : 2023/1/10 17:19
	 */
	@Pagination
	public ResponseResultVO<PageList<OrganizationResponse>> selectByCond(OrganizationQuery organizationQuery) {
		return super.mergeListWithCount(organizationQuery, organizationMapper.selectByCond(organizationQuery),
				organizationMapper.countByCond(organizationQuery));
	}

	/**
	 * @desc   : 通过ID查询
	 * @author : 姜宁
	 * @date   : 2023/1/10 17:19
	 */
	public ResponseResultVO<OrganizationResponse> selectById(Integer orgId) {
		OrganizationQuery organizationQuery = new OrganizationQuery();
		organizationQuery.setOrgId(orgId);
		List<OrganizationResponse> orgList = organizationMapper.selectByCond(organizationQuery);
		if (CollectionUtils.isEmpty(orgList)){
			return ResponseResultUtil.error(ResponseCodeEnum.SELECT_NULL);
		}
		else{
			OrganizationResponse t = orgList.get(0);
			return ResponseResultUtil.success(t);
		}
	}

	/**
	 * @desc   : 保存方法
	 * @author : 姜宁
	 * @date   : 2023/1/11 8:50
	 */
	@Transactional(
			rollbackFor = {Exception.class}
	)
	public ResponseResultVO<?> insert(OrganizationVO organizationVO) {
		// 转化实体
		Organization organization = organizationConvert.convertToPo(organizationVO);
		// 如果不是最上级，获取上级部门的有效标识，上级无效则不能新建下级
		if(organization.getParentId() > 0) {
			// 获取上级部门的有效标识
			boolean flgValid = organizationMapper.selectFlgValidIdById(organization);
			// 上级无效则不能新建下级
//			if (!flgValid){
//				return ResponseResultUtil.error(ErrorCodeEnum.PARENT_ORGANIZATION_DISABLE.getCode(),
//						ErrorCodeEnum.PARENT_ORGANIZATION_DISABLE.getMessage());
//			}
		}
		// 判断编码是否重复
		Long count = organizationMapper.selectByCode(organization);
//		if(count > 0){
//			return ResponseResultUtil.error(ErrorCodeEnum.ORGANIZATION_CODE_EXISTS.getCode(),
//					ErrorCodeEnum.ORGANIZATION_CODE_EXISTS.getMessage());
//		}
		// 插入组织部门数据
		insert(organization);
		// 如果组织部门是最顶级，根据编码查出刚创建的部门的orgId,去更新topId
		if(organization.getTopId() == null || organization.getTopId() == 0){
			organizationMapper.updateOrgTopId(organization);
		}
		// 更新组织部门层级相关字段
		boolean result = organizationMapper.selectResetOrgLevel(organization);
		return result ? ResponseResultUtil.success(organization) :
				ResponseResultUtil.error(ResponseCodeEnum.INSERT_FAIL);
	}

	/**
	 * @desc   : 编辑方法
	 * @author : 姜宁
	 * @date   : 2023/1/11 8:51
	 */
	@Transactional(
			rollbackFor = {Exception.class}
	)
	public ResponseResultVO<Boolean> update(OrganizationVO organizationVO) {
		// 转化实体
		Organization organization = organizationConvert.convertToPo(organizationVO);
		// 判断编码是否重复
		Long count = organizationMapper.selectByCode(organization);
//		if(count > 0){
//			return ResponseResultUtil.error(ErrorCodeEnum.ORGANIZATION_CODE_EXISTS.getCode(),
//					ErrorCodeEnum.ORGANIZATION_CODE_EXISTS.getMessage());
//		}
		// 编辑数据
		super.update(organization);
		// 更新组织部门层级相关字段
		boolean result = organizationMapper.selectResetOrgLevel(organization);
		return result ? ResponseResultUtil.success() :
				ResponseResultUtil.error(ResponseCodeEnum.UPDATE_FAIL);
	}

	/**
	 * @desc   : 停用/启用
	 * @author : 姜宁
	 * @date   : 2023/1/12 13:49
	 */
	@Transactional(
			rollbackFor = {Exception.class}
	)
	public ResponseResultVO<Boolean> updateOrgFlgValid(Integer id, boolean flgValid) {

		// 根据ID获取当前组织部门下的所有下级
		OrganizationQuery organizationQuery = new OrganizationQuery();
		organizationQuery.setOrgId(id);
		// 根据id查询
		List<OrganizationResponse> orgList = organizationMapper.selectByCond(organizationQuery);
		if (CollectionUtils.isEmpty(orgList)) {
			return ResponseResultUtil.error(ResponseCodeEnum.ENABLE_FAIL);
		}
		// 取出level_lower,所有下级的id
		OrganizationResponse orgResponse = orgList.get(0);
		List<Integer> orgIdList = new ArrayList<>();
		// 将本级的组织部门也放入集合中
		orgIdList.add(id);
		// 如果是启用，则需要启用他所有上级的组织部门
		if (flgValid){
			List<Integer> levelUpperList = orgResponse.getLevelUpper();
			// 更新有效标识
			orgIdList.addAll(levelUpperList);
		}
		// 如果是停用，则需要停用他所有下级的组织部门
		else{
			List<Integer> levelLowerList = orgResponse.getLevelLower();
			// 更新有效标识
			orgIdList.addAll(levelLowerList);
		}
		// 实体赋值
		Organization organization = new Organization();
		organization.setFlgValid(flgValid);
		// 循环List,并且更新组织部门的有效标识
		for (Integer orgId : orgIdList) {
			// 更新有效标识
			organization.setOrgId(orgId);
			organizationMapper.updateOrgFlgValid(organization);
		}
		return ResponseResultUtil.success();
	}
}
