package com.scpyun.platform.jilinsscgsdp.service.impl;

import com.scpyun.base.bean.Page;
import com.scpyun.base.core.annotation.Api;
import com.scpyun.base.core.annotation.ApiOperation;
import com.scpyun.base.core.exception.CustomException;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.platform.jilinsscgsdp.utils.DataScopeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api("日常人员管理")
@Service("keyDmUser")
public class KeyDmUserServiceImpl {
    @Autowired
    private CommonService commonService;

    private static final String SUCCESS = "success";
    private final String namespace = "com.scpyun.platform.standard.jilinsscgsdp.keyDmUser.";

    @ApiOperation(value = "分页查询日常人员列表", desc = "分页")
    public Page<Map<String, Object>> selectList(Page<Map<String, Object>> map) {
        if (map == null) map = new Page<>();
        Map<String, Object> user = (Map<String, Object>) map.getParams().get("_user");
        if (user != null) {
            Map<String, String> pos = DataScopeUtil.getPosition(user);
            map.getParams().put("areaId", pos.get("area_id"));
            map.getParams().put("parentIds", user.get("parent_ids")+","+pos.get("area_id"));
        }
        return commonService.findPage(namespace + "selectList", map);
    }

    @ApiOperation(value = "分页查询日常人员可选上级领导列表", desc = "分页")
    public Page<Map<String, Object>> dmUserLeader(Page<Map<String, Object>> map) {
        if (map == null) map = new Page<>();
        return commonService.findPage(namespace + "selectUserLeaderById", map);
    }
    @ApiOperation(value = "分页查询日常人员可选上级部门列表", desc = "分页")
    public Page<Map<String, Object>> dmUserOffice(Page<Map<String, Object>> map) {
        if (map == null) map = new Page<>();
        return commonService.findPage(namespace + "selectUserOfficeById", map);
    }
    @ApiOperation(value = "保存日常人员（编辑）", desc = "保存单条记录")
    public String save(Map<String, Object> map) {
        if (map == null || map.get("id") == null) {
            throw new CustomException("参数缺失");
        }
        // 如果已存在则更新，否则插入（插入时 id 使用 sys_user.id）
        Map<String, Object> exists = commonService.getObject(namespace + "getById", map);
        if (exists == null) {
            if (commonService.insert(namespace + "insert", map) != 1) {
                throw new CustomException("保存失败");
            }
        } else {
            int aff = commonService.update(namespace + "updateSelective", map);
            if (aff < 0) throw new CustomException("保存失败");
        }
        return SUCCESS;
    }

    @ApiOperation(value = "根据机构编码同步用户", desc = "同步本级及下属机构用户")
    public String syncByOffice(Map<String, Object> map) {
        // 查询 sys_user 列表（通过当前机构匹配本级及下属机构）
        Map<String, Object> user = (Map<String, Object>) map.get("_user");
        if (user != null) {
            Map<String, String> pos = DataScopeUtil.getPosition(user);
            map.put("areaId", pos.get("area_id"));
            map.put("parentIds", user.get("parent_ids")+","+pos.get("area_id"));
        }
        List<Map<String, Object>> sysUsers = commonService.findList(namespace + "selectSysUserByOfficeCode", map);
        List<Map<String, Object>> haveUsers = commonService.findList(namespace + "selectDmUserByOfficeCode", map);
        if (sysUsers == null) return SUCCESS;
        Map<String, Map<String, Object>> sysUserMap = haveUsers.stream()
                .collect(Collectors.toMap(
                        item -> (String) item.get("id"), // 键提取器：从每个map中取出"id"的值作为新Map的键
                        item -> item,                    // 值提取器：每个map本身作为新Map的值
                        (existing, replacement) -> existing // 合并函数
                ));

        for (Map<String, Object> u : sysUsers) {
            if (u == null) continue;
            Map<String, Object> exists = sysUserMap.get(String.valueOf(u.get("id")));
            if (exists == null) {
                // prepare insert map: only copy available fields
                Map<String, Object> ins = new HashMap<>();
                ins.put("id", u.get("id"));
                ins.put("is_ext", 1);
                ins.put("is_leave", 0);
                ins.put("office_id", u.get("office_id"));
                ins.put("name", u.get("name"));
                if (u.get("no")!= null|| !"".equals(u.get("no"))) {
                    ins.put("gh", u.get("no"));
                }
                if (u.get("email")!= null|| !"".equals(u.get("email"))) {
                    ins.put("email", u.get("email"));
                }
                if (u.get("phone")!= null|| !"".equals(u.get("phone"))) {
                    ins.put("phone", u.get("phone"));
                }
                if (u.get("mobile")!= null|| !"".equals(u.get("mobile"))) {
                    ins.put("mobile", u.get("mobile"));
                }
                ins.put("is_used", 1);
                commonService.insert(namespace + "insert", ins);
            } else {
                // update: only update non-null fields from sys_user (null 不覆盖)
                Map<String, Object> upd = new HashMap<>();
                upd.put("id", u.get("id"));
                if (u.get("office_id") != null) upd.put("office_id", u.get("office_id"));
                if (u.get("email") != null) upd.put("email", u.get("email"));
                if (u.get("phone") != null) upd.put("phone", u.get("phone"));
                if (u.get("mobile") != null) upd.put("mobile", u.get("mobile"));
                // 保留原有 is_ext 标识（若希望覆盖可修改）
                commonService.update(namespace + "updateSelective", upd);
            }
        }
        return SUCCESS;
    }

    @ApiOperation(value = "人员选择器列表查询", desc = "根据机构和权限过滤人员")
    public Page<Map<String, Object>> selectUserSelectorList(Page<Map<String, Object>> map) {
        if (map == null) map = new Page<>();
        Map<String, Object> user = (Map<String, Object>) map.getParams().get("_user");
        if (user != null) {
            Map<String, String> pos = DataScopeUtil.getPosition(user);
            map.getParams().put("areaId", pos.get("area_id"));
            map.getParams().put("parentId", user.get("parent_id"));
        }
        return commonService.findPage(namespace + "selectUserSelectorList", map);
    }

    @ApiOperation(value = "人员多选器列表查询", desc = "所有在职人员")
    public Page<Map<String, Object>> selectUserMultiSelectorList(Page<Map<String, Object>> map) {
        if (map == null) map = new Page<>();
        Map<String, Object> user = (Map<String, Object>) map.getParams().get("_user");
        if (user != null) {
            Map<String, String> pos = DataScopeUtil.getPosition(user);
            map.getParams().put("areaId", pos.get("area_id"));
            map.getParams().put("parentId", user.get("parent_id"));
            map.getParams().put("parentIds", user.get("parent_ids")+","+pos.get("area_id"));
        }
        return commonService.findPage(namespace + "selectUserMultiSelectorList", map);
    }
}


