package com.mx.cneeds.server.datashow.web.device;

import com.google.gson.Gson;
import com.mx.cneeds.common.UserUtils;
import com.mx.cneeds.common.constant.FilePath;
import com.mx.cneeds.common.constant.ResultCode;
import com.mx.cneeds.common.converter.RequestParamterConverter;
import com.mx.cneeds.common.dto.*;
import com.mx.cneeds.common.pager.Constant;
import com.mx.cneeds.common.result.R;
import com.mx.cneeds.common.vo.DeviceLogFileVo;
import com.mx.cneeds.common.vo.WechatDeviceLogVo;
import com.mx.cneeds.server.datashow.client.DeviceClient;
import com.mx.cneeds.server.datashow.client.LogFileClient;
import com.mx.cneeds.server.datashow.client.UserClient;
import com.mx.hbasefile.hadoop.hdfs.api.HdfsTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName LogFileController
 * @Author zzrdark
 * @Date 2020-04-01 15:14
 * @Description TODO
 **/
@Controller
@Slf4j
@RequestMapping("/logFile")
public class LogFlieController {

    @Autowired
    private LogFileClient logFileClient;

    @Autowired
    private DeviceClient deviceClient;

    @Autowired
    private HdfsTemplate hdfsTemplate;

    @Autowired
    private UserClient userClient;

    /**
     *
     * @param vo
     * @return
     * @throws IOException
     */
    @PostMapping("/logfile/wechatDeviceLogUpload")
    @ResponseBody
    public R wechatUploadLog(@RequestBody WechatDeviceLogVo vo) throws IOException {
        log.debug(vo.toString());
        WechatDeviceLogDto dto = new WechatDeviceLogDto();
        BeanUtils.copyProperties(vo, dto);

        List<Map<String,String>> listUrl = new ArrayList<>();
        /*for (MultipartFile f : file){
            Map<String,String> map = new HashMap<>();
            // 把图片存入 oos 返回路径
            StringBuffer dir = new StringBuffer(FilePath.LogFilePath);
            dir.append(vo.getLogAcceptId());
            hdfsTemplate.saveFile(dir.toString(),f.getOriginalFilename(),f.getInputStream(),f.getSize(), (short) 2);
            map.put(Constant.WechatFileDtoProp.Url.getKey(),dir.toString()+"/"+f.getOriginalFilename());
            map.put(Constant.WechatFileDtoProp.Size.getKey(),String.valueOf(f.getSize()));
            listUrl.add(map);
        }*/
        dto.setFileMap(listUrl);
        DeviceInfoDto deviceInfoDto = deviceClient.queryDeviceByImei(dto.getImei());
        if (deviceInfoDto == null){
            return R.error(ResultCode.NOTFOUND_IMEI,"没有该imei");
        }
        dto.setDeviceId(deviceInfoDto.getDeviceId());

        UserDto userDto = userClient.userInfo(UserUtils.getUserName());
        dto.setCreateUsername(UserUtils.getUserName());
        dto.setUserId(userDto.getUserId());

        logFileClient.wechatUploadLog(dto);
        return R.ok();
    }

    @PostMapping("/logfile/wechatUploadLogFile")
    @ResponseBody
    public R wechatUploadLogFile(String logAcceptId, MultipartFile file) throws IOException {
        log.debug("wechatUploadLogFile:  "+logAcceptId+" file : "+ (file==null ? "空":"不为空"));
        StringBuffer dir = new StringBuffer(FilePath.LogFilePath);
        dir.append(logAcceptId);
        if (logAcceptId == null || file == null ) {
            return R.error(ResultCode.PARAMERROR,"参数有误");
        }
        hdfsTemplate.saveFile(dir.toString(),file.getOriginalFilename(),file.getInputStream(),file.getSize(), (short) 2);

        String locationUrl = dir.toString()+"/"+file.getOriginalFilename();
        WechatFileDto dto = WechatFileDto.builder()
                .fileSize(file.getSize())
                .locationUrl(locationUrl)
                .logAcceptId(logAcceptId).build();

        log.debug(dto.toString());
        logFileClient.wechatUploadAloneFile(dto);
        return R.ok();
    }

    @PostMapping("/logfile/proDeviceUploadLogFile")
    @ResponseBody
    public R proDeviceUploadLogFile(DeviceLogFileVo vo){
        DeviceLogFileDto dto = new DeviceLogFileDto();
        BeanUtils.copyProperties(vo, dto);

        log.debug(vo.toString());
        DeviceInfoDto deviceInfoDto = deviceClient.queryDeviceByImei(dto.getImei());

        if (deviceInfoDto == null){
            log.debug("ResultCode:  "+ResultCode.NOTFOUND_IMEI);
            return R.error(ResultCode.NOTFOUND_IMEI,"没有该imei");
        }
        DeviceLogDto deviceLogDto = logFileClient.queryLogFileByLogAcceptId(vo.getLogAcceptId());

        if ( deviceLogDto == null ){
            log.debug("ResultCode:  "+ResultCode.NOTFOUNDLOG);
            return R.error(ResultCode.NOTFOUNDLOG,"没找到对应的Log日志信息");
        }
        return R.ok();
    }

    @PostMapping("/logfile/DeviceLogFileUpload")
    @ResponseBody
    public R deviceUploadLogFile(DeviceLogFileVo vo, MultipartFile file) throws IOException {
        DeviceLogFileDto dto = new DeviceLogFileDto();
        BeanUtils.copyProperties(vo, dto);

        log.debug(vo.toString());
        DeviceInfoDto deviceInfoDto = deviceClient.queryDeviceByImei(dto.getImei());

        if (deviceInfoDto == null){
            log.debug("ResultCode:  "+ResultCode.NOTFOUND_IMEI);
            return R.error(ResultCode.NOTFOUND_IMEI,"没有该imei");
        }
        DeviceLogDto deviceLogDto = logFileClient.queryLogFileByLogAcceptId(vo.getLogAcceptId());

        if ( deviceLogDto == null ){
            log.debug("ResultCode:  "+ResultCode.NOTFOUNDLOG);
            return R.error(ResultCode.NOTFOUNDLOG,"没找到对应的Log日志信息");
        }

        // 把图片存入oos 返回路径
        StringBuffer dir = new StringBuffer(FilePath.LogFilePath);
        dir.append(vo.getLogAcceptId());
        hdfsTemplate.saveFile(dir.toString(),file.getOriginalFilename(),file.getInputStream(),file.getSize(), (short) 2);

        dto.setLogfileUrl(dir.toString()+"/"+file.getOriginalFilename());
        dto.setLogfileSize(file.getSize());

        dto.setDeviceId(deviceInfoDto.getDeviceId());
        logFileClient.uploadLogFile(dto);
        log.debug("logAcceptId:"+vo.getLogAcceptId() + "  ResultCode: 0");
        return R.ok();
    }

    @RequestMapping("/logfile/downloadFile/{logId}/{isLogFile}/{fileName}")
    public void downloadFile( HttpServletResponse response,
                              @PathVariable("logId") Long logId,
                              @PathVariable("fileName") String fileName,
                              @PathVariable("isLogFile") boolean isLogFile) throws IOException {

        DeviceLogDto deviceLogDto = logFileClient.queryLogFileByLogid(logId);

        /**
         * log文件日志
         */
        if (isLogFile){

            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType(deviceLogDto.getLogfileUrl().substring(deviceLogDto.getLogfileUrl().lastIndexOf(".")+1));
            response.addHeader("Content-Disposition", "attachment; filename" + "testfilename");

            byte[] bytes = new byte[1024];

            InputStream inputStream = hdfsTemplate.openFile(deviceLogDto.getLogfileUrl().
                    substring(0,deviceLogDto.getLogfileUrl().lastIndexOf("/")), fileName);

            long total = deviceLogDto.getLogfileSize();
            while (total>0) {
                inputStream.read(bytes);
                outputStream.write(bytes,0, total>1024?1024: (int) total);
                outputStream.flush();
                total-=1024;
            }
            outputStream.close();
        }else {
            /**
             * 微信上传的 图片 视频文件
             */
        }


    }

}
