package io.gisbi.application.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import io.gisbi.application.system.domain.Organization;
import io.gisbi.application.system.mapper.OrganizationMapper;
import io.gisbi.application.system.service.IOrganizationService;
import io.gisbi.application.system.service.IUserService;
import io.gisbi.utils.AuthUtils;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;


import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 组织机构 服务实现类
 * </p>
 *
 * @author lilin
 * @since 2025-05-08
 */
@Service
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements IOrganizationService {

    @Resource
    private IUserService userService;

    @Resource
    private OrganizationMapper organizationMapper;

    public static final String DEFAULT_IS_VALID = "1";

    /***********************************
     * 用途说明：获取企业列表
     * 参数说明
     * id        企业id
     * orgName   部门名称
     * orgtype   组织类型：01-公司  02-部门
     * parentid   上级ID
     * 返回值说明:  企业列表集合
     ***********************************/
    @Override
    public List<Map<String, Object>> getOrganizations(String appId, String  orgtype, String parentid, String orgname) {
        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Organization::getParentid, parentid);
        queryWrapper.eq(Organization::getAppId, appId);
        queryWrapper.eq(Organization::getOrgtype, orgtype);
        //根据部门名称查询
        queryWrapper.like(StringUtils.isNotBlank(orgname), Organization::getOrgname, orgname);
        List<Map<String, Object>> listMap = this.listMaps(queryWrapper.orderByAsc(Organization::getOrgcode));

        if (listMap == null) {
            return new ArrayList<>();
        }

        for (Map<String, Object> item : listMap) {
            Object idObj = item.get("id");
            // 避免空指针
            if (idObj == null) {
                continue;
            }
            List<Map<String, Object>> childList = child(idObj.toString(), appId, orgname);
            item.put("childList", childList); // 添加新列 子集
//            if (childList != null && !childList.isEmpty()) {
//                listMap.add(item); // 仅保留有子节点的数据
//            }
        }
        return listMap;
    }


    /***********************************
     * 用途说明：获取部门结构树
     * 参数说明
     * parentid      上级id
     * orgname       (根据参数查询部门名称)
     * 返回值说明:  部门结构树
     ***********************************/
    private List<Map<String, Object>> child(String parentid, String appId, String orgname) {
        List<Map<String, Object>> listMap;

        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
        //根据上级id 查询
        queryWrapper.eq(Organization::getParentid, parentid);
        queryWrapper.eq(Organization::getAppId, appId);
        //根据部门名称查询
        queryWrapper.like(StringUtils.isNotBlank(orgname), Organization::getOrgname, orgname);

        listMap = this.listMaps(queryWrapper.orderByAsc(Organization::getOrgcode));
        //判断是否存在子集
        if (listMap != null && !listMap.isEmpty()) {
            //遍历表数据
            for (int i = 0; i < listMap.size(); i++) {
                //循环获取下一子集
                List<Map<String, Object>> childList = child(listMap.get(i).get("id").toString(), appId, orgname);
                //添加新列 子集
                listMap.get(i).put("childList", childList);
            }
        }
        return listMap;
    }

    /***********************************
     * 用途说明：根据ID查询信息
     * 参数说明
     * id              企业id
     * orgName        部门名称
     * 返回值说明:  系统部门框架对象
     ***********************************/
    @Override
    public Organization getOrganizationById(String id) {
        Organization organization=this.getById(id);
        return organization;
    }

    /***********************************
     * 用途说明：新增系统组织框架
     * 参数说明
     * Organization     系统组织框架对象
     * 返回值说明:  是否新增成功
     ***********************************/
    @Override
    public boolean addOrganization(Organization organization) {

        // 构建查询条件
        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
        Organization parent = null;
        int codeMax = 0;
        //查询最大的编号   判断是否存在父级id  有值 根据父级id查询   否则 根据父级id为0 查询
        queryWrapper.select(Organization::getOrgcode);
        if (StrUtil.isNotBlank(organization.getParentid())) {
            parent = this.getById(organization.getParentid());
            queryWrapper.eq(Organization::getParentid, organization.getParentid());
        } else {
            organization.setParentid("0");
            queryWrapper.eq(Organization::getParentid, "0");
        }
        List<Object> maxResult = this.listObjs(queryWrapper);
        if (!maxResult.isEmpty()) {
            String maxCodeStr = maxResult.get(0).toString();
            try {
                codeMax = Integer.parseInt(maxCodeStr.substring(maxCodeStr.length() - 2));
            } catch (NumberFormatException e) {
                // 记录日志并默认从 0 开始
                codeMax = 0;
            }
        }

        DecimalFormat df = new DecimalFormat("00");
        String code = df.format(codeMax + 1);

        if (parent != null) {
            code = parent.getOrgcode() + df.format(codeMax + 1);
        }

        if (StrUtil.isBlank(organization.getIsvaild())) {
            organization.setIsvaild(DEFAULT_IS_VALID);
        }
        //填写 编号
        organization.setOrgcode(code);
        //填写 当前用户名称
        organization.setLastmodifier(AuthUtils.getUser().getUserId().toString());
        //填写 当前日期
        organization.setLastmodifydate(LocalDateTime.now());

        return this.save(organization);
    }


}
