package com.YuyeTech.TPlat.controller;

import com.YuyeTech.TPlat.VO.ResultVO;
import com.YuyeTech.TPlat.enums.DeviceEnum;
import com.YuyeTech.TPlat.exception.UserException;
import com.YuyeTech.TPlat.service.DeviceInfoService;
import com.alibaba.fastjson.JSONObject;
import com.YuyeTech.TPlat.dataobject.DeviceInfo;
import com.YuyeTech.TPlat.utils.QRCodeUtil;
import com.YuyeTech.TPlat.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 管理设备二维码生成
 * @author:slambb
 * @date:2020/6/11
 */
@RestController
@RequestMapping("/backstage_device")
@Slf4j
public class BackstageDeviceController {
    @Autowired
    private DeviceInfoService deviceInfoService;

    //http://192.168.0.108:9090/smallshop/backstage_device/generate?Number=10
    @GetMapping(value = "/generate")
    public ResultVO generateDeviceInfo(@RequestParam(value = "Number") Integer Number ){
        if(Number>100){
            log.info("number过大：{}",Number);
            return ResultVOUtil.error(200,"number过大");
        }
        //todo 创建uuids
        //     存储到数据库表
        //     生成对应的信息二维码
        List<DeviceInfo> deviceInfos = new ArrayList<>();

//        String[] uuids = new String[Number];
        String identifier = System.currentTimeMillis()+"";
        for (int i=0;i<Number;i++){
            String uuid= UUID.randomUUID().toString().replaceAll("-", "");
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setDeviceUuid(uuid);
            deviceInfo.setDeviceType(1);
            deviceInfo.setDeviceStatus(0);
            deviceInfo.setIdentifier(identifier);

            deviceInfos.add(deviceInfo);
        }

        deviceInfoService.addMultipleObjects(deviceInfos);
        Map map = new HashMap();
        map.put("identifier",identifier);
        return ResultVOUtil.success(map);
    }

    //http://192.168.0.108:9090/smallshop/backstage_device/download?identifier=1591971633420
    @PostMapping(value="/download")
    public void downloadCompressFile(@RequestParam(value = "identifier") String identifier ,
                                     HttpServletResponse response,
                                     Map<String, Object> map) throws Exception{
        //1.获取指定信息，
        List<DeviceInfo> deviceInfos =  deviceInfoService.findAllByIdentifier(identifier);
        if(deviceInfos.size() != 0){
            //2.下载压缩包
            ZipOutputStream zos = null;
            String  downloadFilename = "设备二维码_"+identifier;
            //转换中文否则可能会产生乱码
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
            // 指明response的返回对象是文件流
            response.setContentType("application/octet-stream");
            // 设置在下载框默认显示的文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename+".zip");
            zos = new ZipOutputStream(response.getOutputStream());
            for (int i = 0; i<deviceInfos.size(); i++){
                zos.putNextEntry(new ZipEntry("uuid_"+deviceInfos.get(i).getDeviceUuid()+".png"));
                JSONObject obj = new JSONObject();
                obj.put("uuid",deviceInfos.get(i).getDeviceUuid());
                obj.put("type",deviceInfos.get(i).getDeviceType());
                ImageIO.write(QRCodeUtil.encode(obj.toJSONString(), "static/images/icon-1024.png",true),"jpg",zos);
            }
            zos.flush();
            zos.close();
        }

    }

    /**
     * 二维码列表
     * @param page 第几页, 从1页开始
     * @param size 一页有多少条数据
     * @return
     */
    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "size", defaultValue = "10") Integer size,
                             Map<String, Object> map) {
        PageRequest request = PageRequest.of(page - 1, size);
        Page<DeviceInfo> deviceInfos = deviceInfoService.findAllDeviceByPageable(request);
        map.put("deviceInfos", deviceInfos);
        map.put("currentPage", page);
        map.put("size", size);
        return new ModelAndView("/device/list", map);
    }

    @GetMapping("/generateManager")
    public ModelAndView generateManager(Map<String, Object> map) {
        return new ModelAndView("/device/generate",map);
    }

    @PostMapping("/generateDeviceCode")
    public ModelAndView generateDeviceCode(HttpServletRequest request,Map<String, Object> map) {

        String strNum = request.getParameter("number");
        if(StringUtils.isEmpty(strNum)){
            map.put("msg","Number不能为空 ！");
            map.put("url","/backstage_device/generateManager");
            return new ModelAndView("common/error",map);
        }

        Integer Number = Integer.valueOf(strNum);
        if(Number>100||Number <=0){
            log.info("number 超出范围：{}",Number);
            map.put("msg","Number超过 100 或者小于等于 0 ！");
            map.put("url","/backstage_device/generateManager");
            return new ModelAndView("common/error",map);
        }
        //todo 创建uuids
        //     存储到数据库表
        //     生成对应的信息二维码
        List<DeviceInfo> deviceInfos = new ArrayList<>();
        String identifier = System.currentTimeMillis()+"";
        for (int i=0;i<Number;i++){
            String uuid= UUID.randomUUID().toString().replaceAll("-", "");
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setDeviceUuid(uuid);
            deviceInfo.setDeviceType(1);
            deviceInfo.setDeviceStatus(0);
            deviceInfo.setIdentifier(identifier);

            deviceInfos.add(deviceInfo);
        }
        List<DeviceInfo> callback = deviceInfoService.addMultipleObjects(deviceInfos);
        map.put("deviceInfos", callback);
        map.put("identifier",identifier);
        return new ModelAndView("/device/generate",map);
    }


    /**
     * 根据设备id搜索
     * @return
     */
    @PostMapping("/searchDeviceInfo")
    public ModelAndView searchDeviceInfo(
            @RequestParam(value = "deviceUuid") String deviceUuid,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            Map<String, Object> map) {
        if(page<1){
            map.put("msg", "page不能小于1.");
            map.put("url", "/backstage_device/list");
            return new ModelAndView("common/error", map);
        }
        if(StringUtils.isEmpty(deviceUuid)){
            map.put("msg", DeviceEnum.UUID_NULL.getMessage());
            map.put("url", "/backstage_device/list");
            return new ModelAndView("common/error", map);
        }
        //todo 根据用户名搜索,查询用户信息
        try {
            PageRequest request = PageRequest.of(page-1, size);
            Page<DeviceInfo> deviceInfos = deviceInfoService.findAllDeviceByPageableAndUUID(request,deviceUuid);
            map.put("deviceUuid",deviceUuid);
            map.put("deviceInfos", deviceInfos);
            map.put("currentPage", page);
            map.put("size", size);
            return new ModelAndView("/device/list", map);
        } catch (UserException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/backstage_device/list");
            return new ModelAndView("common/error", map);
        }

    }
}
