package com.ebts.generator.service.impl;

import com.ebts.common.constant.ReturnConstants;
import com.ebts.common.core.entity.Result;
import com.ebts.common.exception.EbtsException;
import com.ebts.common.utils.SecurityUtils;
import com.ebts.common.utils.ServerResult;
import com.ebts.common.utils.StringUtils;
import com.ebts.generator.dao.RelationalMapDao;
import com.ebts.generator.dao.SearchTableRoleDao;
import com.ebts.generator.dao.TopSearchTableDao;
import com.ebts.generator.entity.RelationalMap;
import com.ebts.generator.entity.SearchTableRole;
import com.ebts.generator.entity.TopSearchColumn;
import com.ebts.generator.entity.TopSearchTable;
import com.ebts.generator.service.TopSearchTableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * top万能查询主Service业务层处理
 *
 * @author clay
 * @date 2021-07-20
 */
@Service
@Slf4j
public class TopSearchTableServiceImpl implements TopSearchTableService {

    @Resource
    private TopSearchTableDao topSearchTableDao;
    @Resource
    private SearchTableRoleDao searchTableRoleDao;
    @Resource
    private RelationalMapDao relationalMapDao;

    /**
     * 查询top万能查询主
     *
     * @param id top万能查询主ID
     * @return top万能查询主
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Result<TopSearchTable> selectTopSearchTableById(Long id) {
        TopSearchTable topSearchTable = topSearchTableDao.selectTopSearchTableById(id);
        List<SearchTableRole> roleList = searchTableRoleDao.selectSearchTableRoleList(new SearchTableRole(id, null));
        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 Result.ok(topSearchTable);
        } else {
            return Result.info(ReturnConstants.RESULT_EMPTY);
        }
    }

    /**
     * 查询top万能查询主列表
     *
     * @param topSearchTable top万能查询主
     * @return top万能查询主
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Result<List<TopSearchTable>> selectTopSearchTableList(TopSearchTable topSearchTable) {
        List<TopSearchTable> topSearchTableList = topSearchTableDao.selectTopSearchTableList(topSearchTable);
        if (topSearchTableList.size() > 0) {
            return Result.ok(topSearchTableList);
        } else {
            return Result.info(ReturnConstants.RESULT_EMPTY);
        }
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Result<List<TopSearchTable>> selectTopSearchTableInfo() {
        List<TopSearchTable> tableList = topSearchTableDao.selectTopSearchTableInfo();
        return Result.ok(tableList);
    }

    public List<TopSearchColumn> selectTableColumns(Long id) {
        return topSearchTableDao.selectTableColumns(id);
    }

    /**
     * 新增top万能查询主
     *
     * @param topSearchTable top万能查询主
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result<Integer> insertTopSearchTable(TopSearchTable topSearchTable) {
        topSearchTable.setCreateBy(SecurityUtils.getUserId());
        topSearchTableDao.insertTopSearchTable(topSearchTable);
        if (insertTopSearchColumn(topSearchTable)) {
            return Result.error(ReturnConstants.SYS_FAILL);
        }
        return Result.ok();
    }

    /**
     * 修改top万能查询主
     *
     * @param topSearchTable top万能查询主
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result<Integer> updateTopSearchTable(TopSearchTable topSearchTable) {
        topSearchTable.setUpdateBy(SecurityUtils.getUserId());
        topSearchTableDao.deleteTopSearchColumnBySearchTableId(topSearchTable.getId());
        insertTopSearchColumn(topSearchTable);
        List<SearchTableRole> searchTableRoles = new ArrayList<>();
        for (Long roleId : topSearchTable.getRoleIds()) {
            searchTableRoles.add(new SearchTableRole(topSearchTable.getId(), roleId));
        }
        relationalMapDao.deleteRelationalMapById(topSearchTable.getId());
        List<RelationalMap> relationalMapList = topSearchTable.getRelationalMapList();
        for (RelationalMap relationalMap : relationalMapList) {
            relationalMap.setMainId(topSearchTable.getId());
        }
        insertRelationalMap(relationalMapList);


        searchTableRoleDao.deleteSearchTableRoleById(topSearchTable.getId());
        inserTopTableRole(searchTableRoles);
        topSearchTableDao.updateTopSearchTable(topSearchTable);
        return Result.ok();
    }
//    void deleteSearchTableRoleById(Long id){
//        try {
//
//        }catch (RuntimeException e){
//            log.error("无数据");
//        }
//    }


    @Override
    public List<Map<String, Object>> selectDbTableList(Map<String, Object> params) {
        try {
            return topSearchTableDao.selectDbTableList(params);
        } catch (RuntimeException e) {
            log.error(e.getMessage());
            throw new EbtsException(ReturnConstants.OP_ERROR, e);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void importGenTable(String[] tableNames) {
        List<TopSearchTable> tableList = topSearchTableDao.selectDbTableListByNames(tableNames);
        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);
                }
            }
        }
    }

    /**
     * 批量删除top万能查询主
     *
     * @param ids 需要删除的top万能查询主ID
     * @return 结果
     */
    @Transactional
    @Override
    public Result<Integer> deleteTopSearchTableByIds(Long[] ids) {
        //批量删除子表数据
        topSearchTableDao.deleteTopSearchColumnBySearchTableIds(ids);
        searchTableRoleDao.deleteSearchTableRoleByIds(ids);
        topSearchTableDao.deleteTopSearchTableByIds(ids);
        return Result.ok();
    }

    /**
     * 删除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) {
            log.error(e.getMessage());
            throw new EbtsException(ReturnConstants.OP_ERROR, e);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean inserTopTableRole(List<SearchTableRole> roleList) {
        if (StringUtils.isNotNull(roleList)) {
            searchTableRoleDao.batchSearchTableRole(roleList);
        }
        return true;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean insertRelationalMap(List<RelationalMap> relationalMaps) {
        if (StringUtils.isNotNull(relationalMaps) && relationalMaps.size() > 0) {
            relationalMapDao.batchRelationalMap(relationalMaps);
        }
        return true;
    }

    /**
     * 新增top万能查询字段信息
     *
     * @param topSearchTable top万能查询主对象
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    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;
    }
}
