package com.ics.controller.mobile.meeting;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ics.admin.domain.meeting.*;
import com.ics.admin.domain.meeting.vo.DeviceData;
import com.ics.admin.service.meeting.*;
import com.ics.common.core.controller.BaseController;
import com.ics.common.core.domain.R;
import com.ics.common.core.page.PageDomain;
import com.ics.common.core.page.TableSupport;
import com.ics.common.utils.DeviceUtils;
import com.ics.common.utils.StringUtils;
import com.ics.common.utils.device.SignUtils;
import com.ics.common.utils.device.WisDomDeviceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.annotation.Ignore;
import org.wf.jwtp.annotation.RequiresPermissions;

import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/equipment")
public class ApiEquipmentController extends BaseController {


    @Autowired
    private IUserEquipmentService userEquipmentService;

    @Autowired
    private IEquipmentService equipmentService;

    @Autowired
    private IRoomRecordService roomRecordService;

    @Autowired
    private IRoomEquipmentService roomEquipmentService;

    @Autowired
    private IVisitorPersonService visitorPersonService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;



    String smallWxAccessTokenKey = "nantong-";

    //根据用户id查询对应的设备， 楼层分割，房间，设备信息，
    @RequiresPermissions("member:center:view")
    @GetMapping("/getEquipmentByUserId/{userId}")
    public R getEquipmentByUserId(@PathVariable("userId") Long userId) {


        List<UserEquipment> equipments = userEquipmentService.getEquipmentByUserId(userId);


        return R.ok().put("data", equipments);
    }


    /**
     * 开门
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("/openDoor")
    public R openDoor(@RequestBody RoomRecord roomRecord) {
        //判断用户是否有权限开门
        UserEquipment userEquipment1 = new UserEquipment();
        userEquipment1.setEquipmentId(roomRecord.getDeviceId());
        userEquipment1.setUserId(roomRecord.getUserId());

        int count = userEquipmentService.selectCountByUserIdAndDeviceId(userEquipment1);

        if (count == 0) {
            return R.error("您没有权限开门,不在开门时间内");
        }

        Equipment equipment = equipmentService.selectEquipmentById(roomRecord.getDeviceId());
        if (equipment.getType() == 0) {
            String openlock = DeviceUtils.openlock(equipment.getIp());
            JSONObject jsonObject = JSONUtil.parseObj(openlock);
            Integer code = (Integer) jsonObject.get("status");
            Assert.isTrue(code == 0, "开门失败");


        } else if (equipment.getType() == 1) {
            String openlock = DeviceUtils.openControlLock(equipment.getIp());
            log.info("开门控制器的结果为结果:{}", openlock);
            ;
        }
        roomRecord.setType("0");
        int i = roomRecordService.insertRoomRecord(roomRecord);
        Assert.isTrue(i == 1, "开门失败");


        return R.ok("开门成功");
    }


    /**
     * 开门记录
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("/getOpenDoorRecord")
    public R getOpenDoorRecord(@RequestBody RoomRecord roomRecord) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        IPage<RoomRecord> openDoorRecord = roomRecordService.getOpenDoorRecord(roomRecord, pageNum, pageSize);
        for (RoomRecord record : openDoorRecord.getRecords()) {
            Equipment equipment = equipmentService.selectEquipmentById(record.getDeviceId());
            record.setDeviceName(equipment.getEquipmentName());
        }
        return R.ok().put("data", openDoorRecord);
    }

    /**
     * 获取对比记录,获取设备的对比记录，设备往服务端传输数据
     */
    @Ignore
    @PostMapping("/getEquipmentByUserIdAndEquipmentId")
    public R getEquipmentByUserIdAndEquipmentId(@RequestBody DeviceData data) {

        // 对比personId 和用户 id，
        // 对比equipmentId 和设备id

        if (data.getData() != null && data.getData().getEventType() != 17 && StringUtils.isNotEmpty(data.getData().getPersonId())) {
            //用户id
            String personId = data.getData().getPersonId();

            String deviceId = data.getData().getDeviceId();
            Equipment equipment = equipmentService.selectByDeviceCode(deviceId);
            Assert.isTrue(equipment != null, "设备不存在");
            RoomRecord record = new RoomRecord();
            record.setUserId(Long.valueOf(personId));

            if (data.getData().getPersonType().equals("visitor")) {
                VisitorPerson visitorPerson = visitorPersonService.selectByUserId(personId);
                record.setUserId(visitorPerson.getIntervieweeId());
            }
            assert equipment != null;
            record.setParkId(equipment.getParkId());
            record.setType("1");
            record.setDeviceId(equipment.getId());
            RoomEquipment roomEquipment = roomEquipmentService.selectByEquipmentId(equipment.getId());
            if (null != roomEquipment) {
                record.setRoomId(roomEquipment.getRoomId());
            }
            int i = roomRecordService.insertRoomRecord(record);
        }
//        log.info("上传的数据为{}",data.getData().getPersonId());

        return R.ok("调用成功");
    }


    /**
     * 扫描二维码开门 开门控制器  用户id 和设备id
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("/scanOpenDoor")
    public R scanOpenDoor(RoomRecord roomRecord) {


        log.info("用户id为{}", roomRecord.getUserId());
        log.info("房间id为{}", roomRecord.getRoomId());

        if (roomRecord.getEquipmentType().equals("displayScreen")) {
//            Long deviceId = roomRecord.getDeviceId();
//            Long userId = roomRecord.getUserId();

            UserEquipment userEquipment1 = new UserEquipment();
            userEquipment1.setEquipmentId(roomRecord.getDeviceId());
            userEquipment1.setUserId(roomRecord.getUserId());


            int count = userEquipmentService.selectCountByUserIdAndDeviceId(userEquipment1);
            if (count == 0) {
                return R.error("您没有权限开门");
            }

            String ip = equipmentService.selectEquipmentById(roomRecord.getDeviceId()).getIp();

            String openlock = DeviceUtils.openlock(ip);
            JSONObject jsonObject = JSONUtil.parseObj(openlock);
            Integer code = (Integer) jsonObject.get("status");
            Assert.isTrue(code == 0, "开门失败");

            int i = roomRecordService.insertRoomRecord(roomRecord);
            Assert.isTrue(i == 1, "开门失败");
        }

        if (roomRecord.getEquipmentType().equals("control")) {
            UserEquipment userEquipment1 = new UserEquipment();
            userEquipment1.setEquipmentId(roomRecord.getDeviceId());
            userEquipment1.setUserId(roomRecord.getUserId());


            int count = userEquipmentService.selectCountByUserIdAndDeviceId(userEquipment1);
            if (count == 0) {
                return R.error("您没有权限开门");
            }

            String ip = equipmentService.selectEquipmentById(roomRecord.getDeviceId()).getIp();

            String openlock = DeviceUtils.openControlLock(ip);
            log.info("开门控制器的结果为结果:{}", openlock);
            ;
        }

        return R.ok("开门成功");
    }




    /**
     * 扫描二维码开门  用户id 和设备id
     */
    @Ignore
    @PostMapping("/scanDoor")
    public R scanDoor(String ip) {
        // todo 开门
        // todo 获取ip后，key为ip，value为设备id 存入redis
        // 所有设备的ip都存入redis 里面
        System.out.println(ip);
        log.info("ip为{}", ip);
        return R.ok("开门成功");
    }

    /**
     * 开门接口，南通
     */
    @Ignore
    @GetMapping("/isOpenDoor")
    public R isOpenDoor(String ip) {
        // 根据ip 去redis读取数据
        String smallWxAccessToken = redisTemplate.opsForValue().get(smallWxAccessTokenKey + ip);
        if (StringUtils.isNotBlank(smallWxAccessToken)) {
            Boolean delete = redisTemplate.delete(smallWxAccessTokenKey + ip);
            if (delete) {
                R.error("删除redis失败");
            }
            return R.ok("开门成功");
        } else {
            return R.error("开门失败");
        }
    }
}
