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

import com.alibaba.fastjson.JSONObject;
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("keyPersonVisitRecord")
public class KeyPersonVisitRecordServiceImpl {
    @Autowired
    private CommonService commonService;

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

    @ApiOperation(value = "回访记录列表", desc = "回访记录列表（含数据范围、排序）")
    public Page<Map<String, Object>> findVisitRecordList(Page<Map<String, Object>> page) {
        Map<String, Object> params = page.getParams() == null ? new HashMap<>() : page.getParams();
        // 兼容前端入参 { params:{...}, pageNo, pageSize }，有些网关会再包一层 params
        Object inner = params.get("params");
        if (inner instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> innerParams = (Map<String, Object>) inner;
            Map<String, Object> merged = new java.util.HashMap<>(params);
            merged.remove("params");
            merged.putAll(innerParams);
            params = merged;
        }
        // 回访状态必传
        Object doStatus = params.get("do_status");
        if (doStatus == null || String.valueOf(doStatus).trim().isEmpty()) {
            throw new CustomException("回访状态必传");
        }
        Object _user = params.get("_user");
        if (_user != null) {
            Map<String, String> pos = DataScopeUtil.getPosition(_user);
            params.put("scope_grade", pos.get("grade"));
            params.put("scope_area_id", pos.get("area_id"));
        }
        page.setParams(params);
        // 根据重点人员类别分流：'6' -> 未成年人表，其它(含'2','3') -> 成人表
        String ratingDictType = params.get("rating_dict_type") == null ? null : String.valueOf(params.get("rating_dict_type"));
        String stmtId = "findVisitRecordListAdult";
        if ("6".equals(ratingDictType)) {
            stmtId = "findVisitRecordListMinor";
        }
        return commonService.findPage(namespace + stmtId, page);
    }

    @ApiOperation(value = "回访记录详情", desc = "人员基本、计划信息与历史记录")
    public Map<String, Object> getVisitRecordDetail(Map<String, Object> map) {
        Map<String, Object> detail = commonService.getObject(namespace + "getVisitRecordDetail", map);
        if (detail == null) {
            throw new CustomException("未找到记录");
        }
        // 历史列表改为基于详情中的 key_person_id 查询，避免依赖入参方式
        Map<String, Object> historyParam = new HashMap<>();
        historyParam.put("key_person_id", detail.get("key_person_id"));
        List<Map<String, Object>> history = commonService.findList(namespace + "selectVisitHistory", historyParam);
        detail.put("history", history);
        return detail;
    }

    @ApiOperation(value = "历史回访记录分页", desc = "按人员分页查询历史回访记录")
    public Page<Map<String, Object>> selectVisitHistoryPage(Page<Map<String, Object>> page) {
        Map<String, Object> params = page.getParams() == null ? new HashMap<>() : page.getParams();
        Object inner = params.get("params");
        if (inner instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> innerParams = (Map<String, Object>) inner;
            Map<String, Object> merged = new java.util.HashMap<>(params);
            merged.remove("params");
            merged.putAll(innerParams);
            params = merged;
        }
        page.setParams(params);
        return commonService.findPage(namespace + "selectVisitHistoryPage", page);
    }
    @ApiOperation(value = "获取待办统计", desc = "返回正常待办与临期待办数量")
    public Map<String, Object> getPendingStats(Map<String, Object> map) {
        Map<String, Object> params = map == null ? new HashMap<>() : new HashMap<>(map);
        Object _user = params.get("_user");
        if (_user != null) {
            Map<String, String> pos = DataScopeUtil.getPosition(_user);
            params.put("scope_grade", pos.get("grade"));
            params.put("scope_area_id", pos.get("area_id"));
        }
        // 固定统计待办
        params.put("do_status", "0");
        return commonService.getObject(namespace + "getPendingStats", params);
    }

    @ApiOperation(value = "办理回访（更新当前记录）", desc = "按主键更新当前记录并标记，重置同人其它记录的历史标记")
    public String insertVisitRecord(Map<String, Object> map) {
        // 必填校验
        if (map.get("key_person_id") == null || map.get("key_person_visit_id") == null) {
            throw new CustomException("缺少关键参数");
        }
        if (map.get("id") == null || String.valueOf(map.get("id")).trim().isEmpty()) {
            throw new CustomException("缺少当前回访记录主键id");
        }
        // 直接按主键更新当前记录为已回访，并写入办理信息
        int r = commonService.update(namespace + "updateVisitRecordById", map);
        if (r != 1) {
            throw new CustomException("保存失败");
        }
        // 同人其他记录的 is_history 置为 0
        commonService.update(namespace + "resetOtherHistoryByKeyPerson", map);
        return SUCCESS;
    }

    @ApiOperation(value = "获取回访按钮权限", desc = "返回页面按钮权限映射")
    public Map getVisitButtonPower(Map<String, Object> map) {
        Object _user = map == null ? null : map.get("_user");
        if (_user == null) {
            return new java.util.HashMap<>();
        }
        return DataScopeUtil.getButtonPower(_user);
    }
}
