package com.mvc.service.app;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.dao.TAicbqSetupMapper;
import com.mvc.entity.TAicbqSetup;
import com.mvc.entity.TAicbqSetupExample;
import com.mvc.model.TAicbqSetupModel;
import com.mvc.netty.dealconstant.ResourcePath;
import com.mvc.netty.dealconstant.ResourceTag;
import com.mvc.utils.DateUtil;
import com.mvc.utils.StringUtil;
import org.apache.commons.io.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.*;

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

    @Autowired
    private TAicbqSetupMapper mSetupMapper;

    public String upload(MultipartFile file, Integer id,
                                     SetupImageType imageType) throws IOException
    {
        //ImageUploadRespDTO dto = new ImageUploadRespDTO();
        //dto.setSize(file.getSize());

        TAicbqSetup tAicbqSetup = mSetupMapper.selectByPrimaryKey(id);
        if(tAicbqSetup==null){
            return null;
        }

        String fileName = tAicbqSetup.getDeviceSn() + "_" + imageType.getFlag() +"_" + DateUtil.getCurrentTime("yyyyMMddHHmmss") +".jpg";
        //dto.setFileName(fileName);

        String localPath = env.getProperty(ResourceTag.UploadPathTag.getTag()) +"/";
        String setupPath = "setup/" + DateUtil.getCurrentTime("yyyy-MM");
        localPath = localPath + setupPath;
        File folder = new File(localPath);
        if(!folder.exists()){
            folder.mkdirs();
            System.out.println("创建安装图片的本地目录:"+localPath);
        }
        //fileName = localPath + "/" + fileName;
        //dto.setLocalPath(localPath + "/" + fileName);

        InputStream inputStream = file.getInputStream();
        OutputStream outputStream = new FileOutputStream(localPath + "/" + fileName);
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
        inputStream.close();
        outputStream.close();
        String imageUrl = env.getProperty(ResourceTag.ResourceUrlTag.getTag()) + "/image/" + setupPath + "/" + fileName;
        log.info("设备安装照片的路径" + imageUrl);
        //dto.setUrl(imageUrl);
        //return dto.getUrl();
        return imageUrl;
    }

    public TAicbqSetupModel updateTAicbqSetup(Integer id,String imageFlag,String imageUrl){
        TAicbqSetup tAicbqSetup = mSetupMapper.selectByPrimaryKey(id);
        if(imageFlag.equals(SetupImageType.Env1.getFlag())){
            tAicbqSetup.setEnvPic1Url(imageUrl);
        }else if(imageFlag.equals(SetupImageType.Env2.getFlag())){
            tAicbqSetup.setEnvPic2Url(imageUrl);
        }else if(imageFlag.equals(SetupImageType.Env3.getFlag())){
            tAicbqSetup.setEnvPic3Url(imageUrl);
        }else if(imageFlag.equals(SetupImageType.Dail.getFlag())){
            tAicbqSetup.setDialPicUrl(imageUrl);
        }else if(imageFlag.equals(SetupImageType.Side.getFlag())){
            tAicbqSetup.setSidePicUrl(imageUrl);
        }else{
            return null;
        }
        int i = mSetupMapper.updateByPrimaryKey(tAicbqSetup);
        if(i>0) {
            TAicbqSetupModel model = new TAicbqSetupModel();
            BeanUtils.copyProperties(tAicbqSetup, model);
            return model;
        }else {
            return null;
        }
    }

    //清楚安装的照片
    public int clearSetupPicture(int id,String imageFlag){
        TAicbqSetup tAicbqSetup = mSetupMapper.selectByPrimaryKey(id);
        String imageUrl = null;
        if(imageFlag.equals(SetupImageType.Env1.getFlag())){
            imageUrl = tAicbqSetup.getEnvPic1Url();
            tAicbqSetup.setEnvPic1Url(null);
        }else if(imageFlag.equals(SetupImageType.Env2.getFlag())){
            imageUrl = tAicbqSetup.getEnvPic2Url();
            tAicbqSetup.setEnvPic2Url(null);
        }else if(imageFlag.equals(SetupImageType.Env3.getFlag())){
            imageUrl = tAicbqSetup.getEnvPic3Url();
            tAicbqSetup.setEnvPic3Url(null);
        }else if(imageFlag.equals(SetupImageType.Dail.getFlag())){
            imageUrl = tAicbqSetup.getDialPicUrl();
            tAicbqSetup.setDialPicUrl(null);
        }else if(imageFlag.equals(SetupImageType.Side.getFlag())){
            imageUrl = tAicbqSetup.getSidePicUrl();
            tAicbqSetup.setSidePicUrl(null);
        }
        //删除本地照片
        String localFile = getLocalPathByWebUrl(imageUrl);
        File file = new File(localFile);
        if(file.exists()){
            file.delete();
            System.out.println("删除服务器的本地图片:"+localFile);
            return 1;
        }
        return 0;
    }

    //根据网路路径获取本地路径
    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;
    }

    public Map<String,Object> findAllDeviceSetup(Integer page,Integer rows){
        Map<String,Object> resMap = new HashMap<>();
        Page<Object> pageObject = PageHelper.startPage(page,rows);
        List<TAicbqSetup> setups = mSetupMapper.selectByExample(null);
        List<TAicbqSetupModel> resList = new ArrayList<>();
        for(TAicbqSetup aicbqSetup:setups){
            TAicbqSetupModel model = new TAicbqSetupModel();
            BeanUtils.copyProperties(aicbqSetup,model);
            resList.add(model);
        }
        resMap.put("total",pageObject.getTotal());
        resMap.put("list",resList);
        return resMap;
    }

    public Map<String,Object> findDeviceSetupsBySetupman(String setupman,String startTime,String endtime,Integer page,Integer rows){
        Map<String,Object> resMap = new HashMap<>();
        Date startDate = DateUtil.parseTimeStr(startTime,"yyyyMMddHHmmss");
        Date endDate = null;
        if(endtime!=null){
            endDate = DateUtil.parseTimeStr(endtime,"yyyyMMddHHmmss");
        }
        TAicbqSetupExample example = new TAicbqSetupExample();
        TAicbqSetupExample.Criteria criteria = example.createCriteria();
        criteria.andSetupManEqualTo(setupman);
        if(startDate!=null){
            criteria.andSetupTimeGreaterThanOrEqualTo(startDate);
        }
        if(endDate!=null){
            criteria.andSetupTimeLessThanOrEqualTo(endDate);
        }
        example.setOrderByClause("SETUP_TIME desc");
        Page<Object> pageObject = PageHelper.startPage(page,rows);
        List<TAicbqSetup> setups = mSetupMapper.selectByExample(example);
        List<TAicbqSetupModel> resList = new ArrayList<>();
        for(TAicbqSetup aicbqSetup:setups){
            TAicbqSetupModel model = new TAicbqSetupModel();
            BeanUtils.copyProperties(aicbqSetup,model);
            resList.add(model);
        }
        resMap.put("total",pageObject.getTotal());
        resMap.put("list",resList);
        return resMap;
    }

    public TAicbqSetupModel saveAicbqSetup(TAicbqSetupModel model){
        model.setSetupId(StringUtil.getUuid());
        model.setSetupTime(new Date());
        TAicbqSetup aicbqSetup = new TAicbqSetup();
        BeanUtils.copyProperties(model,aicbqSetup);
        int insert = mSetupMapper.insert(aicbqSetup);
        model.setId(aicbqSetup.getId());
        return model;
    }

    public int deleteAicbqSetup(int id){
        int i = mSetupMapper.deleteByPrimaryKey(id);
        return i;
    }

    public TAicbqSetupModel updateDeviceSetup(TAicbqSetupModel model){
        TAicbqSetup tAicbqSetup = mSetupMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model,tAicbqSetup);
        int i = mSetupMapper.updateByPrimaryKey(tAicbqSetup);
        return model;
    }
}
