package cn.quant.andy;

import cn.quant.andy.jpa.entity.EntityConstant;
import cn.quant.andy.jpa.mybatis.mapper.SummaryMapper;
import cn.quant.spring.context.ServerApplicationContext;
import cn.quant.spring.util.CommonUtils;
import cn.quant.spring.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2021/7/19 0019.
 */

public class SummaryRepository {

    private static final Logger logger = LoggerFactory.getLogger(SummaryRepository.class);


    private ServerApplicationContext context;

    private List<String> fields;

    private Integer postDateIndex;

    private SummaryMapper mapper;

    /**
     * @param fields  - 导入数据对应的表字段
     * @param index   - 代表入账时间的字段索引
     * @param mapper
     * @param context
     */
    public SummaryRepository(List<String> fields, int index, SummaryMapper mapper, ServerApplicationContext context) {
        this.fields = fields;
        this.mapper = mapper;
        this.context = context;
        this.postDateIndex = index;
    }

    public List<String> fields() {
        return this.fields;
    }

    public void importData(String base, Integer termNo, Object[] values) {
        HashMap<Object, Object> params = new HashMap<>();
        params.put(EntityConstant.TRANSACTION_ID, context.getIdentitySequencer().nextId());
        params.put(EntityConstant.BASE_CODE, base);
        params.put(EntityConstant.TERM_NO, termNo);

        Date now = DateUtils.now();

        LocalDateTime localDate = DateUtils.toLocalDateTime((Date) values[postDateIndex]);
        params.put(EntityConstant.POST_DATE, localDate.toLocalDate());
        params.put(EntityConstant.POST_TIME, localDate.toLocalTime());
        params.put(EntityConstant.IMPORT_TIME, now);
        params.put(EntityConstant.POSTED_FLAG, false);
        params.put(EntityConstant.CREATED_BY, EntityConstant.CREATED_BY_SYS);
        params.put(EntityConstant.CREATED_DATE, now);
        params.put(EntityConstant.MODIFIED_BY, EntityConstant.MODIFIED_BY_SYS);
        params.put(EntityConstant.MODIFIED_DATE, now);

        try {
            mapper.importData(String.join(",", fields), values, params);
        } catch (Exception e) {
            logger.error("Failed import data - {}, {}", Arrays.toString(values), e.getMessage());
            e.printStackTrace();
        }
    }
}
