package com.beagle.informix.service.impl;

import cn.hutool.json.JSONUtil;
import com.beagle.informix.entity.jpa.Vccinfo;
import com.beagle.informix.repository.VccinfoDao;
import com.beagle.informix.service.InformixService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;

/**
 * Caused by: java.sql.SQLException: Transactions not supported
 * ifx事务默认不开启，需要使用命令 通过ontape -s -B dbname来设置，注意不是服务名，而是数据库名
 *
 * Code-set conversion function failed due to illegal sequence or invalid value.
 * 启动失败字符集错误,暂时还未找到解决办法
 * @author lzz
 * date 2023/5/29
 * @version 1.0
 * description:
 */
@Slf4j
@Service("informixHibernateService")
public class InformixHibernateServiceImpl implements InformixService {
    @Resource
    private VccinfoDao vccinfoDao;
    @Resource
    private ResourceLoader resourceLoader;
    @Override
    @Transactional
    public void doConnectJob() throws Exception{
        insert();
//         update();
//         query();
//         delete();
    }
    private void insert() throws Exception{
        Vccinfo vccinfo = new Vccinfo();
//        vccinfo.setVId(23);
        vccinfo.setEffective(1);
        vccinfo.setVName("hibernate");
        vccinfo.setIvrMax(1);
        vccinfo.setAgentMax(1);
        vccinfo.setUpdateKey("jpa key");
        // 组装clob
        vccinfo.setTClob("@Ddsfsdferewr");
        // 组装blob数据
        // 处理blob字段
        // proxy 处理blob字段时，存放二进制文件（exe），打开异常,存放文本时正常
        org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:test1.doc");
        File inputStream = resource.getFile();
        try (FileInputStream fis = new FileInputStream(inputStream)){
            vccinfo.setTBlob(fis.readAllBytes());
        }
        // insert
        vccinfoDao.addVccinfo(vccinfo);
    }

    private void update(int id) {
        Vccinfo vccinfo = new Vccinfo();
        vccinfo.setVId(id);
        vccinfoDao.updateVccinfo(vccinfo);
    }
    private void query(int id) {


        List<Vccinfo> vccinfoList = vccinfoDao.getAllVccInfo();
        log.info("queryAll：{}",JSONUtil.toJsonStr(vccinfoDao.getAllVccInfo()));
        log.info("queryById：{}",JSONUtil.toJsonStr(vccinfoDao.getVccInfoById(id)));
    }
    private void delete(int id) {
        vccinfoDao.deleteVccinfo(id);
    }
}
