package com.xzzn.ems.service.impl;

import com.xzzn.common.utils.DateUtils;
import com.xzzn.common.utils.StringUtils;
import com.xzzn.ems.domain.SysBizRemark;
import com.xzzn.ems.domain.vo.BizRemarkSaveRequest;
import com.xzzn.ems.mapper.SysBizRemarkMapper;
import com.xzzn.ems.service.ISysBizRemarkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysBizRemarkServiceImpl implements ISysBizRemarkService
{
    @Autowired
    private SysBizRemarkMapper sysBizRemarkMapper;

    @Override
    public Map<String, String> getRemarkMap(String bizType, String bizKey1, List<String> bizKey2List)
    {
        if (StringUtils.isAnyBlank(bizType, bizKey1) || bizKey2List == null || bizKey2List.isEmpty())
        {
            return Collections.emptyMap();
        }
        List<SysBizRemark> remarkList = sysBizRemarkMapper.selectByBizKey2List(bizType, bizKey1, bizKey2List);
        Map<String, String> result = new LinkedHashMap<>();
        for (SysBizRemark item : remarkList)
        {
            result.put(item.getBizKey2(), StringUtils.nvl(item.getRemark(), ""));
        }
        return result;
    }

    @Override
    public int saveRemark(BizRemarkSaveRequest request, String username)
    {
        if (request == null || StringUtils.isAnyBlank(request.getBizType(), request.getBizKey1(), request.getBizKey2()))
        {
            return 0;
        }

        SysBizRemark existed = sysBizRemarkMapper.selectByBizKeys(request.getBizType(), request.getBizKey1(), request.getBizKey2());
        if (existed == null)
        {
            SysBizRemark bizRemark = new SysBizRemark();
            bizRemark.setBizType(request.getBizType());
            bizRemark.setBizKey1(request.getBizKey1());
            bizRemark.setBizKey2(request.getBizKey2());
            bizRemark.setRemark(StringUtils.nvl(request.getRemark(), ""));
            bizRemark.setCreateBy(username);
            bizRemark.setUpdateBy(username);
            bizRemark.setCreateTime(DateUtils.getNowDate());
            bizRemark.setUpdateTime(DateUtils.getNowDate());
            bizRemark.setDelFlag("0");
            return sysBizRemarkMapper.insertSysBizRemark(bizRemark);
        }

        existed.setRemark(StringUtils.nvl(request.getRemark(), ""));
        existed.setUpdateBy(username);
        existed.setUpdateTime(DateUtils.getNowDate());
        existed.setDelFlag("0");
        return sysBizRemarkMapper.updateSysBizRemark(existed);
    }
}
