package com.boman.web.core.service.update;

import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.utils.obj.ObjectUtils;
import com.boman.domain.GenTableColumn;
import com.boman.web.core.domain.TableContext;
import com.boman.web.core.mapper.StandardlyMapper;
import com.boman.web.core.utils.ColumnUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import static com.boman.common.core.utils.obj.ObjectUtils.escapeStr;
import static com.boman.common.core.utils.obj.ObjectUtils.requireNonNull;
import static com.boman.domain.constant.FormDataConstant.*;

/**
 * @author shiqian
 * @date 2021年04月01日 11:07
 **/
@Service
public class BaseUpdateServiceImpl implements IBaseUpdateService {

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

    @Autowired
    private StandardlyMapper mapper;

    /**
     * 功能描述: 批量修改, 默认需要更改的model，更改的字段类型和字段值都是一致的
     *
     * @param context 用到其中的表名和所有的列(用来判断是否需要转义字符)
     * @param idList  idList
     * @return int
     */
    @Override
    public int updateByIdList(TableContext context, List<Long> idList) {
        String tableName = requireNonNull(context.getTableName(), "表名为空");
        String pkName = requireNonNull(context.getPkName(), "主键名称为空");;
        requireNonNull(idList, "需要修改的idList为空");
        JSONObject commitData = requireNonNull(context.getCommitData(), "需要更改的参数为空");
        List<GenTableColumn> columns = context.getColumns();
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());

        ColumnUtils.packUpdateByAndTime(columns, commitData, currentTime, false);
        commitData = ObjectUtils.ifNullSetEmpty(escapeByQueryType(columns, commitData));

        return mapper.updateByIdList(tableName, pkName, idList, commitData);
    }

    private JSONObject escapeByQueryType(List<GenTableColumn> columns, JSONObject commitData) {
        requireNonNull(columns);
        JSONObject result = new JSONObject(columns.size());
        for (Map.Entry<String, Object> entry : commitData.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            for (GenTableColumn column : columns) {
                if (column.getColumnName().equalsIgnoreCase(key) && ObjectUtils.isNotEmpty(value)) {
                    value = covert(column.getColumnType(), String.valueOf(value));
                    result.put(key, value);
                }
            }
        }

        return result;
    }

    private String covert(String columnType, String value) {
        // false 不需要转义
        boolean needEscape = columnType.contains(VARCHAR) || columnType.contains(CHAR) || columnType.contains(BLOB)
                || columnType.contains(DATETIME) || columnType.contains(TIMESTAMP);
        return needEscape ? escapeStr(value) : value;
    }
}
