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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

@Api("办公用品入库管理")
@Service("keyDmInbound")
public class KeyDmInboundServiceImpl {
    @Autowired
    private CommonService commonService;

    private static final String SUCCESS = "success";
    private final String namespace = "com.scpyun.platform.standard.jilinsscgsdp.keyDmInbound.";
    private final String detailNamespace = "com.scpyun.platform.standard.jilinsscgsdp.keyDmInboundDetail.";
    private final String materialNamespace = "com.scpyun.platform.standard.jilinsscgsdp.keyDmMaterialLog.";
    @ApiOperation(value = "入库记录列表", desc = "分页查询")
    public Page<Map<String, Object>> selectList(Map<String, Object> map) {
        if (map == null) map = new HashMap<>();
        return commonService.findPage(namespace + "selectList", map);
    }

    @ApiOperation(value = "保存入库记录", desc = "新增或修改入库单及明细")
    public String save(Map<String, Object> map) {
        if (map == null) throw new CustomException("参数不能为空");
        Object id = map.get("id");
        List<Map<String, Object>> details = (List<Map<String, Object>>) map.get("details");
        if (id == null || String.valueOf(id).trim().isEmpty()) {
            System.out.println(map);
            map.put("id", UUID.randomUUID().toString());
            map.put("order_no",0);
            Instant instant = Instant.parse((String) map.get("inbound_date"));
            LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
            Date inbound_date = java.sql.Date.valueOf(localDate);
            map.put("inbound_date",inbound_date);
            map.put("inbound_status",0);
            if (commonService.insert(namespace + "insert", map) != 1) throw new CustomException("保存失败");

            if (details != null) {
                for (Map<String, Object> d : details) {
                    d.put("inbound_id", map.get("id"));
                    d.put("inbound_type", map.get("inbound_type"));
                    d.put("id",UUID.randomUUID().toString());
                    commonService.insert(detailNamespace + "insertDetail", d);
                }
            }
        } else {
            int aff = commonService.update(namespace + "update", map);
            if (aff < 0) throw new CustomException("保存失败");
            commonService.delete(namespace + "deleteDetailsByInboundId", map);
            if (details != null) {
                for (Map<String, Object> d : details) {
                    d.put("id",UUID.randomUUID().toString());
                    d.put("inbound_id", map.get("id"));
                    commonService.insert(detailNamespace + "insertDetail", d);
                }
            }
        }
        return SUCCESS;
    }

    @ApiOperation(value = "删除入库单", desc = "逻辑删除")
    public String delete(Map<String, Object> map) {
        if (map == null || map.get("id") == null) throw new CustomException("参数缺失");
        int aff = commonService.update(namespace + "delete", map);
        if (aff < 0) throw new CustomException("删除失败");
        return SUCCESS;
    }

    @ApiOperation(value = "执行入库", desc = "将入库单置为已入库，更新库存并写日志")
    public String doInbound(Map<String, Object> map) {
        if (map == null || map.get("id") == null) throw new CustomException("参数缺失");
        // 设置入库状态
        int aff = commonService.update(namespace + "doInbound", map);
        if (aff < 0) throw new CustomException("入库失败");
        Map<String, Object> ret = getById(map);
        ret.put("_user", map.get("_user"));
        // 更新库存明细：调用 mapper 更新库存和日志（mapper 内实现或逐条处理）

        commonService.update(namespace + "updateInventoryByInbound", ret);

        commonService.insert(materialNamespace + "insertLog", ret);
        return SUCCESS;
    }

    @ApiOperation(value = "待归还列表（来自申领）", desc = "查询待归还记录")
    public Page<Map<String, Object>> selectPendingReturnList(Map<String, Object> map) {
        if (map == null) map = new HashMap<>();
        return commonService.findPage(namespace + "selectPendingReturnList", map);
    }

    @ApiOperation(value = "处理归还", desc = "基于申领生成入库单并更新库存")
    public String processReturn(Map<String, Object> map) {
        if (map == null || map.get("id") == null) throw new CustomException("参数缺失");
        // 生成入库单
        commonService.insert(namespace + "insertInboundByReturn", map);
        // 更新库存
        commonService.update(namespace + "updateInventoryByReturn", map);
        // 写日志
        commonService.insert(namespace + "insertMaterialLogByReturn", map);
        return SUCCESS;
    }

    @ApiOperation(value = "库存查询", desc = "实时库存")
    public Page<Map<String, Object>> selectInventoryList(Map<String, Object> map) {
        if (map == null) map = new HashMap<>();
        return commonService.findPage(namespace + "selectInventoryList", map);
    }

    @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> rec = commonService.getObject(namespace + "getById", map);
        ret.putAll(rec == null ? new HashMap<>() : rec);
        List<Map<String, Object>> details = commonService.findList(detailNamespace+ "selectDetailsByInboundId", map);
        ret.put("details", details == null ? new java.util.ArrayList<>() : details);
        List<Map<String, Object>> logs = commonService.findList(namespace + "selectLogsByInboundId", map);
        ret.put("logs", logs == null ? new java.util.ArrayList<>() : logs);
        return ret;
    }
}


