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

import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.constant.CacheConstants;
import com.boman.common.core.utils.SecurityUtils;
import com.boman.common.core.utils.obj.ObjectUtils;
import com.boman.common.redis.service.RedisService;
import com.boman.common.security.service.TokenService;
import com.boman.domain.constant.FormDataConstant;
import com.boman.domain.GenTableColumn;
import com.boman.system.api.model.LoginUser;
import com.boman.web.core.domain.RowResult;
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.Component;

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

/**
 * @author shiqian
 * @description
 * @date 2021年03月22日 11:25
 **/
@Component
public class BaseSaveServiceImpl implements IBaseSaveService {

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

    @Autowired
    private StandardlyMapper mapper;
    @Autowired
    private RedisService redisService;

    /**
     * 功能描述: 保存一行
     *
     * @param context context
     * @param maxId   最大的SEQ
     * @return com.boman.system.common.RowResult
     */
    @Override
    public RowResult insertRow(TableContext context, Long maxId) {
        List<GenTableColumn> columns = context.getColumns();
        JSONObject commitData = context.getCommitData();
        ColumnUtils.packUpdateByAndTime(columns, commitData, new Timestamp(System.currentTimeMillis()), true);
        // 处理默认值
        handlerDefaultValue(commitData, columns);

        commitData.put(context.getPkName(), maxId);
        int ret = mapper.insert(context.getTableName(), commitData);
        if (ret > 0) {
            LOGGER.info("保存成功，保存的数据为：{}", commitData);
            commitData.put(FormDataConstant.SUCCESS_CNT, ret);
            return RowResult.ok("保存成功", commitData);
        }

        return RowResult.error("失败");
    }

    /**
     * 功能描述: 新增的时候处理默认值， 从redis中拿到存在token中的userEnv对象，根据数据库中存的默认值的key，和userEnv中的key做比对，
     * 从中取出作为字段的默认值，redis中存userEnv的位置：{@link TokenService#packUserEnv(com.boman.system.api.model.LoginUser)}
     *
     * @param commitData commitData
     * @param columns 所有的列
     */
    private void handlerDefaultValue(JSONObject commitData, List<GenTableColumn> columns) {
        String token = SecurityUtils.getToken();
        LoginUser loginUser = redisService.getCacheObject(CacheConstants.LOGIN_TOKEN_KEY + token);
        JSONObject userEnv = loginUser.getUserEnv();
        for (GenTableColumn column : columns) {
            // 有默认值的列, 并且前台传过来的key中不包含
            if (ObjectUtils.isNotEmpty(column.getDefaultValue())
                    && !commitData.containsKey(column.getColumnName().toLowerCase())
                    && !commitData.containsKey(column.getColumnName().toUpperCase())) {
                String dbDefaultValue = column.getDefaultValue();
                String defaultValue = ColumnUtils.parseVariables(dbDefaultValue);
                String variables = dbDefaultValue.equalsIgnoreCase(defaultValue) ? dbDefaultValue : userEnv.getString(defaultValue);
                commitData.put(column.getColumnName(), variables);
            }
        }
    }


}
