package com.fdkanfang.web.backend;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.fdkanfang.common.constant.MsgCode;
import com.fdkanfang.common.util.AliyunOssUtil;
import com.fdkanfang.common.util.FileUtils;
import com.fdkanfang.common.util.R;
import com.fdkanfang.dao.backend.ResourceMapper;
import com.fdkanfang.dao.backend.UserMapper;
import com.fdkanfang.domain.backend.*;
import com.fdkanfang.domain.dto.HouseDto;
import com.fdkanfang.service.backend.HouseService2;
import com.fdkanfang.service.backend.ImageService2;
import com.fdkanfang.web.mq.config.RabbitConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by owen on 2020/2/18 0018 10:04
 */
@ApiIgnore
@Log4j2
@Api(value = "TestController",tags = "测试")
@RestController
@RequestMapping("test1")
public class TestController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private ImageService2 imageService2;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private HouseService2 houseService2;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

//    @Value("${image.path}")
    private String IMAGE_PATH;

    ///kanfang/test/aa.jpg

    private static String ossPath = "kanfang/house/";

    @GetMapping
    public String test1(){
        return LocalDateTime.now().toString();
    }


    @ApiOperation("valid")
    @PostMapping("valid")
    public R valid(@Valid @RequestBody HouseDto param){

        return new R(2000, param.toString());
    }

    @ApiOperation("mq map接受消息")
    @GetMapping("mq")
    public R mq(){
        HashMap<Object, Object> mqMsgMap = new HashMap<>();
        String s = new Date().toString();
        log.info("send: {}", s);
        mqMsgMap.put("ossUpload", s);
        log.info("ossUpload: {}", s);

        //发消息到mq
        rabbitTemplate.convertAndSend(RabbitConfig.VERTICAL_EXCHANGE, RabbitConfig.VERTICAL_QUEUE_ROUTING, mqMsgMap);
        return new R(2000, s);
    }


    @ApiOperation("保存sceneJson")
    @GetMapping("sceneJson/{houseId}")
    public R sceneJson(@PathVariable Long houseId){
        log.info("id: {}", houseId);
        HouseEntity house = houseService2.findById(houseId);
        if (house == null) {
            return new R(2000, "house为空");
        }
        String sceneJson = "{\"1-1_cc\": {\"door\": [], \"vertex\": [{\"x\": 0.379, \"y\": -1.2462, \"id\": 0}, {\"x\": 0.379, \"y\": 0.7272, \"id\": 1}, {\"x\": -2.1155, \"y\": 0.7272, \"id\": 2}, {\"x\": -2.1155, \"y\": -0.5785, \"id\": 3}, {\"x\": -0.0038, \"y\": -0.5785, \"id\": 4}, {\"x\": -0.0038, \"y\": -1.2462, \"id\": 5}], \"top\": 1.7748, \"bottom\": -1.6, \"column\": [], \"window\": [], \"wall\": [{\"p1\": 0, \"p2\": 1, \"id\": 0}, {\"p1\": 1, \"p2\": 2, \"id\": 1}, {\"p1\": 2, \"p2\": 3, \"id\": 2}, {\"p1\": 3, \"p2\": 4, \"id\": 3}, {\"p1\": 4, \"p2\": 5, \"id\": 4}, {\"p1\": 5, \"p2\": 0, \"id\": 5}], \"room\": [{\"cameras\": [\"0\"], \"showName\": true, \"subgroup\": 1, \"top\": 1.7748, \"bottom\": -1.6, \"name\": \"\\u623f\\u95f4-1\", \"points\": [0, 1, 2, 3, 4, 5], \"showArea\": true, \"group\": 1}]}, \"2-1_bb\": {\"door\": [], \"vertex\": [{\"x\": 0.2386, \"y\": -0.8504, \"id\": 6}, {\"x\": 0.2386, \"y\": 2.2796, \"id\": 7}, {\"x\": -2.7207, \"y\": 2.2796, \"id\": 8}, {\"x\": -2.7207, \"y\": -0.8504, \"id\": 9}], \"top\": 1.1707, \"bottom\": -1.6, \"column\": [], \"window\": [], \"wall\": [{\"p1\": 6, \"p2\": 7, \"id\": 6}, {\"p1\": 7, \"p2\": 8, \"id\": 7}, {\"p1\": 8, \"p2\": 9, \"id\": 8}, {\"p1\": 9, \"p2\": 6, \"id\": 9}], \"room\": [{\"cameras\": [\"0\"], \"showName\": true, \"subgroup\": 1, \"top\": 1.1707, \"bottom\": -1.6, \"name\": \"\\u623f\\u95f4-1\", \"points\": [6, 7, 8, 9], \"showArea\": true, \"group\": 1}]}}";
        house.setSceneJson(sceneJson);
        houseService2.update(house);
        return new R(2000, house.getId());
    }


    @GetMapping("mapper")
    public R userMapper(){
        List<UserEntity> users = userMapper.selectAll();
        return new R(2000, users);
    }

    @GetMapping("redis")
    public String redis(){
        redisTemplate.boundSetOps("owen1111").add("1","2","3");

        return new Date().toString();
    }

    @ApiOperation("测试参数为空时，查询是否会异常")
    @PostMapping("testParam")
    public R testParam(@RequestBody UserEntity param){
        // 不判断id也不会报错
//        User user = userService.findById(param.getId());

        return new R(2000, "");
    }



    @ApiOperation("测试example分页")
    @PostMapping("example")
    public R example(){
        UserEntity user = new UserEntity();
        user.setSex(1);


//        Page<User> pageAll = userService.findPageAll(Example.of(user));

        return new R(2000, "");
    }

//    @ApiOperation("用户注册/重置密码")
//    @GetMapping("table")
//    public R table(){
//        Map<String, Object> byUserName1 = userRepository.findByUserName1(Long.valueOf("9"));
//
//        return new R(2000, byUserName1);
//    }

    @GetMapping("test")
    public String test(){
        return new Date() + "";
    }



    @ApiOperation("测试上传")
    @PostMapping(value = "upload", consumes = {"multipart/form-data"})
    public R testUpload(@RequestParam("files") MultipartFile[] files){


        // 处理上传图片
        if (files == null || files.length <= 0) {
            log.info("文件为空");
            return new R(MsgCode.e_COMMON_3100, MsgCode.msg_COMMON_3100);
        }

        // 只有新增是才保存图片，修改时另外处理
        // 创建目录路径
        String directoryTimeName = DateUtil.format(new DateTime(), "yyyyMMdd_HHmmss");
        String directoryName = IMAGE_PATH + directoryTimeName;
        FileUtil.mkdir(directoryName);

        // 准备数据,key:原文件路径   value:oss路径， oss会自动创建目录
        HashMap<String, String> imageMap = new HashMap<>();
        for (MultipartFile file : files) {
            ImageEntity image = new ImageEntity();

            String filename = file.getOriginalFilename();
            String filePath = directoryName + File.separator + filename;
            String ossImagePath = ossPath + directoryTimeName+ "/" + filename;

            image.setFileName(filename);
            image.setPath(ossImagePath);
            image.setLocalPath(filePath);

            try {
                FileUtils.downloanAndGetResolutionRate(file.getInputStream(), filePath ,false);

            } catch (IOException e) {
                e.printStackTrace();
            }

            imageService2.save(image);
            imageMap.put(filePath, ossImagePath);
        }
        // 上传的到阿里云
        AliyunOssUtil.uploadMulFiles(imageMap);

        return new R(MsgCode.SUCCESS_CODE, MsgCode.msg_SUCCESS);
    }




}
