package cn.wisenergy.service.app.impl;

import cn.wisenergy.common.utils.R;
import cn.wisenergy.mapper.CustomerServiceMapper;
import cn.wisenergy.model.app.CustomerService;
import cn.wisenergy.service.app.CustomerServiceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class CustomerServiceServiceImpl implements CustomerServiceService {

    @Autowired
    private CustomerServiceMapper customerServiceMapper;

    @Value("${uploadFile.location}")
    private String uploadQRImagesLocation;

    @Override
    public CustomerService getServiceByRand(){
        return customerServiceMapper.randService();
    }

    @Override
    public void setWeChatQRImg(String wechatId, String wechatImgUrl) {
        CustomerService customerService = new CustomerService();
        customerService.setWechatId(wechatId);
        customerService.setWechatImgUrl(wechatImgUrl);
        customerService.setCreateTime(new Date());
        customerService.setUpdateTime(new Date());
        customerServiceMapper.insert(customerService);
    }
    /**
     *  专属客服二维码图片文件上传
     */
    @Override
    public R uploadImage(MultipartFile file, HttpServletRequest request, String wechatId) throws IOException {

        String basePath = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort();

        Long time = System.currentTimeMillis();

        String originalFilename = file.getOriginalFilename();//文件原始名称
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));//从最后一个.开始截取。截取zxName的后缀名
        String newName = time+suffixName; //文件新名称
        //设置文件存储路径，可以存放在你想要指定的路径里面
        String rootPath="/opt/upload/video/"; //上传图片存放位置
        String filePath = rootPath + newName;
        File newFile = new File(filePath);
        //判断目标文件所在目录是否存在
        if(!newFile.getParentFile().exists()){
            //如果目标文件所在的目录不存在，则创建父目录
            newFile.getParentFile().mkdirs();
        }
        //将内存中的数据写入磁盘
        file.transferTo(newFile);
//      图片上传保存url
        String videoUrl = basePath + rootPath + newName;

        CustomerService customerService = new CustomerService();
        customerService.setWechatId(wechatId);
        customerService.setWechatImgUrl(videoUrl);
        customerServiceMapper.insert(customerService);
        return R.ok("上传成功");
    }
}
