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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.sys.dto.UserTableColumnDTO;
import com.patzn.lims.sys.entity.SysTableColumn;
import com.patzn.lims.sys.mapper.SysTableColumnMapper;
import com.patzn.lims.sys.service.ISysCompanyRelTableColumnService;
import com.patzn.lims.sys.service.ISysTableColumnService;
import com.patzn.lims.sys.vo.SysTableColumnVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 系统表格字段表 服务实现类
 * </p>
 *
 * @author hubin
 * @since 2018-10-31
 */
@Service
public class SysTableColumnServiceImpl extends BaseServiceImpl<SysTableColumnMapper, SysTableColumn> implements ISysTableColumnService {
    @Autowired
    private ISysCompanyRelTableColumnService sysCompanyRelTableColumnService;


    @Override
    public Page<SysTableColumnVO> page(Page<SysTableColumnVO> page, SysTableColumn sysTableColumn) {
        if (null != sysTableColumn.getMenuId()) {
            // 递归分页
            return pageRecursive(page, sysTableColumn);
        }
        return page.setRecords(baseMapper.selectPageVo(page, sysTableColumn));
    }


    public Page<SysTableColumnVO> pageRecursive(Page<SysTableColumnVO> page, SysTableColumn sysTableColumn) {
        return page.setRecords(baseMapper.selectPageRecursive(page, sysTableColumn));
    }


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


    @Override
    public List<Object> listIds(UserTableColumnDTO dto) {
        return baseMapper.selectObjs(Wrappers.<SysTableColumn>query().select("id")
                .eq("name", dto.getTableName())
                .in("code", dto.getCodes()));
    }


    @Override
    public List<String> listCodes(Long companyId, String tableName) {
        List<String> codes = sysCompanyRelTableColumnService.listCodes(companyId, tableName);
        if(CollectionUtils.isEmpty(codes)){
            List<Object> codeObjects = baseMapper.selectObjs(Wrappers.<SysTableColumn>query()
                    .select("code").eq("name", tableName));
            if (CollectionUtils.isNotEmpty(codeObjects)) {
                codes = codeObjects.stream().map(o -> String.valueOf(o)).collect(toList());
            }
        }
        return codes;
    }
}
