package com.patzn.lims.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.sys.dto.UserTableColumnDTO;
import com.patzn.lims.sys.entity.SysUserRelTableColumn;
import com.patzn.lims.sys.mapper.SysUserRelTableColumnMapper;
import com.patzn.lims.sys.service.ISysCompanyRelTableColumnService;
import com.patzn.lims.sys.service.ISysTableColumnService;
import com.patzn.lims.sys.service.ISysUserRelTableColumnService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表格字段关联表 服务实现类
 * </p>
 *
 * @author hubin
 * @since 2018-10-31
 */
@Service
public class SysUserRelTableColumnServiceImpl extends BaseServiceImpl<SysUserRelTableColumnMapper, SysUserRelTableColumn> implements ISysUserRelTableColumnService {

    @Autowired
    private ISysCompanyRelTableColumnService sysCompanyRelTableColumnService;
    @Autowired
    private ISysTableColumnService sysTableColumnService;


    @Override
    public List<SysUserRelTableColumn> list(SysUserRelTableColumn sysUserRelTableColumn) {
        return this.list(Wrappers.query(sysUserRelTableColumn));
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(Long userId, UserTableColumnDTO dto) {
        if (null != dto && null != userId
                && CollectionUtils.isNotEmpty(dto.getCodes())) {
            List<Object> tableColumnIds = sysTableColumnService.listIds(dto);
            if (CollectionUtils.isNotEmpty(tableColumnIds)) {
                super.remove(Wrappers.<SysUserRelTableColumn>query().eq("user_id", userId));
                return super.saveBatch(tableColumnIds.stream().map(t -> {
                    SysUserRelTableColumn rel = new SysUserRelTableColumn();
                    rel.setUserId(userId);
                    rel.setTableColumnId((Long) t);
                    return rel;
                }).collect(Collectors.toList()));
            }
        }
        return false;
    }


    @Override
    public boolean removeByCompanyId(Long companyId) {
        return super.remove(Wrappers.<SysUserRelTableColumn>query().eq("company_id", companyId));
    }


    @Override
    public List<String> listCodes(Account account, String tableName) {
        List<String> columns = baseMapper.selectColumns(account.getUserId(), tableName);
        if (CollectionUtils.isEmpty(columns)) {
            columns = sysCompanyRelTableColumnService.listCodes(account.getCompanyId(), tableName);
        }
        return columns;
    }
}
