package easydo.technology.service;

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

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

@Component
public class FlowNoService {
    @Resource
    JdbcClient jdbcClient;
    @Resource
    DataSource dataSource;


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

            BusFlowNo flowno = new BusFlowNo();
            flowno.setType(type);
            flowno = jdbcClient.getJdbcModel(flowno, connection);
            String currDate = LocalDateUtil.localDateTimeFormatyMd(LocalDateTime.now());
            String currDate2 = LocalDateUtil.localDateTimeFormatyMd2(LocalDateTime.now());
            if (flowno.getCurrDate() == null || !flowno.getCurrDate().equals(currDate)) {
                flowno.setCurrDate(currDate);
                flowno.setCurrSeq(1);
            } else {
                flowno.setCurrSeq(flowno.getCurrSeq() + 1);
            }
            String currSeq = String.format("%05d", flowno.getCurrSeq());
            String no = flowno.getPrefix() + currDate2 + currSeq;
            flowno.setCurrNo(no);
            Map<String, Object> whereMap = new HashMap<>();
            whereMap.put("type", type);
            jdbcClient.jdbcUpdate(flowno, whereMap, connection);
            return no;
        } catch (Exception e) {
            throw e;
        } finally {
            if (connections.length == 0) {
                jdbcClient.finallyExecute(connection);
            }
        }
    }
}
