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

import org.joda.time.DateTime;
import org.joda.time.Duration;
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 org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Api("日常请假管理")
@Service("keyDmLeave")
public class KeyDmLeaveServiceImpl {
    @Autowired
    private CommonService commonService;

    private static final String SUCCESS = "success";
    private final String namespace = "com.scpyun.platform.standard.jilinsscgsdp.keyDmLeave.";
    private final String leaveTypeNamespace = "com.scpyun.platform.standard.jilinsscgsdp.keyDmLeaveType.";
    private final String approvalRecordNamespace = "com.scpyun.platform.standard.jilinsscgsdp.keyDmLeaveApprovalRecord.";

    @ApiOperation(value = "部门分页查询请假申请列表", desc = "分页查询")
    public Page<Map<String, Object>> selectList(Page<Map<String, Object>> map) {
        if (map == null) map = new Page<>();
        Page<Map<String, Object>> map1 = commonService.findPage(namespace + "selectList", map);
        return map1;
    }
    @ApiOperation(value = "个人分页查询请假申请列表", desc = "分页查询")
    public Page<Map<String, Object>> selectListByUserId(Page<Map<String, Object>> map) {
        if (map == null) map = new Page<>();
        Page<Map<String, Object>> map1 = commonService.findPage(namespace + "selectListByUserId", map);
        return map1;
    }
    @ApiOperation(value = "待审核列表", desc = "查询待审核数据")
    public Page<Map<String, Object>> selectPendingList(Map<String, Object> map) {
        if (map == null) map = new HashMap<>();
        return commonService.findPage(namespace + "selectPendingList", map);
    }

    @ApiOperation(value = "保存请假申请", desc = "新增或修改，请假单保存")
    public String save(Map<String, Object> map) {
        if (map == null) throw new CustomException("参数不能为空");

        Object id = map.get("id");
        if (id == null || String.valueOf(id).trim().isEmpty()) {
            map.put("id", UUID.randomUUID().toString());
            String typeId = map.get("leave_type_id").toString();
            String typeName = commonService.getObject(leaveTypeNamespace + "selectLeaveTypeById", typeId);
            map.put("leave_type_name", typeName);
            map.put("status", 0); // 默认保存状态为0

            Object startDateObj = map.get("start_time");
            Object endDateObj = map.get("end_time");
            double durationDays = 0; // 初始化天数为0

            // 1. 非空判断 + 计算天数
            if (startDateObj != null && endDateObj != null) {
                try {
                    // 1. 解析字符串时间为DateTime
                    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
                    DateTime startDate = formatter.parseDateTime(startDateObj.toString());
                    DateTime endDate = formatter.parseDateTime(endDateObj.toString());

                    // 2. 计算时间差（毫秒），转成带小数的天数
                    Duration durationObj = new Duration(startDate, endDate);
                    long totalMillis = durationObj.getMillis();
                    // 关键：用86400000.0（浮点数）做除法，保留小数
                    durationDays = totalMillis / 86400000.0;
                    // 可选：保留1位小数（比如0.1天、4.5天），避免小数位数过多
                    durationDays = Math.round(durationDays * 10) / 10.0;

                    // 3. 存入map（小数天数）
                    map.put("duration", durationDays);
                } catch (IllegalArgumentException e) {
                    throw new CustomException("时间格式错误，应为yyyy-MM-dd HH:mm:ss");
                }
            } else {
                // 空值时默认存0.0，保持类型统一
                map.put("duration", 0.0);
            }
            if (commonService.insert(namespace + "insert", map) != 1) {
                throw new CustomException("保存失败");
            }
            // 如果请求中包含审批人信息，插入初始的审批记录到子表（jl_key_dm_leave_approval_record）
            try {
                Object approverId = map.get("approver_id");
                Object approverName = map.get("approver_name");
                if ((approverId != null && String.valueOf(approverId).trim().length() > 0) ||
                        (approverName != null && String.valueOf(approverName).trim().length() > 0)) {
                    Map<String, Object> approvalRecord = new HashMap<>();
                    approvalRecord.put("id", UUID.randomUUID().toString());
                    approvalRecord.put("leave_id", map.get("id"));
                    approvalRecord.put("node_index", 1);
                    approvalRecord.put("node_type", 1); // 1 = 流程节点
                    approvalRecord.put("approver_id", approverId == null ? null : String.valueOf(approverId));
                    approvalRecord.put("approver_name", approverName == null ? null : String.valueOf(approverName));
                    approvalRecord.put("approver_result", 0); // 0 未处理
                    approvalRecord.put("approver_time", null);
                    approvalRecord.put("status", 0); // 0 未操作
                    approvalRecord.put("comment", null);
                    approvalRecord.put("order_no", 1);
                    // 插入子表，mapper id 为 insert
                    commonService.insert(approvalRecordNamespace + "insert", approvalRecord);
                }
            } catch (Exception e) {
                // 子表插入异常不影响主表保存，但记录日志以便排查
                throw new CustomException("保存审批子表记录失败：" + e.getMessage());
            }
        } else {
            int aff = commonService.update(namespace + "update", map);
            if (aff < 0) {
                throw new CustomException("保存失败");
            }
        }
        return SUCCESS;
    }

    @ApiOperation(value = "提交请假申请", desc = "提交进入审批流程")
    public String submit(Map<String, Object> map) {
        if (map == null || map.get("id") == null) throw new CustomException("参数缺失");
        int aff = commonService.update(namespace + "submit", map);
        commonService.update(approvalRecordNamespace + "submit", map);
        if (aff < 0) throw new CustomException("提交失败");
        return SUCCESS;
    }

    @ApiOperation(value = "撤回请假申请", desc = "撤回未完成审批的申请")
    public String revoke(Map<String, Object> map) {
        if (map == null || map.get("id") == null) throw new CustomException("参数缺失");
        int aff = commonService.update(namespace + "revoke", map);
        commonService.update(approvalRecordNamespace + "revoke", map);
        if (aff < 0) throw new CustomException("撤回失败");
        return SUCCESS;
    }

    @ApiOperation(value = "审批通过", desc = "审批操作-通过")
    public String approve(Map<String, Object> map) {
        if (map == null || map.get("id") == null) throw new CustomException("参数缺失");
        int aff = commonService.update(namespace + "approve", map);
        commonService.update(namespace + "approve", map);
        if (aff < 0) throw new CustomException("审批失败");
        return SUCCESS;
    }

    @ApiOperation(value = "审批驳回", desc = "审批操作-驳回")
    public String reject(Map<String, Object> map) {
        if (map == null || map.get("id") == null) throw new CustomException("参数缺失");
        int aff = commonService.update(namespace + "reject", map);
        if (aff < 0) throw new CustomException("驳回失败");
        return SUCCESS;
    }

    @ApiOperation(value = "获取请假详情（含审批记录）", desc = "获取详情")
    public Map<String, Object> getById(Map<String, Object> map) {
        if (map == null || map.get("id") == null) throw new CustomException("参数缺失");
        Map<String, Object> ret = new HashMap<>();
        Map<String, Object> app = commonService.getObject(namespace + "getById", map);
        ret.putAll(app == null ? new HashMap<>() : app);
        // 子表：审批记录
        List<Map<String, Object>> approvals = commonService.findList(approvalRecordNamespace + "selectApprovalRecords", map);
        approvals = approvals == null ? new java.util.ArrayList<>() : approvals;
        ret.put("approvals", approvals);

        // 将子表统一放入 subTables 集合，便于前端区分不同子表
        Map<String, List<Map<String, Object>>> subTables = new HashMap<>();
        subTables.put("approvalRecords", approvals);
        ret.put("subTables", subTables);
        return ret;
    }

    @ApiOperation(value = "审批历史查询", desc = "查询审批历史")
    public Page<Map<String, Object>> selectApprovalHistory(Map<String, Object> map) {
        if (map == null) map = new HashMap<>();
        return commonService.findPage(approvalRecordNamespace + "selectApprovalHistory", map);
    }

    @ApiOperation(value = "请假统计", desc = "按人员统计已通过请假天数")
    public List<Map<String, Object>> selectStats(Map<String, Object> map) {
        if (map == null) map = new HashMap<>();
        return commonService.findList(namespace + "selectStats", map);
    }
}


