package com.YuyeTech.TPlat.controller;

import com.YuyeTech.TPlat.VO.ResultVO;
import com.YuyeTech.TPlat.dataobject.BluetoothInfo;
import com.YuyeTech.TPlat.dataobject.DeviceInfo;
import com.YuyeTech.TPlat.enums.DeviceEnum;
import com.YuyeTech.TPlat.exception.UserException;
import com.YuyeTech.TPlat.service.BluetoothInfoService;
import com.YuyeTech.TPlat.service.DeviceInfoService;
import com.YuyeTech.TPlat.utils.QRCodeUtil;
import com.YuyeTech.TPlat.utils.ResultVOUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
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 javax.validation.constraints.Null;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 管理蓝牙设备mac地址生成
 * @author:slambb
 * @date:2020/12/30
 */
@RestController
@RequestMapping("/backstage_ble")
@Slf4j
public class BackstageBLEDeviceController {
    @Autowired
    private BluetoothInfoService bluetoothInfoService;

    //http://192.168.0.112:9090/api_dev/backstage_ble/generate?startIndex=10&name="1"&Number=100
    @GetMapping(value = "/generate")
    public ResultVO generateBluetoothInfo(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "startIndex") Integer startIndex,
            @RequestParam(value = "Number") Integer Number ){
        if(Number>100){
            log.info("number过大：{}",Number);
            return ResultVOUtil.error(200,"number过大");
        }
        //todo 创建uuids
        //     存储到数据库表
        //     生成对应的信息二维码
        List<BluetoothInfo> bluetoothInfos = new ArrayList<>();

        String identifier = System.currentTimeMillis()+"";
        for (int i=0;i<Number;i++){
            BluetoothInfo bluetoothInfo = new BluetoothInfo();

            //设备名字
            Integer _writeIndex = startIndex + i;
            String _bleName = new StringBuffer(name).append('_').append(_writeIndex).toString();
            bluetoothInfo.setBluetoothName(_bleName);
            //mac地址 c55c19040000
            String oriStr = "C55C19040000";
            BigInteger oriInt =  new BigInteger(oriStr,16);
            BigInteger outInt = oriInt.add(BigInteger.valueOf(_writeIndex));
            String outOriStr = outInt.toString(16);
            String regex = "(\\w)(?=(\\w{2})+(?!\\w))";//"(.{2})";
            String result = outOriStr.replaceAll(regex, "$1:").toUpperCase();
            //设置mac地址
            bluetoothInfo.setBluetoothMac(result);
            //绑定状态
            bluetoothInfo.setBluetoothStatus(0);
            //3 是蓝牙设备
            bluetoothInfo.setBluetoothType(3);


            bluetoothInfos.add(bluetoothInfo);
        }

//        bluetoothInfoService.addMoreBluetoothInfos();
        Map map = new HashMap();
//        map.put("identifier",identifier);
        return ResultVOUtil.success(bluetoothInfos);
    }

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

        String name = request.getParameter("name");
        String startIndex = request.getParameter("startIndex");
        String strNum = request.getParameter("number");
        if(StringUtils.isEmpty(strNum)){
            map.put("msg","Number不能为空 ！");
            map.put("url","/backstage_ble/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_ble/generateManager");
            return new ModelAndView("common/error",map);
        }
        //todo 创建uuids
        //     存储到数据库表
        //     生成对应的信息二维码
        List<BluetoothInfo> bluetoothInfos = new ArrayList<>();

        String identifier = System.currentTimeMillis()+"";
        for (int i=0;i<Number;i++){
            BluetoothInfo bluetoothInfo = new BluetoothInfo();
            //设备名字
            Integer _writeIndex = Integer.valueOf(startIndex) + i;
            String _bleName = new StringBuffer(name).append('_').append(_writeIndex).toString();
            bluetoothInfo.setBluetoothName(_bleName);
            //mac地址 c55c19040000
            String oriStr = "C55C19040000";
            BigInteger oriInt =  new BigInteger(oriStr,16);
            BigInteger outInt = oriInt.add(BigInteger.valueOf(_writeIndex));
            String outOriStr = outInt.toString(16);
            String regex = "(\\w)(?=(\\w{2})+(?!\\w))";//"(.{2})";
            String result = outOriStr.replaceAll(regex, "$1:").toUpperCase();
            //设置mac地址
            bluetoothInfo.setBluetoothMac(result);
            //绑定状态
            bluetoothInfo.setBluetoothStatus(0);
            //3 是蓝牙设备
            bluetoothInfo.setBluetoothType(3);
            //设置不共享 0
            bluetoothInfo.setIsShare(0);

            bluetoothInfo.setIdentifier(identifier);

            bluetoothInfos.add(bluetoothInfo);
        }
        List<BluetoothInfo> callback = bluetoothInfoService.addMoreBluetoothInfos(bluetoothInfos);
        map.put("bleInfos", callback);
        map.put("identifier",identifier);
        map.put("number",strNum);
        map.put("startIndex",startIndex);
        map.put("name",name);
        return new ModelAndView("/ble/generate",map);
    }

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

        String singleName = request.getParameter("singleName");
        String mac = request.getParameter("mac");
        if(StringUtils.isEmpty(singleName)){
            map.put("msg","singleName不能为空 ！");
            map.put("url","/backstage_ble/generateManager?single_name="+singleName);
            return new ModelAndView("common/error",map);
        }
        if(StringUtils.isEmpty(mac)){
            map.put("msg","mac不能为空 ！");
            map.put("url","/backstage_ble/generateManager?single_name="+singleName+"&mac="+mac);
            return new ModelAndView("common/error",map);
        }
        try {
            BluetoothInfo hasBluetoothInfo = bluetoothInfoService.findByMac(mac);
            if(hasBluetoothInfo != null){
                map.put("msg","mac已存在 ！");
                map.put("url","/backstage_ble/generateManager?single_name="+singleName+"&mac="+mac);
                return new ModelAndView("common/error",map);
            }
        }catch (IncorrectResultSizeDataAccessException e){
            map.put("msg","mac在数据库中存在多个，请删除多余的数据！！");
            map.put("url","/backstage_ble/generateManager?single_name="+singleName+"&mac="+mac);
            return new ModelAndView("common/error",map);
        }

        BluetoothInfo bluetoothInfo = new BluetoothInfo();
        //设备名字
        String identifier = System.currentTimeMillis()+"";
        bluetoothInfo.setBluetoothName(singleName);
        //设置mac地址
        bluetoothInfo.setBluetoothMac(mac);
        //绑定状态
        bluetoothInfo.setBluetoothStatus(0);
        //3 是蓝牙设备
        bluetoothInfo.setBluetoothType(3);
        //设置不共享 0
        bluetoothInfo.setIsShare(0);

        bluetoothInfo.setIdentifier(identifier);

        List<BluetoothInfo> bluetoothInfos = new ArrayList<>();
        BluetoothInfo callback = bluetoothInfoService.saveBluetoothInfo(bluetoothInfo);
        bluetoothInfos.add(callback);
        map.put("bleInfos", bluetoothInfos);
        map.put("identifier",identifier);
        map.put("singleName",singleName);
        map.put("mac",mac);

        return new ModelAndView("/ble/generate",map);
    }
    /**
     * 蓝牙列表
     * @param page 第几页, 从1页开始
     * @param size 一页有多少条数据
     * @return
     */
    @GetMapping("/list")
    public ModelAndView gotoList(@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<BluetoothInfo> bluetoothInfos = bluetoothInfoService.findAllBLEInfoByPageable(request);
        map.put("bleInfos", bluetoothInfos);
        map.put("currentPage", page);
        map.put("size", size);
        return new ModelAndView("/ble/list", map);
    }

    @GetMapping("/generateManager")
    public ModelAndView gotoGenerateManager(
            @RequestParam(value = "single_name",defaultValue = "BGBOX_202012") String singleName,
            @RequestParam(value = "mac",defaultValue = "C5:5C:19:04:00:00") String mac,
            @RequestParam(value = "name",defaultValue = "BGBOX_202012") String name,
            Map<String, Object> map) {
        map.put("singleName",singleName);
        map.put("name",name);
        map.put("mac",mac);
        return new ModelAndView("/ble/generate",map);
    }

    /**
     * 根据蓝牙mac搜索
     * @return
     */
    @PostMapping("/searchBluetoothInfo")
    public ModelAndView gotoSearchBluetoothInfo(
            @RequestParam(value = "bleMac") String bleMac,
            @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(bleMac)){
            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<BluetoothInfo> bluetoothInfos = bluetoothInfoService.findAllBLEByPageableAndMac(request,bleMac);
            map.put("bleMac",bleMac);
            map.put("bleInfos", bluetoothInfos);
            map.put("currentPage", page);
            map.put("size", size);
            return new ModelAndView("/ble/list", map);
        } catch (UserException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/backstage_ble/list");
            return new ModelAndView("common/error", map);
        }

    }

    @GetMapping("/deleteGenerateBLE")
    public ModelAndView gotoDeleteGenerateBLE(@RequestParam(value = "id") Integer id,
                                              @RequestParam(value = "identifier") String identifier,
                                              @RequestParam(value = "single_name") String singleName,
                                              @RequestParam(value = "mac") String mac,
                                              @RequestParam(value = "name") String name,
                                      Map<String, Object> map) {

        try {
            bluetoothInfoService.deleteBluetoothInfoById(id);
        }catch ( EmptyResultDataAccessException e){
            log.info("gotoDeleteGenerateBLE 删除不存在的数据");
        }
        //删除后根据标识查找数据
        List<BluetoothInfo> bluetoothInfos =  bluetoothInfoService.findAllByIdentifier(identifier);
        map.put("bleInfos", bluetoothInfos);
        map.put("identifier",identifier);

        map.put("bleInfos", bluetoothInfos);
        map.put("identifier",identifier);
        map.put("singleName",singleName);
        map.put("name",name);
        map.put("mac",mac);
        return new ModelAndView("/ble/generate",map);


    }

    @GetMapping("/reset_bind")
    public ModelAndView resetBind(@RequestParam(value = "bleMac") String bleMac,
                                  @RequestParam(value = "page", defaultValue = "1") Integer page,
                                  @RequestParam(value = "size", defaultValue = "10") Integer size,
                                  Map<String, Object> map) {


        if(StringUtils.isEmpty(bleMac)){
            map.put("msg", DeviceEnum.UUID_NULL.getMessage());
            map.put("url", "/backstage_device/list");
            return new ModelAndView("common/error", map);
        }
        //todo 先重置信息
        try {

            BluetoothInfo bluetoothInfo = bluetoothInfoService.findByMac(bleMac);
            bluetoothInfo.setIsShare(0);
            bluetoothInfo.setBluetoothStatus(0);
            bluetoothInfo.setUserId(null);
            bluetoothInfoService.saveBluetoothInfo(bluetoothInfo);

            PageRequest request = PageRequest.of(page-1, size);
            List<BluetoothInfo> bluetoothInfoList = new ArrayList<>();
            bluetoothInfoList.add(bluetoothInfo);
            Page<BluetoothInfo> bluetoothInfos = new PageImpl<>(bluetoothInfoList,request,bluetoothInfoList.size());
            map.put("bleMac",bleMac);
            map.put("bleInfos", bluetoothInfos);
            map.put("currentPage", page);
            map.put("size", size);
            return new ModelAndView("/ble/list", map);
        } catch (UserException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/backstage_ble/list");
            return new ModelAndView("common/error", map);
        }
    }
}
