package easydo.technology.service;

import easydo.technology.components.JdbcClient;
import easydo.technology.exception.BizException;
import easydo.technology.model.FlowNo;
import easydo.technology.utils.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Service
public class FlowNoService {
    private static final DateTimeFormatter DFY_MD = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter DFY_MD_2 = DateTimeFormatter.ofPattern("yyyyMMdd");
    @Resource
    JdbcClient jdbcClient;
    @Resource
    DataSource dataSource;

    public String getFlowNo(String type, Connection... connections) throws Exception {
        Connection connection = null;
        if (connections.length > 0) {
            connection = connections[0];
        } else {
            connection = dataSource.getConnection();
        }
        try {
            FlowNo flowNo = new FlowNo();
            flowNo.setType(type);
            flowNo = jdbcClient.getJdbcModel(flowNo, connection);

            DateTimeFormatter DFY_MD = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            DateTimeFormatter DFY_MD_2 = DateTimeFormatter.ofPattern("yyyyMMdd");
            String currDate = DFY_MD.format(LocalDateTime.now());
            String currDate2 = DFY_MD_2.format(LocalDateTime.now());

            String no;
            if (StringUtil.isNotEmpty(flowNo.getCurrDate()) && !flowNo.getCurrDate().equals(currDate)) {
                flowNo.setCurrDate(currDate);
                flowNo.setCurrSeq(1);
            } else {
                flowNo.setCurrSeq(flowNo.getCurrSeq() + 1);
            }


            if (StringUtil.isEmpty(flowNo.getCurrDate())) {
                String currSeq = String.format("%06d", flowNo.getCurrSeq());
                no = flowNo.getPrefix() + currSeq;
            } else {
                String currSeq = String.format("%05d", flowNo.getCurrSeq());
                no = flowNo.getPrefix() + currDate2 + currSeq;
            }

            flowNo.setCurrNo(no);

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("type", type);
            jdbcClient.jdbcUpdate(flowNo, paramMap, connection);
            return no;
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        } finally {
            if (connections.length == 0) {
                connection.close();
            }
        }

    }
}
