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

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api("办公用品领用管理")
@Service("keyDmBorrow")
public class KeyDmBorrowServiceImpl {
    @Autowired
    private CommonService commonService;

    private static final String SUCCESS = "success";
    private final String namespace = "com.scpyun.platform.standard.jilinsscgsdp.keyDmBorrow.";
    private final String detailNamespace = "com.scpyun.platform.standard.jilinsscgsdp.keyDmBorrowDetail.";
    private final String materialNamespace = "com.scpyun.platform.standard.jilinsscgsdp.keyDmMaterialLog.";
    @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 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 Page<Map<String, Object>> selectHistoryList(Map<String, Object> map) {
        if (map == null) map = new HashMap<>();
        return commonService.findPage(namespace + "selectHistoryList", map);
    }

    @ApiOperation(value = "保存申请（含明细）", desc = "新增或修改申请")
    public String save(Map<String, Object> map) {
        if (map == null) throw new CustomException("参数不能为空");
        System.out.println(map);
        Object id = map.get("id");
        List<Map<String, Object>> details = (List<Map<String, Object>>) map.get("details");
        Map<String, Object> user = (Map<String, Object>) map.get("_user");
        if (id == null || String.valueOf(id).trim().isEmpty()) {
            map.put("id",UUID.randomUUID().toString());
            map.put("application_no","borrow");
            map.put("applicant_id",user.get("id"));
            map.put("applicant_name", user.get("name"));
            map.put("department_id", user.get("company_id"));
            map.put("department_name", user.get("company_name"));
            //日期格式转换
            Instant instant = Instant.parse((String) map.get("expected_return_date"));
            LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
            Date expected_return_date = java.sql.Date.valueOf(localDate);
            map.put("expected_return_date",expected_return_date);

            map.put("approval_status", 0);
            map.put("issue_status", 0);
            map.put("is_used", 1);
            map.put("create_by", user.get("id"));
            map.put("create_time", new Date());
            map.put("order_no", 0);
            System.out.println(map);
            // insert application
            if (commonService.insert(namespace + "insert", map) != 1) throw new CustomException("保存失败");
            // insert details if any
            if (details != null) {
                for (Map<String, Object> d : details) {
                    d.put("id",UUID.randomUUID().toString());
                    d.put("application_id", map.get("id"));
                    d.put("material_id", "测试");
                    d.put("is_used", 1);
                    d.put("create_by", user.get("id"));
                    d.put("create_time", new Date());
                    d.put("order_no", 0);
                    commonService.insert( detailNamespace + "insertDetail", d);
                }
            }
        } else {
            int aff = commonService.update(namespace + "update", map);
            if (aff < 0) throw new CustomException("保存失败");
            // for simplicity, delete old details and insert new
            System.out.println("---------------------------------------------");
            System.out.println(id);
            commonService.delete(namespace + "deleteDetailsByApplicationId", map);
            if (details != null) {
                for (Map<String, Object> d : details) {
                    d.put("application_id", map.get("id"));
                    commonService.insert(namespace + "insertDetail", d);
                }
            }
        }
        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);
        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);
        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);
        if (aff < 0) throw new CustomException("审批失败");
        // 生成出库记录（mapper 实现）
        commonService.insert(namespace + "insertOutboundByApplication", map);
        // 更新库存（mapper 内部处理）
        commonService.update(namespace + "updateInventoryByApplication", map);
        // 写操作日志（mapper 内部处理）
        commonService.insert(namespace + "insertMaterialLogByApplication", map);
        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 = "根据ID查询申请及明细/日志", 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>> details = commonService.findList(detailNamespace + "selectDetailsByApplicationId", map);
        ret.put("details", details == null ? new java.util.ArrayList<>() : details);
        System.out.println(ret);
        // logs from material log by application relation
        List<Map<String, Object>> logs = commonService.findList(materialNamespace + "selectLogsByApplicationId", map);
        ret.put("logs", logs == null ? new java.util.ArrayList<>() : logs);
        System.out.println(ret);
        return ret;
    }
}


