package cc.smtweb.system.canal.file.impl;

import cc.smtweb.framework.core.common.CanalVO;
import cc.smtweb.framework.core.common.SwEnum;
import cc.smtweb.framework.core.util.StringUtil;
import cc.smtweb.system.canal.file.common.AbstractFileWork;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author yaoq
 * @Date 2022年09月20日 10:29
 * @Description
 */
public class MySqlFileWork extends AbstractFileWork {

    @Override
    protected String getDbType() {
        return SwEnum.DbType.MYSQL.value;
    }

    @Override
    protected void doCreateSql(CanalVO canalVO) {
        getDbEngine().update(canalVO.getSql());
    }

    @Override
    protected void doAlterSql(CanalVO canalVO) {
        getDbEngine().update(canalVO.getSql());
    }

    @Override
    protected void doInsertSql(CanalVO canalVO) {
        Map<String, String> data = canalVO.getData();
        Set<String> fields = data.keySet();
        StringBuilder sql = new StringBuilder();
        List<Object> args = new ArrayList<>();
        sql.append("insert into ").append(canalVO.getSchemaName()).append(".").append(canalVO.getTableName()).append(" ( ");
        for (String field : fields) {
            sql.append(field).append(",");
        }
        sql.deleteCharAt(sql.length() - 1);
        sql.append(")").append("values").append(" ( ");
        for (String field : fields) {
            sql.append("?").append(",");
            String value = data.get(field);
            if (StringUtil.isEmpty(value)) {
                args.add(null);
            } else {
                args.add(value);
            }
        }
        sql.deleteCharAt(sql.length() - 1);
        sql.append(")");
        getDbEngine().update(sql.toString(), args.toArray());
    }

    @Override
    protected void doUpdateSql(CanalVO canalVO) {
        Map<String, String> data = canalVO.getData();
        Set<String> fields = data.keySet();
        StringBuilder sql = new StringBuilder();
        List<Object> args = new ArrayList<>();
        sql.append("update ").append(canalVO.getSchemaName()).append(".").append(canalVO.getTableName()).append(" set ");
        for (String field : fields) {
            if (field.equals(canalVO.getIdField())) continue;
            sql.append(field).append("=").append("?").append(",");
            String value = data.get(field);
            if (StringUtil.isEmpty(value)) {
                args.add(null);
            } else {
                args.add(value);
            }
        }
        sql.deleteCharAt(sql.length() - 1);
        sql.append(" where ").append(canalVO.getIdField()).append("=").append(canalVO.getId());
        getDbEngine().update(sql.toString(), args.toArray());
    }

    @Override
    protected void doDeleteSql(CanalVO canalVO) {
        getDbEngine().update("delete from " + canalVO.getSchemaName() + "." + canalVO.getTableName() + " where " + canalVO.getIdField() + " = ? ", canalVO.getId());
    }
}
