package tech.glinfo.enbao.modules.sh.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.glinfo.enbao.common.contants.Constants;
import tech.glinfo.enbao.common.utils.*;
import tech.glinfo.enbao.modules.mq.MqProducer;
import tech.glinfo.enbao.modules.sh.entity.ShDeviceEntity;
import tech.glinfo.enbao.modules.sh.form.ProtocolContent;
import tech.glinfo.enbao.modules.sh.service.OtherShDeviceService;
import tech.glinfo.enbao.modules.sys.controller.AbstractController;
import tech.glinfo.enbao.modules.sys.entity.SysUserEntity;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 设备管理
 *
 * @author linzhenjie
 * @email linzhenjie@gltech.com
 * @date 2019-12-17 14:57:03
 */
@RestController
@RequestMapping("sh/device")
public class ShDeviceController extends AbstractController {

    private final static Logger logger = LoggerFactory.getLogger(ShDeviceController.class);

    @Value("${upload.qrcode}")
    private String uploadFolder;

    @Value("${upload.path}")
    private String uploadPath;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private OtherShDeviceService otherShDeviceService;

    @Autowired
    private NumberingUtils numberingUtils;

    @Autowired
    private MqProducer mqProducer;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sh:device:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = otherShDeviceService.queryPage(params);

        return R.ok().put("page", page);
    }
    @PostMapping("/useTime")
    @RequiresPermissions("sh:device:list")
    public R useTime(@RequestBody Map<String, Object> params) {
        System.out.println("numbering=" + params.get("numbering"));
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId((String) params.get("numbering"));
        protocol.setContent("");
        protocol.setDeviceType("01");
        protocol.setCmd("04");
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }

    @PostMapping("/setUseTime")
    @RequiresPermissions("sh:device:list")
    public R setUseTime(@RequestBody Map<String, Object> params) {
        logger.info("numbering=" + params.get("numbering"));
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId((String) params.get("numbering"));
        protocol.setContent("FFFFFFFFFFFFFF");
        protocol.setDeviceType("01");
        protocol.setCmd("12");
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }

    @GetMapping("/getUseTime")
    @RequiresPermissions("sh:device:list")
    public R getUseTime(@RequestParam Map<String, Object> params) {
        String uesTime = redisUtils.get(Constants.FILTER_UES_TIME + params.get("numbering"));
        if (uesTime == null) {
            return R.ok().put("useTime", "没有获取到使用期限");
        } else {
            if ("FFFFFFFFFFFFFF".equals(uesTime)) {
                logger.info("uesTime=永久使用");
                return R.ok().put("useTime", "永久使用");
            }else {
                String year = String.valueOf(Integer.valueOf(uesTime.substring(0, 4), 16));
                String month = String.valueOf(Integer.valueOf(uesTime.substring(4, 6), 16));
                String day = String.valueOf(Integer.valueOf(uesTime.substring(6, 8), 16));
                String hour = String.valueOf(Integer.valueOf(uesTime.substring(8, 10), 16));
                String minute = String.valueOf(Integer.valueOf(uesTime.substring(10, 12), 16));
                return R.ok().put("useTime", year + "-" + month + "-" + day + " " + hour + ":" + minute);
            }
        }
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sh:device:info")
    public R info(@PathVariable("id") Integer id) {
        return R.ok().put("device", otherShDeviceService.info(id));
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sh:device:delete")
    public R delete(@RequestBody Integer[] ids) {
        otherShDeviceService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }


    /**
     * 信息
     */
    @RequestMapping("/getNumbering")
    public R getNumbering(Integer count, String type) {
        //判断本周是否已生成
        String format = LocalDate.now().format(DateTimeFormatter.ofPattern("YY"));
        String format1 = LocalDate.now().format(DateTimeFormatter.ofPattern("w"));
        StringBuffer format2 = new StringBuffer();
        format2.append(format);
        if (format1.length() == 1) {
            format2.append("0");
        }
        format2.append(format1);
        String numbering = redisUtils.get(format2.toString() + type);
        if (numbering != null) {
            if (Integer.parseInt(numbering) > 99999) {
                return R.error("一周最多生成99999个设备编号！");
            }
        }
        //生成编号
        List<Map<String, Object>> list = numberingUtils.nextId1(count, type);

        SysUserEntity sysUserEntity = getUser();
        return R.ok().put("list", list).put("name", sysUserEntity.getUsername() + DateUtils.format(new Date(), "yyyyMMddHHmmss"));
    }

}
