package org.jeecg.modules.jmreport.common;

import com.boman.domain.GenTableColumn;
import com.boman.domain.dto.AjaxResult;
import com.boman.gen.api.RemoteGenTableColumnService;
import org.jeecg.modules.jmreport.desreport.dao.JimuReportDbDao;
import org.jeecg.modules.jmreport.desreport.dao.JimuReportDbFieldDao;
import org.jeecg.modules.jmreport.desreport.entity.JmReportDb;
import org.jeecg.modules.jmreport.desreport.entity.JmReportDbField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.List;

import static com.boman.common.core.utils.obj.ObjectUtils.*;

/**
 * @author shiqian
 * @date 2021年08月17日 14:41
 **/
@Service
public class ColumnCovertService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ColumnCovertService.class);

    @Resource
    private JimuReportDbDao reportDbDao;
    @Resource
    private JimuReportDbFieldDao reportDbFieldDao;
    @Resource
    private RemoteGenTableColumnService remoteGenTableColumnService;

    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public List<JmReportDbField> columnCovert(String reportId, String tableName, String tableNameChn) {
        requireNonNull(reportId, "reportId is empty");
        requireNonNull(tableName, "tableName is empty");
        requireNonNull(tableNameChn, "tableNameChn is empty");
        List<JmReportDb> jmReportDbs = reportDbDao.selectList(reportId);
        requireNonNull(jmReportDbs, "jmReportDbs is empty");
        JmReportDb jmReportDb = jmReportDbs.get(0);
        String jmReportDbId = jmReportDb.getId();
        jmReportDb.setDbChName(tableNameChn);

        reportDbDao.update(jmReportDb);

        List<JmReportDbField> jmReportDbFields = reportDbFieldDao.listByDbId(jmReportDbId);
        List<GenTableColumn> genTableColumns = remoteGenTableColumnService.listColumnsByTableName(tableName);
        requireNonNull(genTableColumns, "genTableColumns is empty");

        for (JmReportDbField field : jmReportDbFields) {
            String fieldName = field.getFieldName();
            for (GenTableColumn column : genTableColumns) {
                if (fieldName.equalsIgnoreCase(column.getColumnName())) {
                    field.setFieldText(column.getColumnComment());
                    break;
                }
            }

            // 更改filedText
            reportDbFieldDao.update(field);
        }

        return jmReportDbFields;
    }


}
