/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.youchain.service.impl;

import com.youchain.domain.ExcelConfig;
import com.youchain.domain.ExcelConfigKey;
import com.youchain.repository.ExcelConfigKeyRepository;
import com.youchain.utils.FileUtil;
import com.youchain.utils.PageUtil;
import com.youchain.utils.QueryHelp;
import com.youchain.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import com.youchain.repository.ExcelConfigRepository;
import com.youchain.service.ExcelConfigService;
import com.youchain.service.dto.ExcelConfigDto;
import com.youchain.service.dto.ExcelConfigQueryCriteria;
import com.youchain.service.mapstruct.ExcelConfigMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author baobl
* @date 2024-09-14
**/
@Service
@RequiredArgsConstructor
public class ExcelConfigServiceImpl implements ExcelConfigService {

    private final ExcelConfigRepository excelConfigRepository;
    private final ExcelConfigKeyRepository excelConfigKeyRepository;
    private final ExcelConfigMapper excelConfigMapper;

    @Override
    public Map<String,Object> queryAll(ExcelConfigQueryCriteria criteria, Pageable pageable){
        Page<ExcelConfig> page = excelConfigRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(excelConfigMapper::toDto));
    }

    @Override
    public List<ExcelConfigDto> queryAll(ExcelConfigQueryCriteria criteria){
        return excelConfigMapper.toDto(excelConfigRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public ExcelConfigDto findById(Long id) {
        ExcelConfig excelConfig = excelConfigRepository.findById(id).orElseGet(ExcelConfig::new);
        ValidationUtil.isNull(excelConfig.getId(),"ExcelConfig","id",id);
        return excelConfigMapper.toDto(excelConfig);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExcelConfigDto create(ExcelConfigDto resources) {
        ExcelConfig excelConfig=new ExcelConfig();
        if (resources.getId()!=null){
            excelConfig=excelConfigRepository.getById(resources.getId());
        }
        /*List<ExcelConfig> excelConfigList=excelConfigRepository.findByTableNameAndTableColumnName(resources.getTableName(),resources.getTableColumnName());
        if (excelConfigList.size()>0){
            excelConfig=excelConfigList.get(0);
        }*/
        excelConfig.setDictName(resources.getDictName());
        excelConfig.setTableName(resources.getTableName());
        excelConfig.setTableColumnName(resources.getTableColumnName());
        excelConfig.setTableColumnType(resources.getTableColumnType());
        excelConfig.setExcelColumnName(resources.getExcelColumnName());
        excelConfig.setGlbType(resources.getGlbType());
        excelConfig.setOnlyFlag(resources.getOnlyFlag());
        excelConfig.setDefaultValue(resources.getDefaultValue());
        excelConfigRepository.save(excelConfig);
        if (excelConfig.getGlbType()!=null&&excelConfig.getGlbType()==1){
            /* 外键控制*/
            ExcelConfigKey key=excelConfig.getEcKey();
            if (key==null){
                key=new ExcelConfigKey();
            }
            key.setTableName(resources.getEcKey().getTableName());
            key.setTableColumnName(resources.getEcKey().getTableColumnName());
            key.setTableColumnType(resources.getEcKey().getTableColumnType());
            key.setKeyName(resources.getEcKey().getKeyName());
            excelConfigKeyRepository.save(key);
            excelConfig.setEcKey(key);
            excelConfigRepository.save(excelConfig);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ExcelConfig resources) {
        ExcelConfig excelConfig = excelConfigRepository.findById(resources.getId()).orElseGet(ExcelConfig::new);
        ValidationUtil.isNull( excelConfig.getId(),"ExcelConfig","id",resources.getId());
        excelConfig.copy(resources);
        excelConfigRepository.save(excelConfig);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            ExcelConfig excelConfig=excelConfigRepository.getById(id);
            ExcelConfigKey excelConfigKey=excelConfig.getEcKey();
            if (excelConfigKey!=null) {
                excelConfigKeyRepository.deleteById(excelConfigKey.getId());
            }
            excelConfigRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ExcelConfigDto> all, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ExcelConfigDto excelConfig : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("table表名", excelConfig.getTableName());
            map.put("Excel列名", excelConfig.getExcelColumnName());
            map.put("table字段名", excelConfig.getTableColumnName());
            map.put("table字段类型", excelConfig.getTableColumnType());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}