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.gen.domain.GenTableColumn;
import com.boman.system.api.model.LoginUser;
import com.boman.web.core.constant.FormDataConstant;
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();
        String pkName = context.getPkName();
        String tableName = context.getTableName();
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        commitData.put(pkName.toUpperCase(), maxId);

        ColumnUtils.packUpdateByAndTime(columns, commitData, currentTime);
        // 处理默认值
        handlerDefaultValue(commitData, columns);

        // 默认创建人和创建时间是都有的
        commitData.put(FormDataConstant.CREATE_TIME.toUpperCase(), currentTime);
        commitData.put(FormDataConstant.CREATE_BY.toUpperCase(), "张三");
        int ret = mapper.insert(tableName, commitData);
        if (ret > 0) {
            LOGGER.info("保存成功，保存的数据为：{}", commitData);
            commitData.put(FormDataConstant.SUCCESS_CNT, ret);
            return RowResult.ok("保存成功", commitData);
        }

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

    private void handlerDefaultValue(JSONObject jsonObject, 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())
                    && !jsonObject.containsKey(column.getColumnName().toLowerCase())
                    && !jsonObject.containsKey(column.getColumnName().toUpperCase())) {
                String dbDefaultValue = column.getDefaultValue();
                String defaultValue = ColumnUtils.parseVariables(dbDefaultValue);
                String variables = dbDefaultValue.equalsIgnoreCase(defaultValue) ? dbDefaultValue : userEnv.getString(defaultValue);
                jsonObject.put(column.getColumnName(), variables);
            }
        }
    }


}
