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;

@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<>();
        return commonService.findPage(namespace + "selectList", 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) {

        if (map == null || map.get("office_code") == null) {
            throw new CustomException("缺少机构编码");
        }
        // 查询 sys_user 列表（通过 office_code 匹配本级及下属机构）
        List<Map<String, Object>> sysUsers = commonService.findList(namespace + "selectSysUserByOfficeCode", map);
        if (sysUsers == null) return SUCCESS;
        for (Map<String, Object> u : sysUsers) {
            if (u == null) continue;
            Map<String, Object> byIdParam = new HashMap<>();
            byIdParam.put("id", u.get("id"));
            Map<String, Object> exists = commonService.getObject(namespace + "getById", byIdParam);
            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("office_id", u.get("office_id"));
                ins.put("name", u.get("name"));
                ins.put("gh", u.get("no"));
                ins.put("email", u.get("email"));
                ins.put("phone", u.get("phone"));
                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<>();
        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("orgId", pos.get("area_id"));
//        }
        return commonService.findPage(namespace + "selectUserMultiSelectorList", map);
    }
}


