package com.dcsoft.system.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.system.domain.SysPeopleRule;
import com.dcsoft.system.service.ISysConfigService;
import com.dcsoft.system.service.ISysPeopleEquipmentService;
import com.dcsoft.system.service.ISysPeopleRuleService;
import com.dcsoft.system.uniubi.service.ISysApiService;
import com.dcsoft.system.uniubi.service.ISysSdkService;
import com.dcsoft.system.utils.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dcsoft.common.log.annotation.Log;
import com.dcsoft.common.log.enums.BusinessType;
import com.dcsoft.common.security.annotation.RequiresPermissions;
import com.dcsoft.system.domain.SysEquipment;
import com.dcsoft.system.service.ISysEquipmentService;
import com.dcsoft.common.core.web.controller.BaseController;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.core.utils.poi.ExcelUtil;
import com.dcsoft.common.core.web.page.TableDataInfo;

/**
 * 设备信息Controller
 *
 * @author nichun
 * @date 2023-03-08
 */
@RestController
@RequestMapping("/equipment")
public class SysEquipmentController extends BaseController
{
    @Autowired
    private ISysEquipmentService sysEquipmentService;

    @Autowired
    private ISysApiService sysApiService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysSdkService sdkService;

    @Autowired
    private ISysPeopleRuleService sysPeopleRuleService;

    @Autowired
    private ISysPeopleEquipmentService peopleEquipmentService;

    @Value("${server.ip}")
    private String ip;

    @Value("${server.inPort}")
    private String port;

    /**
     * 查询设备信息列表
     */
    @RequiresPermissions("system:equipment:list")
    @GetMapping("/list")
    public TableDataInfo list(SysEquipment sysEquipment)
    {
        startPage();
        List<SysEquipment> list = sysEquipmentService.selectSysEquipmentList(sysEquipment);
        return getDataTable(list);
    }

    @GetMapping("/alllist")
    public AjaxResult alllist(SysEquipment sysEquipment)
    {
        List<SysEquipment> list = sysEquipmentService.selectSysEquipmentList(sysEquipment);
        return AjaxResult.success(list);
    }

    /**
     * 导出设备信息列表
     */
    @RequiresPermissions("system:equipment:export")
    @Log(title = "设备信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysEquipment sysEquipment)
    {
        List<SysEquipment> list = sysEquipmentService.selectSysEquipmentList(sysEquipment);
        ExcelUtil<SysEquipment> util = new ExcelUtil<SysEquipment>(SysEquipment.class);
        util.exportExcel(response, list, "设备信息数据");
    }

    /**
     * 获取设备信息详细信息
     */
    @RequiresPermissions("system:equipment:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysEquipmentService.selectSysEquipmentById(id));
    }

    public void notification(SysEquipment sysEquipment) throws Exception {
        String xml= "<HttpHostNotification version=\"2.0\" xmlns=\"http://www.isapi.org/ver20/XMLSchema\">" +
                "<id>1</id>" +
                "<url>/system/api/remoteCheck</url>" +
                "<protocolType>HTTP</protocolType>" +
                "<parameterFormatType></parameterFormatType>" +
                "<addressingFormatType>ipaddress</addressingFormatType>" +
                "<ipAddress>"+ip+"</ipAddress>" +
                "<ipv6Address>::</ipv6Address>" +
                "<portNo>"+port+"</portNo>" +
                "<httpAuthenticationMethod>none</httpAuthenticationMethod>" +
                "<SubscribeEvent>" +
                "<heartbeat>30</heartbeat>" +
                "<pictureURLType>cloudStorageURL</pictureURLType>" +
                "<eventMode>all</eventMode>" +
                "<EventList>" +
                "<Event>" +
                "<type>AccessControllerEvent</type>" +
                "<minorAlarm></minorAlarm>" +
                "<minorException></minorException>" +
                "<minorOperation></minorOperation>" +
                "<minorEvent></minorEvent>" +
                "<pictureURLType>binary</pictureURLType>" +
                "</Event>" +
                "<Event>" +
                "<type>IDCardInfoEvent</type>" +
                "<minorEvent></minorEvent>" +
                "<pictureURLType>binary</pictureURLType>" +
                "</Event>" +
                "</EventList>" +
                "</SubscribeEvent>" +
                "</HttpHostNotification>";
        cn.hutool.json.JSONObject jsonObject2= HttpUtil.putISAPI(sysEquipment.getIp(), sysEquipment.getRemark(), sysEquipment.getPassword(), "/ISAPI/Event/notification/httpHosts/1",xml);
        System.out.println("返回信息+++++++++++++++"+jsonObject2);
    }

    /**
     * 新增设备信息
     */
    @RequiresPermissions("system:equipment:add")
    @Log(title = "设备信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysEquipment sysEquipment)
    {
        if("hkycsb".equals(sysEquipment.getSystemFlag())){
            try {
                notification(sysEquipment);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return toAjax(sysEquipmentService.insertSysEquipment(sysEquipment));
    }

    /**
     * 修改设备信息
     */
    @RequiresPermissions("system:equipment:edit")
    @Log(title = "设备信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysEquipment sysEquipment)
    {
        if("hkycsb".equals(sysEquipment.getSystemFlag())){
            try {
                notification(sysEquipment);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return toAjax(sysEquipmentService.updateSysEquipment(sysEquipment));
    }


    /**
     * 删除设备信息
     */
    @RequiresPermissions("system:equipment:remove")
    @Log(title = "设备信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {

        return toAjax(sysEquipmentService.deleteSysEquipmentByIds(ids));
    }

    /**
     * 设备控制
     */
    @GetMapping("/command/{id}/{type}")
    public AjaxResult command(@PathVariable Long id, @PathVariable Integer type) {
        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        SysEquipment equipment=sysEquipmentService.selectSysEquipmentById(id);
        /*if("true".equals(cloud)) {
            String data =sysApiService.deviceCommand(equipment,type);
            JSONObject jsons= JSONObject.parseObject(data);
            if(!"1".equals(jsons.get("result")+"")) {
                return error(jsons.get("msg")+"");
            }
        }else{
            String data="";
            if(type==1){//重启
                 data =sdkService.restartDevice(equipment.getIp(),equipment.getPassword());
            }else{//重置
                 data =sdkService.resetDevice(equipment.getIp(),equipment.getPassword());
            }
            JSONObject jsons= JSONObject.parseObject(data);
            if(!"1".equals(jsons.get("result")+"")) {
                return error(jsons.get("msg")+"");
            }
        }*/
        return AjaxResult.success();
    }

    /**
     * 设备控制
     */
    @GetMapping("/interactive/{id}")
    public AjaxResult interactive(@PathVariable Long id) {

        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        SysEquipment equipment=sysEquipmentService.selectSysEquipmentById(id);
       /* if("true".equals(cloud)) {
            String data =sysApiService.deviceInteractive(equipment);
            JSONObject jsons= JSONObject.parseObject(data);
            if(!"1".equals(jsons.get("result")+"")) {
                return error(jsons.get("msg")+"");
            }
        }else{
            String data =sdkService.openDoorControl(equipment.getIp(),equipment.getPassword());
            JSONObject jsons= JSONObject.parseObject(data);
            if(!"1".equals(jsons.get("result")+"")) {
                return error(jsons.get("msg")+"");
            }
        }*/
        return AjaxResult.success();
    }

    /**
     * 获取设备信息详细信息
     */
    @GetMapping(value = "/empty/{id}")
    public AjaxResult empty(@PathVariable("id") Long id)
    {
        //判断设备是否上云
        SysEquipment equipment=sysEquipmentService.selectSysEquipmentById(id);
        sdkService.personDelete("-1",equipment.getIp(),equipment.getPassword());
        return success(equipment);
    }

    /**
     * 获取设备信息详细信息
     */
    @GetMapping(value = "/recover/{id}")
    public AjaxResult recover(@PathVariable("id") Long id)
    {
        //判断设备是否上云
        //查询已经受过这设备的权限人员放入到关联表中
        List<Map<String,Object>> list=sysEquipmentService.selectSysEquipmentPeopleById(id);
        for(Map<String,Object> obj:list){
            Long peopleId=Long.parseLong(obj.get("people_id")+"");
            SysPeopleRule sysPeopleRule=new SysPeopleRule();
            sysPeopleRule.setPeopleId(peopleId);
            sysPeopleRule.setEquipmentId(id);
            sysPeopleRuleService.insertSysPeopleRule(sysPeopleRule);
        }
        return success(list);
    }

    /**
     * 获取设备信息详细信息
     */
    @GetMapping(value = "/sendConsume/{id}")
    public AjaxResult sendConsume(@PathVariable("id") Long id)
    {
        //判断设备是否上云
        int i=peopleEquipmentService.deleteSysPeopleEquipmentByEquipmentId(id);
        return success(i);
    }

    @Log(title = "海康设备同步", businessType = BusinessType.INSERT)
    @PostMapping("/syncEquipment")
    public AjaxResult syncEquipment()
    {
        return toAjax(sysEquipmentService.syncEquipment());
    }

    /**
     * 根据设备序列号查询设备信息
     * @param sysEquipment
     * @return
     */
    @PostMapping(value = "/queryEquipmentByDeviceKey")
    public AjaxResult queryEquipmentByDeviceKey(@RequestBody SysEquipment sysEquipment) {
        return success(sysEquipmentService.queryEquipmentByDeviceKey(sysEquipment));
    }

    /**
     * 根据设备序列号修改设备密码
     * @param sysEquipment
     * @return
     */
    @PostMapping(value = "/updateEquipmentByDeviceKey")
    public AjaxResult updateEquipmentByDeviceKey(@RequestBody SysEquipment sysEquipment) {
        sysEquipmentService.updateEquipmentByDeviceKey(sysEquipment);
        return success();
    }

    /**
     * 根据设备序列号修改设备轮播文件
     * @param sysEquipment
     * @return
     */
    @PostMapping(value = "/updateEquipmentFile")
    public AjaxResult updateEquipmentFile(@RequestBody SysEquipment sysEquipment) {
        sysEquipmentService.updateEquipmentFile(sysEquipment);
        return success();
    }

}
