package io.hmit.modules.serviceOrder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.hmit.common.service.impl.CrudServiceImpl;
import io.hmit.common.utils.Result;
import io.hmit.modules.serviceOrder.dao.PensionDocumentDao;
import io.hmit.modules.serviceOrder.dto.PensionDocumentDTO;
import io.hmit.modules.serviceOrder.entity.PensionDocumentEntity;
import io.hmit.modules.serviceOrder.service.PensionDocumentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件信息表
 *
 * @author zsh 408538940@qq.com
 * @since 1.0.0 2021-01-27
 */
@Service
public class PensionDocumentServiceImpl extends CrudServiceImpl<PensionDocumentDao, PensionDocumentEntity, PensionDocumentDTO> implements PensionDocumentService {

    @Override
    public QueryWrapper<PensionDocumentEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<PensionDocumentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }

    @Value("${QR.download-path}")
    private String QRPath;

    @Override
    public Map<String, Object> uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            return null;
        }
        //生成随机时间错
        Long currenttime=System.currentTimeMillis();
        //上传文件
        String file_path = "/static/"+ currenttime +"-" + file.getOriginalFilename();
        String file_path_act = QRPath  + currenttime+"-"+file.getOriginalFilename();
        System.out.println(file_path_act);
        File fileAct = new File(file_path_act);
        if (!fileAct.getParentFile().exists()) {
            fileAct.getParentFile().mkdirs();
        }
        try {
            file.transferTo(fileAct);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }

        //保存文件信息
        PensionDocumentEntity pensionDocumentEntity = new PensionDocumentEntity();
        pensionDocumentEntity.setFileName(fileAct.getName());
        pensionDocumentEntity.setFilePath(file_path);
        pensionDocumentEntity.setFilePathAct(fileAct.getPath());
        pensionDocumentEntity.setFileSize(Double.parseDouble(String.valueOf(file.getSize())));
        pensionDocumentEntity.setFileType(file.getContentType());
        pensionDocumentEntity.setStatus("1");
        insert(pensionDocumentEntity);

        Map<String, Object> result = new HashMap<>();
        result.put("fileName",fileAct.getName());
        result.put("filePath",file_path);
        result.put("docId", pensionDocumentEntity.getId());
        return result;
    }
}