package com.boman.gen.service;

import com.boman.common.core.constant.UserConstants;
import com.boman.common.core.text.Convert;
import com.boman.common.core.utils.DateUtils;
import com.boman.common.core.utils.SecurityUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.core.utils.obj.ObjectUtils;
import com.boman.common.log.enums.BusinessType;
import com.boman.domain.constant.FormDataConstant;
import com.boman.domain.GenTable;
import com.boman.domain.GenTableColumn;
import com.boman.domain.TableSql;
import com.boman.gen.mapper.GenTableColumnMapper;
import com.boman.gen.mapper.GenTableMapper;
import com.boman.gen.mapper.TableSqlMapper;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 业务字段 服务层实现
 *
 * @author ruoyi
 */
@Service
public class GenTableColumnServiceImpl implements IGenTableColumnService {
    @Autowired
    private GenTableColumnMapper genTableColumnMapper;
    @Autowired
    private GenTableMapper genTableMapper;
    @Autowired
    private TableSqlMapper tableSqlMapper;

    /**
     * 查询业务字段列表
     *
     * @param tableId 业务字段编号
     * @return 业务字段集合
     */
    @Override
    public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId) {
        return genTableColumnMapper.selectGenTableColumnListByTableId(tableId);
    }

    @Override
    public List<GenTableColumn> selectGenTableColumnList(GenTableColumn genTableColumn) {
        return genTableColumnMapper.selectGenTableColumnList(genTableColumn);
    }

    /**
     * 根据gen_table_column的id查询字段对象
     *
     * @param columnId
     * @return
     */
    @Override
    public GenTableColumn selectGenTableColumnListByColumnId(Long columnId) {
        return genTableColumnMapper.selectGenTableColumnByColumnId(columnId);
    }

    /**
     /**
     * 根据字段编号获取字段详细信息, 把此外键对应的名称返回给前台
     * @param columnId pk
     */
    @Override
    public GenTableColumn getByIdWithForeignKey(Long columnId) {
        GenTableColumn tableColumn = selectGenTableColumnListByColumnId(columnId);
        String foreignKey = tableColumn.getForeignKey();
        if (ObjectUtils.isNotEmpty(foreignKey)) {
            GenTableColumn fkTableColumn = selectGenTableColumnListByColumnId(Long.parseLong(foreignKey));
            String columnName = fkTableColumn.getColumnName();
            Map<String, String> map = Maps.newHashMap();
            map.put(FormDataConstant.SINGLE_OBJ_NAME, foreignKey);
            map.put(FormDataConstant.SINGLE_OBJ_VALUE, columnName);
            tableColumn.setFkInfo(map);
        }

        return tableColumn;
    }

    /**
     * 查询业务字段列表
     *
     * @param tableIdList 业务字段编号List
     * @return 业务字段集合
     */
    @Override
    public List<GenTableColumn> listByTableIdList(List<Long> tableIdList) {
        if (null == tableIdList || tableIdList.isEmpty()) {
            return Collections.emptyList();
        }

        return genTableColumnMapper.listByTableIdList(tableIdList);
    }

    /**
     * 新增业务字段
     *
     * @param genTableColumn 业务字段信息
     * @return 结果
     */
    @Override
    public int insertGenTableColumn(GenTableColumn genTableColumn) {
        int i = genTableColumnMapper.insertGenTableColumn(genTableColumn);
        isAk(genTableColumn);
        insertCreateLog(genTableColumn, BusinessType.INSERT);
        return i;
    }

    /**
     * 修改业务字段
     *
     * @param genTableColumn 业务字段信息
     * @return 结果
     */
    @Override
    public int updateGenTableColumn(GenTableColumn genTableColumn) {
        isAk(genTableColumn);
        insertCreateLog(genTableColumn, BusinessType.UPDATE);
        return genTableColumnMapper.updateGenTableColumn(genTableColumn);
    }

    /**
     * 插入表sql日志
     */
    public void insertCreateLog(GenTableColumn genTableColumn, BusinessType type) {
        GenTable genTable = genTableMapper.selectGenTableById(genTableColumn.getTableId());
        //新增业务字段的同时新增一条建表sql修改日志
        TableSql tableSql = tableSqlMapper.selectTableSqlByTableId(genTableColumn.getTableId());
        String createLog = tableSql.getCreateLog();
        StringBuffer sb = new StringBuffer(createLog);
        //ALTER TABLE table_name ADD COLUMN column_name VARCHAR(100) DEFAULT NULL COMMENT '新加字段';
        sb.append("\r\n").append(DateUtils.getTime()).append(" ").append(SecurityUtils.getUsername()).append(" ALTER TABLE ").append(genTable.getTableName());
        if (BusinessType.INSERT.equals(type)){
            sb.append(" ADD COLUMN ").append(genTableColumn.getColumnName()).append(" ").append(genTableColumn.getColumnType());
            sb = genTableColumn.getDefaultValue() == null ? sb.append(" DEFAULT NULL COMMENT ") : sb.append(" DEFAULT '").append(genTableColumn.getDefaultValue()).append("' COMMENT '");
            sb.append(genTableColumn.getColumnComment()).append("';");
        }else if(BusinessType.UPDATE.equals(type)){
            sb.append(" MODIFY ").append(genTableColumn.getColumnName()).append(" ").append(genTableColumn.getColumnType()).append(";");
        }else if(BusinessType.DELETE.equals(type)){
            sb.append(" DROP ").append(genTableColumn.getColumnName()).append(";");
        }
        tableSql.setCreateLog(sb.toString());
        tableSqlMapper.updateTableSql(tableSql);
    }

    /**
     * 判断对象是否设置显示和输入字段
     *
     * @param genTableColumn
     */
    public void isAk(GenTableColumn genTableColumn) {
        //是否是输入
        String isIn = genTableColumn.getIsIn();
        //是否是显示
        String isOut = genTableColumn.getIsOut();
        List<GenTableColumn> genTableColumns = genTableColumnMapper.selectGenTableColumnListByTableId(genTableColumn.getTableId());
        GenTable genTable = new GenTable();
        if (UserConstants.YES.equals(isIn)) {
            //判断是否已经存在输入字段且不是同一个字段
            for (GenTableColumn tableColumn : genTableColumns) {
                if (UserConstants.YES.equals(tableColumn.getIsIn()) && !tableColumn.getColumnId().equals(genTableColumn.getColumnId())){
                    tableColumn.setIsIn("N");
                    genTableColumnMapper.updateGenTableColumn(tableColumn);
                    break;
                }
            }
            genTable.setTableId(genTableColumn.getTableId());
            genTable.setAkColumn(genTableColumn.getColumnId());
        }
        if (UserConstants.YES.equals(isOut)) {
            //判断是否已经存在显示字段且不是同一个字段
            for (GenTableColumn tableColumn : genTableColumns) {
                if (UserConstants.YES.equals(tableColumn.getIsOut()) && !tableColumn.getColumnId().equals(genTableColumn.getColumnId())){
                    tableColumn.setIsOut("N");
                    genTableColumnMapper.updateGenTableColumn(tableColumn);
                    break;
                }
            }
            genTable.setTableId(genTableColumn.getTableId());
            genTable.setDkColumn(genTableColumn.getColumnId());
        }
        if (genTable.getTableId() != null) {
            genTableMapper.updateGenTable(genTable);
        }
    }


    /**
     * 删除业务字段对象
     *
     * @param ids 表id
     * @return 结果
     */
    @Override
    public int deleteGenTableColumnByIds(String ids) {
        return genTableColumnMapper.deleteGenTableColumnByIds(Convert.toLongArray(ids));
    }

    /**
     * 删除业务字段对象
     *
     * @param ids 字段id
     * @return
     */
    @Override
    public int deleteGenTableColumnByColumnIds(String ids) {
        Long[] longs = Convert.toLongArray(ids);
        for (Long aLong : longs) {
            GenTableColumn genTableColumn = genTableColumnMapper.selectGenTableColumnByColumnId(aLong);
            insertCreateLog(genTableColumn,BusinessType.DELETE);
        }
        return genTableColumnMapper.deleteGenTableColumnByColumnIds(Convert.toLongArray(ids));
    }

    /**
     * 校验column_name是否重复
     *
     * @param genTableColumn
     * @return
     */
    @Override
    public String checkColumnNameUnique(GenTableColumn genTableColumn) {
        Long columnId = StringUtils.isNull(genTableColumn.getColumnId()) ? -1L : genTableColumn.getColumnId();
        GenTableColumn column = genTableColumnMapper.checkColumnNameUnique(genTableColumn);
        if (StringUtils.isNotNull(column) && !column.getColumnId().equals(columnId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}