package com.mvc.service.setup;

import com.mvc.dao.TSetupPicMapper;
import com.mvc.entity.TSetupPic;
import com.mvc.entity.TSetupPicExample;
import com.mvc.model.TSetupModel;
import com.mvc.model.TSetupPicModel;
import com.mvc.netty.dealconstant.ResourcePath;
import com.mvc.netty.dealconstant.ResourceTag;
import com.mvc.service.aiiden.PicType;
import com.mvc.service.app.AppSetupService;
import com.mvc.utils.DateUtil;
import com.mvc.utils.StringUtil;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class TSetupPicService {
    private static Logger log = LoggerFactory.getLogger(AppSetupService.class);

    @Resource
    private Environment env;

    @Autowired(required = false)
    private TSetupPicMapper tSetupPicMapper;

    @Autowired
    private TSetupService tSetupService;

    public TSetupPicModel saveTSetupPic(MultipartFile file, TSetupPicModel model) throws IOException {
        String imageUrl = addPic(file,model);
        log.info("设备安装图片的网路路径:" + imageUrl);
        model.setPicUrl(imageUrl);
        model.setPicId(StringUtil.getUuid());
        model.setCreateTime(new Date());
        PicType picType = PicType.getElement(model.getPicType());
        model.setPicName(picType.getName());
        TSetupPic setupPic = new TSetupPic();
        BeanUtils.copyProperties(model,setupPic);
        int insert = tSetupPicMapper.insert(setupPic);
        model.setId(setupPic.getId());

        changeTSetupGps(model);

        return model;
    }

    public TSetupPicModel updateTSetupPic(MultipartFile file, TSetupPicModel model) throws IOException{
        //1. 删除服务器图片
        deletePic(model.getPicUrl());
        log.info("删除服务器设备安装照片:"+ model.getPicUrl());
        System.out.println("删除服务器设备安装照片:"+ model.getPicUrl());
        //2. 新增服务器图片
        String imgUrl = addPic(file,model);
        model.setPicUrl(imgUrl);
        System.out.println("新增服务器设备安装照片:" + imgUrl);

        TSetupPic tSetupPic = tSetupPicMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model,tSetupPic);
        int iresult = tSetupPicMapper.updateByPrimaryKey(tSetupPic);

        changeTSetupGps(model);

        return model;
    }


    public int deleteTSetupPic(TSetupPicModel model) throws IOException{
        //删除本地照片
        deletePic(model.getPicUrl());

        model.setPicLat(null);
        model.setPicLon(null);
        changeTSetupGps(model);

        return tSetupPicMapper.deleteByPrimaryKey(model.getId());
    }

    //新增本地照片
    private String addPic(MultipartFile file,TSetupPicModel model) throws IOException{
        TSetupModel setupModel = tSetupService.findTSetupBySetupId(model.getSetupId());
        if(setupModel == null){
            return null;
        }
        PicType picType = PicType.getElement(model.getPicType());
        String localFileName = setupModel.getDeviceSn()+"_"+setupModel.getStationCode() +"_" + picType.getType() +
                "_" + DateUtil.getCurrentTime("yyyyMMddHHmmss") +".jpg";

        //本地上传基本路径
        String localUploadBasePath = env.getProperty(ResourceTag.UploadPathTag.getTag()) + "/";
        String localSetupPath = "setup/" + setupModel.getDeviceSn();
        String localPath = localUploadBasePath + localSetupPath;
        File folder = new File(localPath);
        if(!folder.exists()){
            folder.mkdirs();
            System.out.println("创建安装图片的本地目录:"+localPath);
        }
        String localPathFile = localPath + "/" + localFileName;

        InputStream inputStream = file.getInputStream();
        OutputStream outputStream = new FileOutputStream(localPathFile);
        IOUtils.copy(inputStream,outputStream);
        outputStream.flush();
        inputStream.close();
        outputStream.close();
        String imagetUrl = env.getProperty(ResourceTag.ResourceUrlTag.getTag()) +
                ResourcePath.Image.getPath() + localSetupPath + "/" + localFileName;
        return imagetUrl;
    }

    //删除本地照片
    private void deletePic(String picUrl){
        if(picUrl != null) {
            String localPathFile = getLocalPathByWebUrl(picUrl);
            File file = new File(localPathFile);
            if (file.exists()) {
                file.delete();
                System.out.println("删除服务的本地图片:" + localPathFile);
            }
        }
    }


    public int deleteTSetupPicBySetupId(String setupId){
        TSetupPicExample example = new TSetupPicExample();
        TSetupPicExample.Criteria criteria = example.createCriteria();
        criteria.andSetupIdEqualTo(setupId);
        return  tSetupPicMapper.deleteByExample(example);
    }

    public List<TSetupPicModel> findSetupPicsBySetupId(String setupId){
        List<TSetupPicModel> modelList = new ArrayList<>();
        TSetupPicExample example = new TSetupPicExample();
        TSetupPicExample.Criteria criteria = example.createCriteria();
        criteria.andSetupIdEqualTo(setupId);
        List<TSetupPic> setupPicList = tSetupPicMapper.selectByExample(example);
        for(TSetupPic setupPic:setupPicList){
            TSetupPicModel model = new TSetupPicModel();
            BeanUtils.copyProperties(setupPic,model);
            modelList.add(model);
        }
        return modelList;
    }

    //根据网路路径获取本地路径
    private String getLocalPathByWebUrl(String imageUrl){
        if(imageUrl.contains("http")){
            String src = env.getProperty(ResourceTag.ResourceUrlTag.getTag())+ ResourcePath.Image.getPath();
            String tar = env.getProperty(ResourceTag.UploadPathTag.getTag());
            return imageUrl.replaceAll(src,tar);
        }
        return imageUrl;
    }

    //根据照片，更改安装目录表的GPS坐标
    private void changeTSetupGps(TSetupPicModel model){
        if( model.getPicType() == PicType.Env.getType() ){
            TSetupModel setupModel = tSetupService.findTSetupBySetupId(model.getSetupId());
            if(setupModel!=null){
                setupModel.setStationLon( model.getPicLon() );
                setupModel.setStationLat( model.getPicLat() );
                tSetupService.updateTSetup(setupModel);
            }
        }
    }

}
