package com.jpsoft.shinestar.modules.hikvision.controller;

import com.jpsoft.ehome.common.EHomeResult;
import com.jpsoft.ehome.config.EHomeParamConfig;
import com.jpsoft.ehome.device.EHomeDeviceManager;
import com.jpsoft.ehome.device.EHomeSDK;
import com.jpsoft.ehome.xml.InputXmlSection;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.hikvision.service.IEHomeService;
import com.jpsoft.shinestar.modules.pacs.dto.PacsMsgResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

@Slf4j
@Api
@RestController
@RequestMapping(value = "ehome")
public class EHomeController {
    @Autowired
    private EHomeSDK eHomeSDK;

    @Autowired
    private EHomeParamConfig eHomeConfig;

    @GetMapping("deviceList")
    @ApiOperation(value="查看在线设备列表")
    public MessageResult<List> deviceList(){
        MessageResult<List> messageResult = new MessageResult<>();

        try {
            List<Map> data = EHomeDeviceManager.onlineList();

            messageResult.setData(data);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);

            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @ApiOperation(value="读取设备设置")
    @PostMapping("getDeviceConfig")
    public EHomeResult<String> getDeviceConfig(Integer loginID, @RequestBody String inputXML) throws UnsupportedEncodingException {
        return eHomeSDK.deviceXMLConfig(loginID, "GETDEVICECONFIG", inputXML);
    }

    @ApiOperation(value="设置设备设置")
    @PostMapping("setDeviceConfig")
    public EHomeResult<String> setDeviceConfig(Integer loginID, @RequestBody String inputXML) throws UnsupportedEncodingException {
        return eHomeSDK.deviceXMLConfig(loginID, "SETDEVICECONFIG", inputXML);
    }

    @ApiOperation(value="获取远程配置")
    @RequestMapping(value = "getXMLConfig",method = {RequestMethod.GET})
    public EHomeResult<String> getXMLConfig(HttpServletRequest request, Integer loginID,String deviceNo, String url) throws UnsupportedEncodingException {
        if (StringUtils.isNotEmpty(deviceNo)){
            loginID = EHomeDeviceManager.get(deviceNo);
        }

        return eHomeSDK.ptXMLConfig(request.getMethod(), loginID, url, null, null);
    }

    @ApiOperation(value="远程配置")
    @RequestMapping(value = "setXMLConfig",method = {RequestMethod.POST,RequestMethod.PUT})
    public EHomeResult<String> setXMLConfig(HttpServletRequest request, Integer loginID,String deviceNo, String url, @RequestBody String inputXML) throws UnsupportedEncodingException {
        if (StringUtils.isNotEmpty(deviceNo)){
            loginID = EHomeDeviceManager.get(deviceNo);
        }

        return eHomeSDK.ptXMLConfig(request.getMethod(), loginID, url, null, inputXML);
    }

    @PostMapping("uploadPicture")
    @ApiOperation(value="上传照片")
    public EHomeResult<String> uploadPicture(MultipartFile photoFile){
        EHomeResult<String> messageResult = new EHomeResult<>();

        try {
            //todo 填写具体代码
            //荆楚云docker容器中无法访问服务器外网IP
            messageResult = eHomeSDK.clientUpload("127.0.0.1",
                    eHomeConfig.getPictureServerTcpPort(),photoFile.getInputStream(),
                    eHomeConfig.getUrlPrefix());
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);

            messageResult.setSuccess(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @GetMapping("remoteOpen")
    @ApiOperation(value="远程开门")
    public EHomeResult<String> remoteOpen(int loginID){
        EHomeResult<String> eHomeResult = new EHomeResult<>();

        try {
            eHomeResult = eHomeSDK.remoteControl(loginID, InputXmlSection.remoteControlXml("1","OPEN"));
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);

            eHomeResult.setSuccess(false);
            eHomeResult.setMessage(ex.getMessage());
        }

        return eHomeResult;
    }

    @PostMapping("deletePersonFromDevice")
    @ApiOperation(value="从设备中删除用户信息")
    public PacsMsgResult deletePersonFromDevice(String deviceNo,Long personId){
        PacsMsgResult pacsMsgResult = new PacsMsgResult();

        pacsMsgResult.setPersonId(personId);

        Integer loginID = EHomeDeviceManager.get(deviceNo);
        String cardNo = String.valueOf(personId);

        try {
            EHomeResult<String> eHomeResult = eHomeSDK.deviceXMLConfig(loginID, "SETDEVICECONFIG",
                    InputXmlSection.setCardConfigXml(cardNo, 0, null, null));

            pacsMsgResult.setSuccess(eHomeResult.isSuccess());
            pacsMsgResult.setMsg(eHomeResult.getMessage());
        }
        catch (Exception ex){
            pacsMsgResult.setSuccess(false);
            pacsMsgResult.setMsg(ex.getMessage());

            log.error(ex.getMessage(),ex);
        }

        return pacsMsgResult;
    }

    @PostMapping("userToDevice")
    @ApiOperation(value="用户信息下发到设备")
    public EHomeResult<String> userToDevice(int loginID,String employeeNo,String name,MultipartFile photoFile){
        EHomeResult<String> messageResult = new EHomeResult<>();

        try {
            //1.下发卡号 SetCardCfg
            messageResult = eHomeSDK.deviceXMLConfig(loginID, "SETDEVICECONFIG",
                    InputXmlSection.setCardConfigXml(employeeNo,1,employeeNo,name));

            if (!messageResult.isSuccess()){
                throw new Exception("下发卡号失败!" + messageResult.getMessage());
            }

            //2.卡号开权限 SetCardRightCfg
            messageResult = eHomeSDK.deviceXMLConfig(loginID,"SETDEVICECONFIG",
                    InputXmlSection.cardRightConfigXml(employeeNo));

            if (!messageResult.isSuccess()){
                throw new Exception("卡号权限设置失败!" + messageResult.getMessage());
            }

            //3.上传人脸照片到KMS,文件名字不能有中文
            messageResult = eHomeSDK.clientUpload(eHomeConfig.getRemoteIP(),
                    eHomeConfig.getPictureServerTcpPort(),
                    photoFile.getInputStream(),eHomeConfig.getUrlPrefix());

            if (!messageResult.isSuccess()){
                throw new Exception("上传人脸照片到KMS失败!" + messageResult.getMessage());
            }

            //4.下发人脸照片到设备 SetFaceParamCfg
            String facePicUrl = messageResult.getData();

            messageResult = eHomeSDK.ptXMLConfig("POST", loginID,
                    "/ISAPI/AccessControl/SetFaceParamCfg",null,InputXmlSection.faceParamCfgXml(employeeNo,facePicUrl));
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);

            messageResult.setSuccess(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

}
