package com.shkj.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.shkj.common.core.domain.Result;
import com.shkj.common.utils.StringUtils;
import com.shkj.wms.common.SwitchShowEntity;
import com.shkj.wms.domain.TableHeader;
import com.shkj.wms.mapper.TableHeaderMapper;
import com.shkj.wms.service.ITableHeaderService;
import com.shkj.wms.bo.SyncTableHeaderBo;
import com.shkj.wms.bo.TableHeaderAddBo;
import com.shkj.wms.bo.TableHeaderEditBo;
import com.shkj.wms.bo.TableHeaderQueryBo;
import com.shkj.wms.vo.TableColumnVo;
import com.shkj.wms.vo.TableHeaderVo;
import com.shkj.wms.vo.TableListVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 表格表头Service业务层处理
 *
 * @author lch
 * @date 2022-03-19
 */
@Slf4j
@Service
public class TableHeaderServiceImpl extends ServiceImpl<TableHeaderMapper, TableHeader> implements ITableHeaderService {

    @Override
    public Result<TableHeaderVo> queryById(Long id) {
        TableHeader db = this.baseMapper.selectById(id);
        TableHeaderVo vo = BeanUtil.toBean(db, TableHeaderVo.class);
        return Result.ok().data(vo);
    }

    @Override
    public List<TableHeaderVo> queryList(TableHeaderQueryBo bo) {
        LambdaQueryWrapper<TableHeader> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getTableName()), TableHeader::getTableName, bo.getTableName());
        lqw.eq(StrUtil.isNotBlank(bo.getProp()), TableHeader::getProp, bo.getProp());
        lqw.orderByAsc(TableHeader::getPropSort)
                .orderByAsc(TableHeader::getId);
        List<TableHeaderVo> voList = entity2Vo(this.list(lqw));
        return voList;

    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<TableHeaderVo> entity2Vo(Collection<TableHeader> collection) {
        List<TableHeaderVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, TableHeaderVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<TableHeader> page = (Page<TableHeader>) collection;
            Page<TableHeaderVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Boolean> insertByAddBo(TableHeaderAddBo bo) {
        TableHeader add = BeanUtil.toBean(bo, TableHeader.class);
        this.save(add);
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Boolean> updateByEditBo(TableHeaderEditBo bo) {
        TableHeader one = getById(bo.getId());
        if (one == null) {
            return Result.err().msg("不存在");
        }
        TableHeader update = BeanUtil.toBean(bo, TableHeader.class);
        this.updateById(update);
        return Result.ok();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Boolean> deleteWithValidById(Long id, Boolean isValid) {
        return this.removeById(id) ? Result.ok() : Result.err();
    }

    /**
     * 切换状态
     *
     * @param switchStatusEntity
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Boolean> switchStatus(SwitchShowEntity switchStatusEntity) {
        TableHeader status = getById(switchStatusEntity.getId());
        if ( status == null){
            return Result.err().msg("表格不存在");
        }
        status.setIstrue(switchStatusEntity.getIstrue());
        return this.updateById(status) ? Result.ok() : Result.err();
    }

    /**
     * 根据表名同步表头
     *
     * @param bo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Boolean> syncTableHeader(SyncTableHeaderBo bo) {
        String tableName = bo.getTableName();
        Integer table = this.baseMapper.getTable(tableName);
        if (table == null || table == 0) {
            return Result.err().msg("没有该数据表");
        }

        //查询对应表的字段信息
        List<TableColumnVo> tableColumn = this.baseMapper.getTableColumn(tableName);
        List<TableHeader> addList = new ArrayList<>();
        List<TableHeader> headerList = this.list(new LambdaQueryWrapper<TableHeader>().eq(TableHeader::getTableName, tableName));

        //已经存在了、那么只添加不存在的字段
        for (TableColumnVo columnVo : tableColumn) {
            TableHeader header = headerList.stream().filter(x -> x.getFieldCode().equals(columnVo.getColumnName())).findFirst().orElse(null);
            if (header == null) {
                TableHeader tableHeader = new TableHeader();
                tableHeader.setTableDesc(columnVo.getTableName());
                tableHeader.setTableName(columnVo.getTableName());
                tableHeader.setFieldCode(columnVo.getColumnName());
                tableHeader.setLabel(columnVo.getColumnComment());
                tableHeader.setProp(StringUtils.toCamelCase(columnVo.getColumnName()));
                tableHeader.setPropSort(columnVo.getOrdinalPosition());
                tableHeader.setIstrue(true).setSortable(true);
                addList.add(tableHeader);
            }
        }
        if (CollectionUtils.isEmpty(addList)) {
            return Result.ok();
        }
        saveBatch(addList);
        return Result.ok();
    }

    @Override
    public Result<List<TableListVo>> getTableOption(SyncTableHeaderBo bo) {
        List<TableListVo> list = this.baseMapper.getTableOption(bo);
        return Result.ok().data(list);
    }

    @Override
    public List<TableHeaderVo> queryTableList(TableHeaderQueryBo bo) {

        List<TableHeaderVo> tableHeaderVos = this.baseMapper.queryTableList(bo);
        for (TableHeaderVo tableHeaderVo : tableHeaderVos) {
            LambdaQueryWrapper<TableHeader> wrapper = new LambdaQueryWrapper<TableHeader>().eq(TableHeader::getTableName, tableHeaderVo.getTableName());
            List<TableHeader> headerList = list(wrapper);
            String fileList = headerList.stream().sorted(Comparator.comparing(TableHeader::getPropSort)).map(TableHeader::getLabel).collect(Collectors.joining(","));
            tableHeaderVo.setFileList(fileList);
        }
        return tableHeaderVos;

    }
}
