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

import com.alibaba.fastjson.JSONObject;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.entity.DeviceInfo;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.DeviceInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonDeviceRelationService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.constant.LApiConstant;
import com.jpsoft.shinestar.modules.pacs.dto.PacsMsgResult;
import com.jpsoft.shinestar.modules.uniview.request.LapiRequest;
import com.jpsoft.shinestar.modules.pacs.service.IGuardService;
import io.netty.handler.codec.http.HttpMethod;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/devOps")
@Api(description = "运维人员操作")
public class DevOpsController {
    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonDeviceRelationService personDeviceRelationService;

    @Autowired
    private IGuardService lapiService;

    @Autowired
    private LapiRequest lapiRequest;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("login")
    public String loginPage(){
        return "login";
    }

    @GetMapping("listOfSchool")
    public String listOfSchoolPage(){
        return "listOfSchool";
    }

    @GetMapping("listOfDevice")
    public String listOfDevicePage(String schoolId){
        return "listOfDevice";
    }

    @GetMapping("listOfPeopleLib")
    public String listOfPeopleLibPage(String schoolId, String deviceId, Model model){
        CompanyInfo school = companyInfoService.get(schoolId);
        model.addAttribute("school",school);

        DeviceInfo deviceInfo = deviceInfoService.get(deviceId);
        model.addAttribute("device",deviceInfo);

        return "listOfPeopleLib";
    }

    @GetMapping("listOfPeople")
    public String listOfPeoplePage(String deviceId,Model model){
        DeviceInfo deviceInfo = deviceInfoService.get(deviceId);
        model.addAttribute("device",deviceInfo);

        return "listOfPeople";
    }

    @ResponseBody
    @ApiOperation(value="获取设备列表")
    @PostMapping("listOfDevice")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "schoolId",value = "学校id", required = true,paramType = "query")
    })
    public MessageResult<List<DeviceInfo>> listOfDevice(String schoolId){
        MessageResult<List<DeviceInfo> > msgResult = new MessageResult<>();

        List<DeviceInfo> deviceInfoList = deviceInfoService.findByCompanyIdRelation(schoolId);

        List<DeviceInfo> filterList = deviceInfoList.stream()
                .filter((deviceInfo -> !deviceInfo.getDelFlag()))
                .collect(Collectors.toList());

        msgResult.setResult(true);
        msgResult.setData(filterList);
        return msgResult;
    }

    @ResponseBody
    @ApiOperation(value="远程开门")
    @PostMapping("remoteOpened")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceId",value = "设备编号", required = true,paramType = "query")
    })
    public MessageResult<String> remoteOpened(String deviceId){
        MessageResult<String> msgResult = new MessageResult<>();

        try {
            PacsMsgResult pacsMsgResult = lapiService.remoteOpen(deviceId);

            msgResult.setResult(pacsMsgResult.isSuccess());

            if (msgResult.isResult()){
                msgResult.setMessage("远程开门成功!");
            }
            else{
                msgResult.setMessage(pacsMsgResult.getMsg());
            }
        }
        catch (Exception ex){
            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ResponseBody
    @ApiOperation(value="查询人员库")
    @GetMapping("queryPeopleLib")
    public MessageResult<JSONObject> queryPeopleLib(String deviceNo){
        MessageResult<JSONObject> msgResult = new MessageResult<>();

        try {
            JSONObject jsonObject = lapiRequest.send(deviceNo,LApiConstant.GETFACEDB, HttpMethod.GET, null);
            msgResult.setData(jsonObject);
            msgResult.setResult(true);
        }
        catch(Exception ex){
            log.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ResponseBody
    @ApiOperation(value="查询人员")
    @PostMapping("queryPeople")
    @ApiImplicitParams({
            @ApiImplicitParam(name="deviceNo",value = "设备编号",required = true,paramType = "form"),
            @ApiImplicitParam(name="libId",value = "人员库编号",required = true,paramType = "form"),
            @ApiImplicitParam(name="qryType",value = "查询类型(27:人员编号，55:人员姓名，58：证件号,无查询条件则获取所有人员信息)",paramType = "form"),
            @ApiImplicitParam(name="qryData",value = "查询内容",paramType = "form"),
            @ApiImplicitParam(name="offset",value = "偏移量",paramType = "form"),
            @ApiImplicitParam(name="limit",value = "每页条数",paramType = "form")
    })
    public MessageResult<JSONObject> queryPeople(String deviceNo, String libId,
                                                 @DefaultValue(value = "27") String qryType,
                                                 String qryData,
                                                 @DefaultValue(value = "0") int offset,
                                                 @DefaultValue(value = "5") int limit){
        MessageResult<JSONObject> msgResult = new MessageResult<>();

        try {
            HashMap map = new HashMap();
            map.put("Limit", limit);
            map.put("Offset", offset);
            List queryInfos = new ArrayList();

            if(StringUtils.isNotEmpty(qryData)) {
                HashMap queryInfo = new HashMap();
                queryInfo.put("QryType", qryType);
                queryInfo.put("QryCondition", 0);
                queryInfo.put("QryData", qryData);
                queryInfos.add(queryInfo);
            }

            if (queryInfos.size()>0) {
                map.put("QueryInfos", queryInfos);
                map.put("Num", queryInfos.size());
            }

            JSONObject jsonObject = lapiRequest.send(deviceNo, LApiConstant.PEOPLE_LIBRARIES + libId + "/People/Info", HttpMethod.POST, map);

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

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

        return msgResult;
    }

    @ResponseBody
    @ApiOperation(value="删除设备中的人员")
    @PostMapping("deletePeople")
    @ApiImplicitParams({
            @ApiImplicitParam(name="deviceNo",value = "设备编号",required = true,paramType = "form"),
            @ApiImplicitParam(name="libId",value = "人员库编号",required = true,paramType = "form"),
            @ApiImplicitParam(name="personId",value = "人员编号",required = true,paramType = "form")
    })
    public MessageResult<JSONObject> deletePeople(String deviceNo, String libId, String personId){
        MessageResult<JSONObject> msgResult = new MessageResult<>();

        try {
            Date now = new Date();

            JSONObject jsonObject = lapiRequest.send(deviceNo,
                    LApiConstant.DELETEPERSON + libId + "/People/" + personId + "?LastChange=" + now.getTime(),
                    HttpMethod.DELETE, null);

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

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

        return msgResult;
    }
}
