package com.zhongshu.card.server.core.service.user;

import com.zhongshu.card.client.model.org.DepartmentModel;
import com.zhongshu.card.client.model.org.DepartmentParam;
import com.github.microservice.net.ResultContent;
import com.github.microservice.net.ResultMessage;
import com.zhongshu.card.client.model.org.OidAboutInfo;
import com.zhongshu.card.client.service.org.DepartmentService;
import com.zhongshu.card.client.utils.ITree;
import com.zhongshu.card.client.utils.TreeUtil;
import com.zhongshu.card.client.type.DataState;
import com.zhongshu.card.server.core.dao.org.DepartmentDao;
import com.zhongshu.card.server.core.domain.org.Department;
import com.zhongshu.card.server.core.domain.org.Organization;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.orgManager.OrganizationManagerServiceImpl;
import com.zhongshu.card.server.core.util.BeanUtils;
import com.zhongshu.card.server.core.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author TRX
 * @date 2024/6/3
 */
@Slf4j
@Service
public class DepartmentServiceImpl extends SuperService implements DepartmentService {

    @Autowired
    DepartmentDao departmentDao;

    @Autowired
    OrganizationManagerServiceImpl organizationManagerService;

    /**
     * 添加部门
     *
     * @param param
     * @return
     */
    @Override
    public ResultContent<Department> addDepartment(DepartmentParam param) {
        if (StringUtils.isEmpty(param.getOrgOid())) {
            return ResultContent.buildFail(String.format("oid不能为空"));
        }
        param.setOid(param.getOrgOid());
        OidAboutInfo aboutInfo = organizationManagerService.getOidAboutInfo(param.getOid());

        if (CommonUtil.longIsEmpty(param.getSort())) {
            param.setSort(1L);
        }
        if (StringUtils.isEmpty(param.getParentId())) {
            param.setParentId(ITree.ROOT_ID);
        }
        if (!param.getParentId().equals(ITree.ROOT_ID)) {
            Department temp = departmentDao.findTopById(param.getParentId());
            if (ObjectUtils.isEmpty(temp)) {
                return ResultContent.buildFail(String.format("上级部门ID不存在：%s", param.getParentId()));
            }
        }
        if (param.getState() == null) {
            param.setState(DataState.Enable);
        }
        Department department = null;
        if (StringUtils.isNotEmpty(param.getId())) {
            department = departmentDao.findTopById(param.getId());
            if (ObjectUtils.isEmpty(department)) {
                return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, param.getId()));
            }
            if (StringUtils.isNotEmpty(param.getCode())) {
                department = departmentDao.findTopByCodeAndOid(param.getCode(), department.getOid());
                if (ObjectUtils.isNotEmpty(department) && !department.getId().equals(param.getId())) {
                    return ResultContent.buildFail(String.format("%s code已存在", param.getCode()));
                }
            }
        } else {
            if (StringUtils.isNotEmpty(param.getCode())) {
                department = departmentDao.findTopByCodeAndOid(param.getCode(), param.getOid());
                if (ObjectUtils.isNotEmpty(department)) {
                    return ResultContent.buildFail(String.format("%s code已存在", param.getCode()));
                }
            }
            department = new Department();
        }
        BeanUtils.copyProperties(param, department);
        department.setProjectOid(aboutInfo.getProjectOid());
        department.setAboutOid(aboutInfo.getOid());
        department.setAboutAuthType(aboutInfo.getAuthType());
        departmentDao.save(department);
        return ResultContent.buildSuccess(department);
    }

    /**
     * 初始机构部门信息
     *
     * @param organization
     * @return
     */
    public ResultContent initOrgDepartment(Organization organization) {
        String oid = organization.getOid();
        List<Department> departments = departmentDao.findByParentIdAndOid(ITree.ROOT_ID, oid);
        if (ObjectUtils.isEmpty(departments)) {
            Department department = new Department();
            department.setOid(oid);
            department.setName(organization.getName());
            department.setParentId(ITree.ROOT_ID);
            departmentDao.save(department);
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 删除部门
     *
     * @param id
     * @return
     */
    @Override
    public ResultContent deleteDepartment(String id) {
        String oid = getCurrentOid();
        Department department = departmentDao.findTopById(id);
        if (ObjectUtils.isEmpty(department)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, id));
        }
        List<Department> childrens = departmentDao.findByParentIdAndOid(id, oid);
        if (ObjectUtils.isNotEmpty(childrens)) {
            return ResultContent.buildFail(String.format("%s 有下级部门，不能删除", department.getName()));
        }
        departmentDao.delete(department);
        return ResultContent.buildSuccess();
    }

    /**
     * 得到结构所有部门信息 (树形结构)
     *
     * @param oid
     * @return
     */
    @Override
    public ResultContent<List<ITree>> getDepartmentTree(String oid) {
        if (StringUtils.isEmpty(oid)) {
            return ResultContent.buildFail("oid不能为空");
        }
        List<Department> list = departmentDao.findByOidOrderBySortAsc(oid);
        List<ITree> models = list.stream().map(this::toModel).collect(Collectors.toList());
        List<ITree> iTrees = TreeUtil.buildTree(models, ITree.ROOT_ID);
        return ResultContent.buildSuccess(iTrees);
    }

    /**
     * 加载当前部门的所有上级部门（包括自己）
     *
     * @param id
     * @return
     */
    public List<DepartmentModel> getParents(String id) {
        List<Department> list = new ArrayList<>();
        loopLoad(id, list);
        List<DepartmentModel> models = list.stream().map(this::toModel).collect(Collectors.toList());
        if (ObjectUtils.isNotEmpty(models)) {
            Collections.reverse(models);
        }
        return models;
    }

    private void loopLoad(String id, List<Department> list) {
        Department entity = departmentDao.findTopById(id);
        if (ObjectUtils.isNotEmpty(entity)) {
            list.add(entity);
            if (StringUtils.isNotEmpty(entity.getParentId()) && !entity.getParentId().equals(ITree.ROOT_ID)) {
                loopLoad(entity.getParentId(), list);
            }
        }
    }

    public Department getProjectDepartmentByName(String projectOid, String name) {
        Department department = null;
        if (StringUtils.isNotEmpty(projectOid) && StringUtils.isNotEmpty(name)) {
            String[] arr = name.split("/");
            name = arr[arr.length - 1];
            department = departmentDao.findTopByProjectOidAndName(projectOid, name);
        }
        return department;
    }

    public DepartmentModel toModel(Department entity) {
        DepartmentModel model = null;
        if (ObjectUtils.isNotEmpty(entity)) {
            model = new DepartmentModel();
            BeanUtils.copyProperties(entity, model);
        }
        return model;
    }
}
