/*
*  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.businessdata.service.impl;

import com.youchain.businessdata.domain.BaseCode;
import com.youchain.exception.EntityExistException;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.businessdata.repository.BaseCodeRepository;
import com.youchain.businessdata.service.BaseCodeService;
import com.youchain.businessdata.service.dto.BaseCodeDto;
import com.youchain.businessdata.service.dto.BaseCodeQueryCriteria;
import com.youchain.businessdata.service.mapstruct.BaseCodeMapper;
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.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author baobinglin
* @date 2023-08-22
**/
@Service
@RequiredArgsConstructor
public class BaseCodeServiceImpl implements BaseCodeService {

    private final BaseCodeRepository baseCodeRepository;
    private final BaseCodeMapper baseCodeMapper;

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

    @Override
    public List<BaseCodeDto> queryAll(BaseCodeQueryCriteria criteria){
        return baseCodeMapper.toDto(baseCodeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public BaseCodeDto findById(Integer id) {
        BaseCode baseCode = baseCodeRepository.findById(id).orElseGet(BaseCode::new);
        ValidationUtil.isNull(baseCode.getId(),"BaseCode","id",id);
        return baseCodeMapper.toDto(baseCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseCodeDto create(BaseCode resources) {
        if(baseCodeRepository.findByCode(resources.getCode()) != null){
            throw new EntityExistException(BaseCode.class,"code",resources.getCode());
        }
        return baseCodeMapper.toDto(baseCodeRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(BaseCode resources) {
        BaseCode baseCode = baseCodeRepository.findById(resources.getId()).orElseGet(BaseCode::new);
        ValidationUtil.isNull( baseCode.getId(),"BaseCode","id",resources.getId());
        baseCode = baseCodeRepository.findById(resources.getId()).get();
        /*if(baseCode != null && !baseCode.getId().equals(baseCode.getId())){
            throw new EntityExistException(BaseCode.class,"code",resources.getCode());
        }*/
        baseCode.copy(resources);
        baseCodeRepository.save(baseCode);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            baseCodeRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<BaseCodeDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (BaseCodeDto baseCode : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" code",  baseCode.getCode());
            map.put(" key",  baseCode.getKey());
            map.put(" value",  baseCode.getValue());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    private static String key_time_type="yyMMdd";//时间
    @Override
    public synchronized String baseCodeFor(String key_code, int len){
        String code="";
        String key_time = new SimpleDateFormat(key_time_type).format(Calendar.getInstance().getTime());
        String key=key_code+key_time;

        String value;
        BaseCodeQueryCriteria queryBaseCode=new BaseCodeQueryCriteria();
        queryBaseCode.setKey(key);
        List<BaseCodeDto> baseCodeDtos = queryAll(queryBaseCode);
        BaseCode baseCode = new BaseCode();
        if (baseCodeDtos.size()<1){
            baseCode.setKey(key);
            baseCode.setValue("0");
            create(baseCode);
        }else {
            baseCode=baseCodeMapper.toEntity(baseCodeDtos.get(0));
        }
        value = (Integer.valueOf(baseCode.getValue().toString())+1)+"";
        baseCode.setValue(value);
        while (value.length()<len){
            value="0"+value;
        }
        code=key+value;
        baseCode.setCode(code);
        update(baseCode);
        return  code;
    }
}