package com.yifu.cloud.plus.v1.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.business.entity.system.TBusAttaInfo;
import com.yifu.cloud.plus.v1.business.mapper.system.TBusAttaInfoMapper;
import com.yifu.cloud.plus.v1.business.service.system.TBusAttaInfoService;
import com.yifu.cloud.plus.v1.business.vo.BusFileVo;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.OSSUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.List;

/**
 * B端附件表
 *
 * @author hgw
 * @date 2021-08-12 16:38:51
 */
@Slf4j
@Service
public class TBusAttaInfoServiceImpl extends ServiceImpl<TBusAttaInfoMapper, TBusAttaInfo> implements TBusAttaInfoService {

     @Autowired
     private OSSUtil ossUtil;

     /**
      * B端附件表简单分页查询
      *
      * @param tBusAttaInfo B端附件表
      * @return list，含url
      */
     @Override
     public List<TBusAttaInfo> getBusAttaList(TBusAttaInfo tBusAttaInfo) {
          List<TBusAttaInfo> list = baseMapper.getBusAttaList(tBusAttaInfo);
          if (list != null && !list.isEmpty()) {
               for (TBusAttaInfo info : list) {
                    this.setOssSrc(info);
               }
          }
          return list;
     }

     @Override
     public R<BusFileVo> uploadFile(@RequestBody MultipartFile file, String filePath, Integer type, String domain) throws IOException {
          if (null == file) {
               return R.failed("文件异常，请重新上传！");
          }
          String fileName = file.getOriginalFilename();
          if (Common.isEmpty(fileName)) {
               return R.failed("文件名不能为空！");
          }
          if (fileName.length() > 50) {
               return R.failed("文件名不能超过50个字符！");
          }
          //filePath不传默认存储空间的根目录
          //jpg,jpeg,png,bmp
          String key;
          if (Common.isNotNull(filePath)) {
               key = filePath + "/" + System.currentTimeMillis() + fileName;
          } else {
               key = System.currentTimeMillis() + fileName;
          }
          if (!Common.checkFile(key)) {
               return R.failed("非法上传类型！");
          }
          boolean flag = ossUtil.uploadFileByStream(file.getInputStream(), key, null);
          BusFileVo fileVo;
          TBusAttaInfo busAtta;
          URL url;
          if (flag) {
               log.info("文件：" + fileName + "上传至存储空间" + ossUtil.getBucketName() + "成功！");
               if (null != type) {
                    busAtta = this.initTBusAttaInfo(fileName, key, file.getSize(), type, domain);
                    try {
                         this.save(busAtta);
                    } catch (Exception e) {
                         log.error("上传保存文件失败：" + e.getMessage());
                         ossUtil.deleteObject(null, key);
                         return R.failed("上传保存文件失败:" + e.getMessage());
                    }
                    url = ossUtil.getObjectUrl(null, busAtta.getAttaSrc());
                    fileVo = new BusFileVo(busAtta.getId(), busAtta.getAttaName(), url.toString().replace("http","https"));
                    return R.ok(fileVo, "success");
               } else {
                    return R.failed("类型不可为空！");
               }
          } else {
               return R.failed("fail:上传失败");
          }
     }

     /**
      * @Description: 初始化附件表
      * @Author: hgw
      * @Date: 2021/8/12 17:52
      * @return: com.yifu.cloud.v1.hrobusiness.api.entity.system.TBusAttaInfo
      **/
     private TBusAttaInfo initTBusAttaInfo(String fileName, String key, Long fileSize
             , Integer type, String domain) {
          YifuUser user = SecurityUtils.getUser();
          TBusAttaInfo empAtta = new TBusAttaInfo();
          if (user == null || Common.isEmpty(user.getId())) {
               return empAtta;
          }
          char point = '.';
          char slash = '/';
          if (fileName.lastIndexOf(slash) >= 0) {
               empAtta.setAttaName(fileName.substring(fileName.lastIndexOf(slash)));
          } else {
               empAtta.setAttaName(fileName);
          }
          if (key.lastIndexOf(point) >= 0) {
               empAtta.setAttaType(key.substring(key.lastIndexOf(point)));
          }
          empAtta.setAttaSize(fileSize);
          empAtta.setAttaSrc(key);
          empAtta.setCreateTime(LocalDateTime.now());
          empAtta.setCreateUserId(String.valueOf(user.getId()));
          empAtta.setCreateUserName(user.getNickname());
          empAtta.setRelationType(type);
          empAtta.setRelationId(domain);
          return empAtta;
     }

     /**
      * @param id
      * @Description: 单个查询url
      * @Author: hgw
      * @Date: 2021/8/20 14:37
      * @return: com.yifu.cloud.v1.hrobusiness.api.entity.system.TBusAttaInfo
      **/
     @Override
     public TBusAttaInfo getUrlByid(String id) {
          TBusAttaInfo busAtta = this.getById(id);
          if (null != busAtta) {
               this.setOssSrc(busAtta);
          }
          return busAtta;
     }

     /**
      * @param busAtta
      * @Description: 获取附件的阿里云地址
      * @Author: hgw
      * @Date: 2021/8/20 14:36
      * @return: void
      **/
     private void setOssSrc(TBusAttaInfo busAtta) {
          URL url = ossUtil.getObjectUrl(null, busAtta.getAttaSrc());
          busAtta.setAttaSrc(url.toString().replace("http","https"));
     }

}
