package com.community.huiju.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.community.commom.hk.HKConstant;
import com.community.commom.hk.HKOpenApi;
import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.huiju.model.TpConfiguration;
import com.community.huiju.model.TpEquipment;
import com.community.huiju.model.TpEquipmentTree;
import com.community.huiju.service.ITpConfigurationService;
import com.community.huiju.service.ITpEquipmentService;
import com.community.huiju.service.ITpEquipmentTreeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/")
@Api(value = "自动配置门禁设备", description = "自动配置门禁设备")
public class HkDoorsController {

    @Autowired
    private ITpConfigurationService tpConfigurationService;

    @Autowired
    private ITpEquipmentTreeService tpEquipmentTreeService;

    @Autowired
    private ITpEquipmentService tpEquipmentService;

    @ApiOperation(value = "自动按小区配置门禁设备", notes = "自动按小区配置门禁设备")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataTypeClass = String.class, name = "communityId", value = "小区ID")
    })
    @RequestMapping(value = "/auto/door/{communityId}",method = RequestMethod.GET)
    public ResponseBean autoDoors(@PathVariable Integer communityId) {
        ResponseBean responseBean = new ResponseBean();
        //根小区获取设备树的详细信息
        QueryWrapper<TpEquipmentTree> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("community_id",communityId);
        TpEquipmentTree tpEquipmentTree = tpEquipmentTreeService.getOne(queryWrapper);
        //获取此小区的全部门禁点
        Map<String,Object> parMap = new HashMap<>();
        parMap.put("appkey",tpEquipmentTree.getAppkey());
        parMap.put("pageNo",1);
        parMap.put("pageSize",100);
        parMap.put("opUserUuid", tpEquipmentTree.getOpUserUuid());
        parMap.put("secret", tpEquipmentTree.getSecret());
        parMap.put("openapi_ip_port_http", tpEquipmentTree.getHttpServer());
        JSONObject jsonObject = JSONObject.parseObject(HKOpenApi.getDoorDevices(parMap));
        if (jsonObject.getIntValue("errorCode") != 0){
            responseBean.addError(jsonObject.getString("errorMessage"));
            return responseBean;
        }
        JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
        for (Object doorsJson : jsonArray){
            addDoorsData(communityId,tpEquipmentTree.getId(),doorsJson);
        }
        responseBean.addSuccess("插入成功");
        return responseBean;
    }

    /**
     * 添加新的设备
     * @param communityId
     * @param equipmentTreeId
     * @param doorsJson
     */
    private void addDoorsData(Integer communityId, Integer equipmentTreeId, Object doorsJson) {
        JSONObject doorJson = (JSONObject) doorsJson;
        boolean state = getSaveDoorState(communityId,equipmentTreeId,doorJson);
        if (state){
            //插入配置表config
            TpConfiguration tpConfiguration = new TpConfiguration();
            tpConfiguration.setKey("");
            tpConfiguration.setConfigurationName(doorJson.getString("deviceName"));
            tpConfiguration.setConfigurationType(1);
            tpConfiguration.setConfigurationValue(doorJson.getString("longNumber"));
            tpConfiguration.setCreateTiem(LocalDateTime.now());
            tpConfiguration.setCreateUser(1);
            tpConfiguration.setUpdateTime(LocalDateTime.now());
            tpConfiguration.setUpdateUser(1);
            tpConfiguration.setCommunityId(communityId);
            tpConfiguration.setDoorUuid(null);
            tpConfiguration.setDeviceUuid(doorJson.getString("deviceUuid"));
            tpConfiguration.setDeviceType(1);
            tpConfigurationService.save(tpConfiguration);

            //插入设备
            TpEquipment tpEquipment = new TpEquipment();
            tpEquipment.setCommunityId(communityId);
            tpEquipment.setCreateTime(LocalDateTime.now());
            tpEquipment.setCreateUser(1);
            tpEquipment.setUpdateTime(LocalDateTime.now());
            tpEquipment.setUpdateUser(1);
            tpEquipment.setUuidId(tpConfiguration.getId());
            tpEquipment.setEquipmentType("3");
            tpEquipment.setEquipmentTreeId(equipmentTreeId);
            tpEquipmentService.save(tpEquipment);

            //插入配置表config
            TpConfiguration videoConfiguration = new TpConfiguration();
            videoConfiguration.setKey("高清地址");
            videoConfiguration.setConfigurationName(doorJson.getString("deviceName")+"_视频流");
            videoConfiguration.setConfigurationType(1);
            videoConfiguration.setConfigurationValue("标清地址");
            videoConfiguration.setCreateTiem(LocalDateTime.now());
            videoConfiguration.setCreateUser(1);
            videoConfiguration.setUpdateTime(LocalDateTime.now());
            videoConfiguration.setUpdateUser(1);
            videoConfiguration.setCommunityId(communityId);
            videoConfiguration.setDoorUuid(null);
            videoConfiguration.setDeviceUuid(doorJson.getString("deviceUuid"));
//            videoConfiguration.setDeviceType(1);
            tpConfigurationService.save(videoConfiguration);

            //插入设备
            TpEquipment videoEquipment = new TpEquipment();
            videoEquipment.setCommunityId(communityId);
            videoEquipment.setCreateTime(LocalDateTime.now());
            videoEquipment.setCreateUser(1);
            videoEquipment.setUpdateTime(LocalDateTime.now());
            videoEquipment.setUpdateUser(1);
            videoEquipment.setEquipmentType("5");
            videoEquipment.setUuidId(videoConfiguration.getId());
            videoEquipment.setEquipmentTreeId(equipmentTreeId);
            videoEquipment.setAppkey("dbeb0f364e9149c19b06a858c5bb7c29");
            videoEquipment.setSecret("0b1933480ffbf01e9e5e5f4447033d12");
            tpEquipmentService.save(videoEquipment);
        }

    }

    /**
     * 判断是否插入字段
     * @param communityId
     * @param equipmentTreeId
     * @param doorJson
     * @return
     */
    private boolean getSaveDoorState(Integer communityId, Integer equipmentTreeId, JSONObject doorJson) {
        QueryWrapper<TpConfiguration> tpConfigurationQueryWrapper = new QueryWrapper<>();
        tpConfigurationQueryWrapper.eq("community_id",communityId);
        tpConfigurationQueryWrapper.isNotNull("deviceUuid");
        List<TpConfiguration> configurationList = tpConfigurationService.list(tpConfigurationQueryWrapper);
        for (TpConfiguration tpConfiguration : configurationList){
            if (tpConfiguration.getDeviceUuid().equals(doorJson.getString("deviceUuid"))){
                return false;
            }
        }
        return true;
    }
}
