package com.stdproject.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stdproject.common.OperationLog;
import com.stdproject.common.Result;
import com.stdproject.entity.AppOrganization;
import com.stdproject.service.IAppOrganizationService;
import com.stdproject.service.IAppUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 应用-组织机构 前端控制器
 * </p>
 *
 * @author StdProject
 * @since 2023-12-07
 */
@Tag(name = "组织管理", description = "组织添加、组织修改、组织删除、组织查询等功能，支持公司和部门两级树形结构")
@RestController
@RequestMapping("/api/org")
public class AppOrganizationController {

    @Autowired
    private IAppOrganizationService appOrganizationService;
    // 需要在类开头注入 IAppUserService
    @Autowired
    private IAppUserService appUserService;

    @Operation(summary = "查询公司结构树")
    @GetMapping("/getCompanyTree")
    @OperationLog(type = "06", module = "组织管理", description = "查询公司结构树")
    public Result<List<AppOrganization>> getCompanyTree() {
        QueryWrapper<AppOrganization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orgtype", "01");
        queryWrapper.eq("isvaild", "1");
        queryWrapper.orderByAsc("orgcode");        
        List<AppOrganization> children = appOrganizationService.list(queryWrapper);
        return Result.success(children);
    }

    @Operation(summary = "查询部门列表")
    @GetMapping("/getDepartmentList")
    @OperationLog(type = "06", module = "组织管理", description = "查询部门列表")
    public Result<List<AppOrganization>> getDepartmentList(@RequestParam String parentid,@RequestParam String keystr) {
        QueryWrapper<AppOrganization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orgtype", "02");
        queryWrapper.eq("parentid", parentid);
        queryWrapper.eq("isvaild", "1");
        if (StringUtils.hasText(keystr)) {
            queryWrapper.and(wrapper -> wrapper
                    .like("orgname", keystr)
                    .or().like("orgcode", keystr)
                    .or().like("description", keystr)
            );
        }
        queryWrapper.orderByAsc("orgcode");
        List<AppOrganization> children = appOrganizationService.list(queryWrapper);
        return Result.success(children);
    }



    @Operation(summary = "根据ID查询组织详情")
    @GetMapping("getDetailById/{id}")
    @OperationLog(type = "06", module = "组织管理", description = "根据ID查询组织详情")
    public Result<AppOrganization> getDetailById(@PathVariable String id) {
        AppOrganization organization = appOrganizationService.getById(id);
        return Result.success(organization);
    }


    @Operation(summary = "新增组织")
    @PostMapping("add")
    @OperationLog(type = "01", module = "组织管理", description = "新增组织")
    public Result<String> add(@RequestBody @Valid AppOrganization appOrganization) {
        // 设置默认值
        //生成新的组织编号  公司编号：010101  部门编号：0001
        appOrganization.setOrgcode(getNewOrgCode(appOrganization.getOrgtype(), appOrganization.getParentid()));
        //设置状态为有效
        appOrganization.setIsvaild("1");
        // 从当前登录用户上下文中获取用户名
        appOrganization.setLastmodifier(appUserService.getCurrentUsername());
        appOrganization.setLastmodifydate(LocalDateTime.now());
        boolean success = appOrganizationService.save(appOrganization);
        return success ? Result.success("新增成功") : Result.error("新增失败");
    }

    @Operation(summary = "修改组织")
    @PostMapping("update")
    @OperationLog(type = "02", module = "组织管理", description = "修改组织")
    public Result<String> update(@RequestBody @Valid AppOrganization appOrganization) {
        // 检查组织是否存在
        AppOrganization existOrg = appOrganizationService.getById(appOrganization.getId());
        if (existOrg == null) {
            return Result.error("组织不存在");
        }
        // 验证父级组织变更的合法性
        if (StringUtils.hasText(appOrganization.getParentid()) && !"0".equals(appOrganization.getParentid())) {
            // 不能将自己设为父级
            if (appOrganization.getId().equals(appOrganization.getParentid())) {
                return Result.error("不能将自己设为父级组织");
            }
            // 验证父级组织是否存在
            AppOrganization parent = appOrganizationService.getById(appOrganization.getParentid());
            if (parent == null || !"1".equals(parent.getIsvaild())) {
                return Result.error("父级组织不存在或已禁用");
            }
         
            if ("02".equals(parent.getOrgtype())) {
                return Result.error("部门下不能有子组织");
            }
        }
        appOrganization.setLastmodifier(appUserService.getCurrentUsername());
        appOrganization.setLastmodifydate(LocalDateTime.now());
        boolean success = appOrganizationService.updateById(appOrganization);
        return success ? Result.success("修改成功") : Result.error("修改失败");
    }

    @Operation(summary = "删除组织")
    @PostMapping("delete/{id}")
    @OperationLog(type = "03", module = "组织管理", description = "删除组织")
    public Result<String> delete(@PathVariable String id) {
        boolean success = appOrganizationService.removeById(id);
        return success ? Result.success("删除成功") : Result.error("删除失败");
    }

    /**
     * 根据组织类型和父节点生成新的组织编码
     *
     * @param orgType 组织类型："01"表示公司，"02"表示部门
     * @param parentId 父节点ID，新增部门时使用
     * @return 新的组织编码
     */
    private String getNewOrgCode(String orgType, String parentId) {
        if ("01".equals(orgType)) {
            // 公司类型：查找当前最大的公司编码并递增最后一级
            AppOrganization parentOrg = null;
            if (StringUtils.hasText(parentId) && !"0".equals(parentId)) {
                parentOrg = appOrganizationService.getById(parentId);
                if (parentOrg == null || !"1".equals(parentOrg.getIsvaild())) {
                    throw new IllegalArgumentException("无效的父级组织");
                }
            }

            // 获取父节点编码（顶级为“01”）
            String parentCode = parentOrg != null ? parentOrg.getOrgcode() : "01";

            // 获取当前父节点下的最大子节点编码
            String maxCompanyCode = getMaxCodeByParentId("01",parentId);

            int nextLevel = 1;
            if (maxCompanyCode != null && !maxCompanyCode.isEmpty()) {
                try {
                    // 提取最后两位
                    String lastTwo = maxCompanyCode.substring(maxCompanyCode.length() - 2);
                    nextLevel = Integer.parseInt(lastTwo) + 1;
                } catch (Exception e) {
                    nextLevel = 1; // 出错则重置为1
                }
            }

            if (nextLevel > 99) {
                throw new RuntimeException("公司编码已达上限，请联系管理员处理");
            }

            return parentCode + String.format("%02d", nextLevel);
        } else if ("02".equals(orgType) && StringUtils.hasText(parentId)) {
            // 部门类型：查找该公司下最大部门编码并递增
            AppOrganization parentOrg = appOrganizationService.getById(parentId);
            if (parentOrg == null || !"1".equals(parentOrg.getIsvaild())) {
                throw new IllegalArgumentException("无效的父级组织");
            }

            // 获取该父节点下最大部门编号
            String maxDeptCodeStr = getMaxCodeByParentId("02",parentId);
            int nextSeq = 1;

            if (maxDeptCodeStr != null && !maxDeptCodeStr.isEmpty()) {
                try {
                    nextSeq = Integer.parseInt(maxDeptCodeStr) + 1;
                } catch (NumberFormatException e) {
                    nextSeq = 1;
                }
            }

            if (nextSeq > 9999) {
                throw new RuntimeException("部门编码已达上限，请联系管理员处理");
            }

            return String.format("%04d", nextSeq);
        } else {
            throw new IllegalArgumentException("无法生成组织编码：参数不完整");
        }
    }


    private String getMaxCodeByParentId(String orgType,String parentId) {
        LambdaQueryWrapper<AppOrganization> queryWrapper = new LambdaQueryWrapper<AppOrganization>()
                .eq(AppOrganization::getOrgtype, orgType)
                .eq(AppOrganization::getParentid, parentId)
                .eq(AppOrganization::getIsvaild, "1")
                .orderByDesc(AppOrganization::getOrgcode)
                .select(AppOrganization::getOrgcode)
                .last("LIMIT 1");
        // 使用selectList方法获取符合条件的记录列表
        List<AppOrganization> list = appOrganizationService.list(queryWrapper);
        // 如果列表不为空，返回第一个记录的orgcode
        return list.isEmpty() ? null : list.get(0).getOrgcode();
    }

}