package com.ebts.generator.service.impl;

import java.util.List;

import com.ebts.common.constant.ReturnConstants;
import com.ebts.common.exception.EbtsException;
import com.ebts.common.utils.SecurityUtils;
import com.ebts.common.utils.DateUtils;
import com.ebts.common.utils.SecurityUtils;
import com.ebts.common.utils.DateUtils;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.dao.SearchTableRoleDao;
import com.ebts.generator.entity.SearchTableRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ebts.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ebts.generator.entity.TopSearchColumn;
import com.ebts.generator.dao.TopSearchTableDao;
import com.ebts.generator.entity.TopSearchTable;
import com.ebts.generator.service.TopSearchTableService;

/**
 * top万能查询主Service业务层处理
 * 
 * @author clay
 * @date 2021-07-20
 */
@Service
public class TopSearchTableServiceImpl implements TopSearchTableService {
    private Logger logger = LoggerFactory.getLogger(TopSearchTableServiceImpl.class);

    @Autowired
    private TopSearchTableDao topSearchTableDao;
    @Autowired
    private SearchTableRoleDao searchTableRoleDao;

    /**
     * 查询top万能查询主
     * 
     * @param id top万能查询主ID
     * @return top万能查询主
     */
    @Override
    public ServerResult<TopSearchTable> selectTopSearchTableById(Long id) {
        try {
            TopSearchTable topSearchTable = topSearchTableDao.selectTopSearchTableById(id);
            List<SearchTableRole> roleList = searchTableRoleDao.selectSearchTableRoleList(new SearchTableRole());
            Long[] roles = new Long[roleList.size()] ;
            for (int i = 0; i < roleList.size(); i++) {
                roles[i] = roleList.get(i).getRoleId();
            }
            topSearchTable.setRoleIds(roles);
            if (topSearchTable != null){
                return new ServerResult<>(true,topSearchTable);
            }else {
                return new ServerResult<>(false, ReturnConstants.RESULT_EMPTY);
            }
        }catch (RuntimeException e){
            logger.error(e.getMessage());
            throw new EbtsException(ReturnConstants.OP_ERROR,e);
        }
    }

    /**
     * 查询top万能查询主列表
     * 
     * @param topSearchTable top万能查询主
     * @return top万能查询主
     */
    @Override
    public ServerResult<List<TopSearchTable>> selectTopSearchTableList(TopSearchTable topSearchTable) {
        try {
            List<TopSearchTable> topSearchTableList = topSearchTableDao.selectTopSearchTableList(topSearchTable);
            if (topSearchTableList.size()>0){
                return new ServerResult<>(true,topSearchTableList);
            }else {
                return new ServerResult<>(false,ReturnConstants.RESULT_EMPTY);
            }
        }catch (RuntimeException e){
            logger.error(e.getMessage());
            throw new EbtsException(ReturnConstants.OP_ERROR,e);
        }
    }

    /**
     * 新增top万能查询主
     * 
     * @param topSearchTable top万能查询主
     * @return 结果
     */
    @Transactional
    @Override
    public ServerResult<Integer> insertTopSearchTable(TopSearchTable topSearchTable) {
        try {
            topSearchTable.setCreateBy(SecurityUtils.getUserId());
            int renewal = topSearchTableDao.insertTopSearchTable(topSearchTable);
            if (insertTopSearchColumn(topSearchTable)){
                return new ServerResult<>(false,ReturnConstants.DB_EX);
            }
            if (renewal >0){
                return new ServerResult<>(true,renewal);
            }else {
                return new ServerResult<>(false,ReturnConstants.SYS_FAILL);
            }
        }catch (RuntimeException e){
            logger.error(e.getMessage());
            throw new EbtsException(ReturnConstants.OP_ERROR,e);
        }
    }

    /**
     * 修改top万能查询主
     * 
     * @param topSearchTable top万能查询主
     * @return 结果
     */
    @Transactional
    @Override
    public ServerResult<Integer> updateTopSearchTable(TopSearchTable topSearchTable) {
        try {
            topSearchTable.setUpdateBy(SecurityUtils.getUserId());
            topSearchTableDao.deleteTopSearchColumnBySearchTableId(topSearchTable.getId());
            if (insertTopSearchColumn(topSearchTable)){
                return new ServerResult<>(false,ReturnConstants.DB_EX);
            }
            List<SearchTableRole> searchTableRoles = new ArrayList<>();
            for (Long roleId : topSearchTable.getRoleIds()) {
                searchTableRoles.add(new SearchTableRole(topSearchTable.getId(),roleId));
            }
            searchTableRoleDao.deleteSearchTableRoleById(topSearchTable.getId());
            boolean renewalRole = inserTopTableRole(searchTableRoles);
            Integer renewal = topSearchTableDao.updateTopSearchTable(topSearchTable);
            if (renewal >0 && renewalRole){
                return new ServerResult<>(true,renewal);
            }else {
                return new ServerResult<>(false,ReturnConstants.OP_ERROR);
            }
        }catch (RuntimeException e){
            logger.error(e.getMessage());
            throw new EbtsException(ReturnConstants.OP_ERROR,e);
        }
    }

    @Override
    public List<TopSearchTable> selectDbTableListByNames(String[] tableNames) {
        try {
            return topSearchTableDao.selectDbTableListByNames(tableNames);
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            throw new EbtsException(ReturnConstants.OP_ERROR,e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importGenTable(List<TopSearchTable> tableList) {
        try {
            Long createBy = SecurityUtils.getUserId();
            for (TopSearchTable table : tableList) {
                String tableName = table.getTableName();
                table.setCreateBy(createBy);
                int row = topSearchTableDao.insertTopSearchTable(table);
                if (row>0){
                    List<TopSearchColumn> searchColumns = topSearchTableDao.selectDbTableColumnsByName(tableName);
                    for (TopSearchColumn searchColumn : searchColumns) {
                        searchColumn.setSearchTableId(table.getId());
                    }
                    if (searchColumns.size() > 0) {
                        topSearchTableDao.batchTopSearchColumn(searchColumns);
                    }
                }
            }
        }catch (RuntimeException e){
            logger.error(e.getMessage());
            throw new EbtsException("导入失败：" + e.getMessage(),e);
        }

    }

    /**
     * 批量删除top万能查询主
     * 
     * @param ids 需要删除的top万能查询主ID
     * @return 结果
     */
    @Transactional
    @Override
    public ServerResult<Integer> deleteTopSearchTableByIds(Long[] ids) {
        try {
            //批量删除子表数据
            topSearchTableDao.deleteTopSearchColumnBySearchTableIds(ids);
            Integer renewal = topSearchTableDao.deleteTopSearchTableByIds(ids);
            if (renewal >0){
                return new ServerResult<>(true,renewal);
            }else {
                return new ServerResult<>(false,ReturnConstants.SYS_FAILL);
            }
        }catch (RuntimeException e){
            logger.error(e.getMessage());
            throw new EbtsException(ReturnConstants.OP_ERROR,e);
        }
    }

    /**
     * 删除top万能查询主信息
     * 
     * @param id top万能查询主ID
     * @return 结果
     */
    @Override
    public ServerResult<Integer> deleteTopSearchTableById(Long id) {
        try {
        //删除子表数据
        topSearchTableDao.deleteTopSearchColumnBySearchTableId(id);
            Integer renewal = topSearchTableDao.deleteTopSearchTableById(id);
            if (renewal >0){
                return new ServerResult<>(true,renewal);
            }else {
                return new ServerResult<>(false,ReturnConstants.SYS_FAILL);
            }
        }catch (RuntimeException e){
            logger.error(e.getMessage());
            throw new EbtsException(ReturnConstants.OP_ERROR,e);
        }
    }
    public boolean inserTopTableRole(List<SearchTableRole> roleList){
        if (StringUtils.isNotNull(roleList)){
            Integer renewal = searchTableRoleDao.batchSearchTableRole(roleList);
            if (renewal>0){
                return true;
            }
        }
        return false;
    }

    /**
     * 新增top万能查询字段信息
     * 
     * @param topSearchTable top万能查询主对象
     */
    public boolean insertTopSearchColumn(TopSearchTable topSearchTable) {
        List<TopSearchColumn> topSearchColumnList = topSearchTable.getTopSearchColumnList();
        Long id = topSearchTable.getId();
        if (StringUtils.isNotNull(topSearchColumnList)) {
            List<TopSearchColumn> list = new ArrayList<TopSearchColumn>();
            for (TopSearchColumn topSearchColumn : topSearchColumnList){
                topSearchColumn.setSearchTableId(id);
                list.add(topSearchColumn);
            }
            if (list.size() > 0) {
                Integer renewal = topSearchTableDao.batchTopSearchColumn(list);
                if (renewal>0){
                    return false;
                }
            }
        }
        return true;
    }
}
