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

import cn.hutool.core.util.ObjectUtil;
import com.youchain.appupdate.domain.SysAppUpdate;
import com.youchain.appupdate.service.dto.SysNewAppUpdateDto;
import com.youchain.appupdate.service.mapstruct.SysNewAppUpdateMapper;
import com.youchain.config.FileProperties;
import com.youchain.exception.BadRequestException;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.appupdate.repository.SysAppUpdateRepository;
import com.youchain.appupdate.service.SysAppUpdateService;
import com.youchain.appupdate.service.dto.SysAppUpdateDto;
import com.youchain.appupdate.service.dto.SysAppUpdateQueryCriteria;
import com.youchain.appupdate.service.mapstruct.SysAppUpdateMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
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 liuxue
* @date 2023-07-17
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class SysAppUpdateServiceImpl implements SysAppUpdateService {

    private final SysAppUpdateRepository sysAppUpdateRepository;
    private final SysAppUpdateMapper sysAppUpdateMapper;
    private final SysNewAppUpdateMapper sysNewAppUpdateMapper;
    private final FileProperties properties;
    @Override
    public Map<String,Object> queryAll(SysAppUpdateQueryCriteria criteria, Pageable pageable){
        Page<SysAppUpdate> page = sysAppUpdateRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        for (SysAppUpdate bean:page ) {
        }

        return PageUtil.toPage(page.map(sysAppUpdateMapper::toDto));
    }

    @Override
    public List<SysAppUpdateDto> queryAll(SysAppUpdateQueryCriteria criteria){
        return sysAppUpdateMapper.toDto(sysAppUpdateRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }


    @Override
    public List<SysNewAppUpdateDto> queryByname(SysAppUpdateQueryCriteria criteria){
        return sysNewAppUpdateMapper.toDto(sysAppUpdateRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public SysAppUpdateDto findById(Integer id) {
        SysAppUpdate sysAppUpdate = sysAppUpdateRepository.findById(id).orElseGet(SysAppUpdate::new);
        ValidationUtil.isNull(sysAppUpdate.getId(),"SysAppUpdate","id",id);
        return sysAppUpdateMapper.toDto(sysAppUpdate);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysAppUpdateDto create(String appName,int versionCode, String versionName, String modifyContent, MultipartFile multipartFile) {

        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type +  File.separator);
        if(ObjectUtil.isNull(file)){
            throw new BadRequestException("上传失败");
        }
        //name = StringUtils.isBlank(name) ? FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename()) : name;


        Long size=multipartFile.getSize()/1024;
        SysAppUpdate resources=new SysAppUpdate();
        resources.setAppName(appName);
        resources.setId(0);
        resources.setUpdateStatus(0);
        resources.setVersionCode(versionCode);
        resources.setVersionName(versionName);
        resources.setModifyContent(modifyContent);

        resources.setDownloadUrl("/file/"+type+"/"+file.getName());
        resources.setApkSize(size.intValue());
        resources.setApkMd5("");

        return sysAppUpdateMapper.toDto(sysAppUpdateRepository.save(resources));
    }

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

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

    @Override
    public void download(List<SysAppUpdateDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysAppUpdateDto sysAppUpdate : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("更新状态。", sysAppUpdate.getUpdateStatus());
            map.put("版本代码", sysAppUpdate.getVersionCode());
            map.put("版本名称", sysAppUpdate.getVersionName());
            map.put("修改内容", sysAppUpdate.getModifyContent());
            map.put("下载网站", sysAppUpdate.getDownloadUrl());
            map.put("程序大小", sysAppUpdate.getApkSize());
            map.put("APKMD5", sysAppUpdate.getApkMd5());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
