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.*;

@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();
        if (params == null) {
            params = new HashMap<>();
        }

        // 获取当前登录用户信息
        Object _user = params.get("_user");
        if (_user == null) {
            throw new CustomException("未获取到登录用户信息");
        }
        JSONObject user = JSONObject.parseObject(JSONObject.toJSONString(_user));
        String companyName = user.getString("company_name");
        if (companyName == null || companyName.trim().isEmpty()) {
            throw new CustomException("未获取到用户所属机构名称");
        }
        params.put("company_name", companyName);
        Map<String, String> pos = DataScopeUtil.getPosition(user);
        params.put("scope_grade", pos.get("grade"));
        params.put("scope_area_id", pos.get("area_id"));
        // 重置用户信息（用于数据权限）
        params = DataScopeUtil.resetUser(params);
        Map<String, Object> officeTypeInfo = DataScopeUtil.getOfficeType(_user);
        if (officeTypeInfo != null) {
            params.putAll(officeTypeInfo);
        }
        page.setParams(params);

        // 查询列表
        Page<Map<String, Object>> result = commonService.findPage(namespace + "findVisitRecordList", page);

        return result;
    }

    @ApiOperation(value = "获取人员信息（用于回访）", desc = "根据人员ID和类别获取人员基本信息")
    public Map<String, Object> getPersonInfoForVisit(Map<String, Object> map) {
        String personId = String.valueOf(map.get("person_id"));
        String ratingDictType = String.valueOf(map.get("rating_dict_type"));
        String sysType = String.valueOf(map.get("sys_type"));

        if (personId == null || "null".equals(personId)) {
            throw new CustomException("人员ID不能为空");
        }

        map.put("id", personId);
        map.put("rating_dict_type", ratingDictType);
        // 如果传入了sys_type，则传递给SQL用于动态选择表
        if (sysType != null && !"null".equals(sysType) && !sysType.trim().isEmpty()) {
            map.put("sys_type", sysType);
        }

        Map<String, Object> result = commonService.getObject(namespace + "getPersonInfoForVisit", map);
        if (result == null) {
            throw new CustomException("未找到人员信息");
        }

        return result;
    }

    @ApiOperation(value = "保存回访记录", desc = "保存回访记录，并更新历史记录状态")
    public String saveVisitRecord(Map<String, Object> map) {
        // 参数校验
        if (isBlank(map.get("key_person_id"))) {
            throw new CustomException("人员ID不能为空");
        }
        if (isBlank(map.get("visit_time"))) {
            throw new CustomException("回访时间不能为空");
        }
        if (isBlank(map.get("visit_record")) && isBlank(map.get("visit_img"))) {
            throw new CustomException("请填写回访记录或上传图片，至少一项");
        }
        if (isBlank(map.get("key_person_visit_id"))) {
            throw new CustomException("回访计划ID不能为空");
        }
        if (isBlank(map.get("rating_dict_type"))) {
            throw new CustomException("人员类别不能为空");
        }
        if (isBlank(map.get("sys_type_office_label")) || isBlank(map.get("sys_type_office_value"))) {
            throw new CustomException("请携带完整的部门信息");
        }
        if (isBlank(map.get("rating_type"))) {
            throw new CustomException("风险等级不能为空");
        }

        String keyPersonId = String.valueOf(map.get("key_person_id"));

        // 获取当前登录用户信息
        Object _user = map.get("_user");
        if (_user == null) {
            throw new CustomException("未获取到登录用户信息");
        }
        JSONObject user = JSONObject.parseObject(JSONObject.toJSONString(_user));
        Map<String, Object> officeTypeInfo = DataScopeUtil.getOfficeType(_user);
        if (officeTypeInfo != null) {
            map.putAll(officeTypeInfo);
        }
        // 设置回访人信息
        map.put("visit_user_id", user.getString("id"));
        map.put("visit_user_name", user.getString("name"));
        map.put("visit_user_company_name", user.getString("company_name"));
        map.put("visit_user_company_code", user.getString("company_code"));

        // 生成ID
        map.put("id", UUID.randomUUID().toString().replace("-", ""));

        // 先将该人员的其他回访记录标记为历史
        Map<String, Object> updateHistoryMap = new HashMap<>();
        updateHistoryMap.put("key_person_id", keyPersonId);
        updateHistoryMap.put("_user", _user);
        commonService.update(namespace + "updateVisitHistory", updateHistoryMap);

        // 插入新的回访记录
        int insertCount = commonService.insert(namespace + "insertVisitRecord", map);
        if (insertCount != 1) {
            throw new CustomException("保存回访记录失败");
        }

        return SUCCESS;
    }

    @ApiOperation(value = "查询回访历史（分页）", desc = "分页查询人员的回访历史记录")
    public Page<Map<String, Object>> selectVisitHistoryPage(Page<Map<String, Object>> page) {
        Map<String, Object> params = page.getParams();
        if (params == null) {
            params = new HashMap<>();
        }

        Object rawInnerParams = params.get("params");
        if (rawInnerParams instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> innerParams = new HashMap<>((Map<String, Object>) rawInnerParams);
            if (!innerParams.containsKey("_user") && params.get("_user") != null) {
                innerParams.put("_user", params.get("_user"));
            }
            params = innerParams;
        }

        String keyPersonId = String.valueOf(params.get("key_person_id"));
        if (keyPersonId == null || "null".equals(keyPersonId) || keyPersonId.trim().isEmpty()) {
            throw new CustomException("人员ID不能为空");
        }

        Object _user = params.get("_user");
        if (_user == null) {
            throw new CustomException("未获取到登录用户信息");
        }

        Map<String, Object> officeType = DataScopeUtil.getOfficeType(_user);
        if (officeType != null && !"综治中心".equals(officeType.get("office_label"))) {
            String label = String.valueOf(officeType.get("office_label"));
            Map<String, Object> _map = new HashMap<>();
            _map.put("label", label);
            List<Map<String, Object>> tlist = commonService.findList(namespace + "selectVisitOffice", _map);
//            List<String> _list = new ArrayList<>();
//            _list.add("0");
            if(tlist!=null&&tlist.size()>0){
                String v = String.valueOf(tlist.get(0).get("relation_office_label"));
//                String[] ss = v.split(",");
//                for (String s : ss) {
//                    _list.add(s);
//                }
                params.put("labels", v);
            }
//            params.put("sys_type_office_label", officeType.get("office_label"));
//            params.put("sys_type_office_value", officeType.get("office_value"));
        }

        page.setParams(params);
        return commonService.findPage(namespace + "selectVisitHistoryPage", page);
    }

    @ApiOperation(value = "查询回访记录详情", desc = "根据回访记录ID查询详情")
    public Map<String, Object> getVisitRecordDetail(Map<String, Object> map) {
        String id = String.valueOf(map.get("id"));
        if (id == null || "null".equals(id) || id.trim().isEmpty()) {
            throw new CustomException("回访记录ID不能为空");
        }

        Map<String, Object> result = commonService.getObject(namespace + "getVisitRecordDetail", map);
        if (result == null) {
            throw new CustomException("未找到回访记录");
        }

        return result;
    }

    /**
     * 计算回访状态和按钮可用性
     * 状态：0-无待访，1-正常待访，2-临期待访，3-超期待访
     */
    private void calculateVisitStatus(Map<String, Object> row) {
        try {
            // 获取回访计划信息
            Object visitStartDayObj = row.get("visit_start_day");
            Object visitEndDayObj = row.get("visit_end_day");
            Object overdueWarningDayObj = row.get("overdue_warning_day");

            if (visitStartDayObj == null || visitEndDayObj == null) {
                row.put("visit_status", "0");
                row.put("can_visit", false);
                return;
            }

            int visitStartDay = Integer.parseInt(String.valueOf(visitStartDayObj));
            int visitEndDay = Integer.parseInt(String.valueOf(visitEndDayObj));
            int overdueWarningDay = overdueWarningDayObj != null ?
                Integer.parseInt(String.valueOf(overdueWarningDayObj)) : 0;

            // 获取最后一次回访时间
            Object lastVisitTimeObj = row.get("last_visit_time");
            Date now = new Date();
            Date lastVisitTime = null;

            if (lastVisitTimeObj != null && !"null".equals(String.valueOf(lastVisitTimeObj))) {
                try {
                    if (lastVisitTimeObj instanceof Date) {
                        lastVisitTime = (Date) lastVisitTimeObj;
                    } else if (lastVisitTimeObj instanceof String) {
                        // 尝试解析字符串日期
                        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        lastVisitTime = sdf.parse((String) lastVisitTimeObj);
                    }
                } catch (Exception e) {
                    // 解析失败，使用当前时间
                }
            }

            // 如果没有回访记录，默认状态为正常待访
            if (lastVisitTime == null) {
                row.put("visit_status", "1");
                row.put("can_visit", true);
                return;
            }

            // 计算回访时间范围
            // 起始时间 = 上次回访时间 + visit_start_day
            // 结束时间 = 上次回访时间 + visit_end_day
            // 预警时间 = 结束时间 - overdue_warning_day
            Date startDate = addDays(lastVisitTime, visitStartDay);
            Date endDate = addDays(lastVisitTime, visitEndDay);
            Date warningDate = addDays(endDate, -overdueWarningDay);

            // 判断当前状态
            int visitStatus = 0; // 默认无待访
            boolean canVisit = false;

            // 使用日期比较（忽略时分秒）
            java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
            String nowDateStr = dateFormat.format(now);
            String startDateStr = dateFormat.format(startDate);
            String warningDateStr = dateFormat.format(warningDate);
            String endDateStr = dateFormat.format(endDate);

            if (nowDateStr.compareTo(startDateStr) < 0) {
                // 当前日期在起始日期之前，无待访
                visitStatus = 0;
                canVisit = false;
            } else if (nowDateStr.compareTo(warningDateStr) <= 0) {
                // 当前日期在起始日期和预警日期之间（包含），正常待访
                visitStatus = 1;
                canVisit = true;
            } else if (nowDateStr.compareTo(endDateStr) <= 0) {
                // 当前日期在预警日期和结束日期之间（包含），临期待访
                visitStatus = 2;
                canVisit = true;
            } else {
                // 当前日期超过结束日期，超期待访
                visitStatus = 3;
                canVisit = true;
            }

            row.put("visit_status", String.valueOf(visitStatus));
            row.put("can_visit", canVisit);

        } catch (Exception e) {
            // 计算失败，默认状态
            row.put("visit_status", "0");
            row.put("can_visit", false);
        }
    }

    /**
     * 日期加天数
     */
    private Date addDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_MONTH, days);
        return cal.getTime();
    }

    private boolean isBlank(Object value) {
        if (value == null) {
            return true;
        }
        String text = String.valueOf(value);
        return text == null || "null".equalsIgnoreCase(text) || text.trim().isEmpty();
    }
}
