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

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.live.model.v20161101.DescribeLiveStreamsOnlineListResponse;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.AliyunLiveConfig;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.config.YsConfig;
import com.jpsoft.shinestar.modules.base.entity.CameraCompany;
import com.jpsoft.shinestar.modules.base.entity.CameraInfo;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.entity.DeviceInfo;
import com.jpsoft.shinestar.modules.base.service.CameraCompanyService;
import com.jpsoft.shinestar.modules.base.service.CameraInfoService;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.dto.CameraPersonDTO;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.*;
import com.jpsoft.shinestar.modules.sys.entity.DataDictionary;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RestController
@RequestMapping("/base/cameraInfo")
@Api(description = "cameraInfo")
public class CameraInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CameraInfoService cameraInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private CameraCompanyService cameraCompanyService;

    @Autowired
    private YsUtil ysUtil;

    @Autowired
    private YsConfig ysConfig;

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private UserService userService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private AliyunLiveConfig aliyunLiveConfig;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<CameraInfo> create(){
        MessageResult<CameraInfo> msgResult = new MessageResult<>();

        CameraInfo cameraInfo = new CameraInfo();

        msgResult.setData(cameraInfo);
        msgResult.setResult(true);

        return msgResult;
    }

    @ApiOperation(value="查询设备信息")
    @GetMapping("queryDeviceInfo")
    public MessageResult<JSONObject> queryDeviceInfo(String deviceSerial,String classify){
        MessageResult<JSONObject> messageResult = new MessageResult<>();

        try {
            String appKey,appSecret;

            if ("1".equals(classify)){
                appKey = ysConfig.getFreeAppKey();
                appSecret = ysConfig.getFreeAppSecret();
            }
            else{
                appKey = ysConfig.getPayAppKey();
                appSecret = ysConfig.getPayAppSecret();
            }

            JSONObject deviceObj = ysUtil.getDeviceInfo(appKey,appSecret,deviceSerial);

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

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

        return messageResult;
    }

    @PostMapping(value="queryLiveAddressUrl")
    @ApiOperation(value = "查询直播地址")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "deviceSerial",value = "设备序列号", required = true, paramType = "form"),
        @ApiImplicitParam(name = "channelNo",value = "通道号", required = true, paramType = "form"),
        @ApiImplicitParam(name = "expireTime",value = "过期时间毫秒数", required = true, paramType = "form")
    })
    public MessageResult<JSONObject> queryLiveAddressUrl(String id,String deviceSerial,int channelNo,Long expireTime){
        MessageResult<JSONObject> messageResult = new MessageResult<>();
    
        try {
            CameraInfo cameraInfo = cameraInfoService.get(id);

            if ("ys".equals(cameraInfo.getPlatform())) {
                String appKey = cameraInfo.getAccount();
                String appSecret = cameraInfo.getPassword();

                JSONObject jsonObject = ysUtil.getLiveAddressUrl(appKey, appSecret, deviceSerial, channelNo, expireTime);

                messageResult.setData(jsonObject);
            }
            else if("aliyun".equals(cameraInfo.getPlatform())){
                //推流地址需要长期有效
                String pushStreamSignedUrl = AliyunLiveUtil.generateSignedUrl(aliyunLiveConfig.getPushStreamUrl(),
                        "/" + aliyunLiveConfig.getAppName() + "/" + deviceSerial,
                        (new Date()).getTime()/1000 + 365*24*3600,
                        aliyunLiveConfig.getPushKey());

                //播流地址短时间有效
                String pullStreamSignedUrl = AliyunLiveUtil.generateSignedUrl(
                        aliyunLiveConfig.getPullStreamUrl(),
                        "/" + aliyunLiveConfig.getAppName() + "/" + deviceSerial + ".m3u8",
                        (new Date()).getTime()/1000 + expireTime,
                        aliyunLiveConfig.getPullKey());

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("hdAddress", pullStreamSignedUrl);
                jsonObject.put("pushAddress", pushStreamSignedUrl);

                messageResult.setData(jsonObject);
            }

            messageResult.setResult(true);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return messageResult;
    }

    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<CameraInfo> add(@RequestBody CameraInfo cameraInfo,@RequestAttribute String subject){
        MessageResult<CameraInfo> msgResult = new MessageResult<>();

        try {
            cameraInfo.setId(UUID.randomUUID().toString());
            cameraInfo.setDelFlag(false);
            cameraInfo.setCreateBy(subject);
            cameraInfo.setCreateTime(new Date());

            updatePicUrl(cameraInfo);

            int affectCount = cameraInfoService.insert(cameraInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(cameraInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    private void updatePicUrl(@RequestBody CameraInfo cameraInfo) throws IOException {
        if ("ys".equals(cameraInfo.getPlatform())) {
            //查询设备在线状态
            JSONObject deviceObj = ysUtil.getDeviceInfo(cameraInfo.getAccount(), cameraInfo.getPassword(), cameraInfo.getDeviceSerial());

            if (deviceObj != null) {
                cameraInfo.setStatus(deviceObj.getInteger("status"));
            }

            if (Integer.valueOf(1).equals(cameraInfo.getStatus())) {
                String picUrl = ysUtil.capturePicture(cameraInfo.getAccount(), cameraInfo.getPassword(), cameraInfo.getDeviceSerial(), cameraInfo.getChannelNo());

                InputStream inputStream = HttpConnectionUtil.downloadStream(picUrl);

                if (inputStream != null) {
                    String newPicUrl = OSSUtil.upload(ossConfig, "ys7", "1.jpg", inputStream);
                    cameraInfo.setPicUrl(newPicUrl);

                    inputStream.close();
                } else {
                    cameraInfo.setPicUrl(picUrl);
                }
            }
        }
        else if("aliyun".equals(cameraInfo.getPlatform())){
            cameraInfo.setPicUrl(aliyunLiveConfig.getScreenshotUrl() + "/" + aliyunLiveConfig.getAppName() + "/" + cameraInfo.getDeviceSerial() + ".jpg");

            //查询设备推流是否在线
            List<DescribeLiveStreamsOnlineListResponse.LiveStreamOnlineInfo> onlineList =
                    AliyunLiveUtil.queryPushStreamOnlineList(aliyunLiveConfig.getRegionId(),
                    aliyunLiveConfig.getAccessKeyId(),
                    aliyunLiveConfig.getAccessKeySecret(),
                    aliyunLiveConfig.getPushStreamUrl().replace("rtmp://", ""),
                    aliyunLiveConfig.getAppName(),cameraInfo.getDeviceSerial());

            cameraInfo.setStatus(onlineList.size()>0 ? 1 : 0);
        }
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<CameraInfo> edit(@PathVariable("id") String id){
        MessageResult<CameraInfo> msgResult = new MessageResult<>();

        try {
            CameraInfo cameraInfo = cameraInfoService.get(id);

            if (cameraInfo != null) {
                msgResult.setResult(true);
                msgResult.setData(cameraInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="刷新")
    @PostMapping("refresh/{id}")
    public MessageResult<CameraInfo> refresh(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<CameraInfo> msgResult = new MessageResult<>();

        try {
            CameraInfo cameraInfo = cameraInfoService.get(id);

            updatePicUrl(cameraInfo);

            cameraInfo.setUpdateBy(subject);
            cameraInfo.setUpdateTime(new Date());

            int affectCount = cameraInfoService.update(cameraInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(cameraInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="更新")
    @PostMapping("update")
    public MessageResult<CameraInfo> update(@RequestBody CameraInfo cameraInfo,@RequestAttribute String subject){
        MessageResult<CameraInfo> msgResult = new MessageResult<>();

        try {
            cameraInfo.setUpdateBy(subject);
            cameraInfo.setUpdateTime(new Date());
            
            int affectCount = cameraInfoService.update(cameraInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(cameraInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

	@ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            CameraInfo cameraInfo = cameraInfoService.get(id);
            cameraInfo.setDelFlag(true);
            cameraInfo.setUpdateBy(subject);
            cameraInfo.setUpdateTime(new Date());

            int affectCount = cameraInfoService.update(cameraInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                CameraInfo cameraInfo = cameraInfoService.get(id);
                cameraInfo.setDelFlag(true);
                cameraInfo.setUpdateBy(subject);
                cameraInfo.setUpdateTime(new Date());

                affectCount += cameraInfoService.update(cameraInfo);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String platform,
            String deviceSerial,
            String deviceName,
            String status,
            String companyId,
            String roomAddress,
            String classify,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestParam(value="field",defaultValue="a.create_time") String field,
            @RequestParam(value="direction",defaultValue="asc") String direction,
            @RequestAttribute String subject){
        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort(field,direction));

        if (StringUtils.isNotEmpty(deviceSerial)) {
            searchParams.put("deviceSerial","%" + deviceSerial + "%");
        }

        if (StringUtils.isNotEmpty(deviceName)) {
            searchParams.put("deviceName","%" + deviceName + "%");
        }

        if (StringUtils.isNotEmpty(roomAddress)) {
            searchParams.put("roomAddress","%" + roomAddress + "%");
        }

        if (StringUtils.isNotEmpty(status)) {
            searchParams.put("status", status);
        }

        if (StringUtils.isNotEmpty(companyId)) {
            searchParams.put("companyId",companyId);
        }

        if (StringUtils.isNotEmpty(platform)) {
            searchParams.put("platform",platform);
        }

        if (StringUtils.isNotEmpty(classify)) {
            searchParams.put("classify",classify);
        }

        User user = userService.get(subject);

        if(!userService.hasRole(user.getId(),"SYSADMIN")) {
            //非系统管理员只能查看自己单位下的设备
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
            searchParams.put("companyCode", companyInfo.getCode() + "%");
        }

        Map<String, DataDictionary> platformMap = dataDictionaryService.findMapByCatalogName("摄像头云平台");

        Page<CameraInfo> page = cameraInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);

        for (CameraInfo cameraInfo : page) {
            if (platformMap.containsKey(cameraInfo.getPlatform())){
                cameraInfo.setPlatformN(platformMap.get(cameraInfo.getPlatform()).getName());
            }
        }

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

//    @GetMapping("bindPersonList/{id}")
//    @ApiOperation(value="摄像头关联人员列表")
//    public MessageResult<List> bindClassList(@PathVariable(value = "id") String id){
//        MessageResult<List> messageResult = new MessageResult<>();
//
//        try {
//            List<CameraPersonDTO> dtoList = new ArrayList<>();
//
//            CameraInfo cameraInfo = cameraInfoService.get(id);
//            CompanyInfo school = companyInfoService.get(cameraInfo.getCompanyId());
//
//            List<CompanyInfo> classList = companyInfoService.findByCompanyCodeAndType(school.getCode() + "%","3");
//
//            for (CompanyInfo classInfo : classList) {
//                CameraPersonDTO dto = new CameraPersonDTO();
//
//                dto.setCameraId(cameraInfo.getId());
//                dto.setPersonId(classInfo.getId());
//                dto.setPersonName(classInfo.getName());
//
//                boolean enabled = cameraCompanyService.existByKey(dto.getCameraId(),dto.getClassId());
//
//                dto.setEnabled(enabled);
//
//                dtoList.add(dto);
//            }
//
//            //倒序
//            dtoList.sort(Comparator.comparing(CameraClassDTO::getEnabled));
//            Collections.reverse(dtoList);
//
//            messageResult.setData(dtoList);
//            messageResult.setResult(true);
//        }
//        catch (Exception ex){
//            logger.error(ex.getMessage(),ex);
//
//            messageResult.setResult(false);
//            messageResult.setMessage(ex.getMessage());
//        }
//
//        return messageResult;
//    }

//    @PostMapping("bindClass")
//    @ApiOperation(value="绑定人员")
//    public MessageResult<String> bindClass(@RequestBody CameraPersonDTO dto,@RequestAttribute String subject){
//        MessageResult<String> messageResult = new MessageResult<>();
//
//        try {
//            boolean exist = cameraCompanyService.existByKey(dto.getCameraId(),dto.getClassId());
//
//            //绑定新班级
//            if (!exist && dto.getEnabled()){
//                CameraCompany cameraCompany = new CameraCompany();
//                cameraCompany.setId(UUID.randomUUID().toString());
//                cameraCompany.setCameraId(dto.getCameraId());
//                cameraCompany.setCompanyId(dto.getPersonId());
//                cameraCompany.setCreateBy(subject);
//                cameraCompany.setCreateTime(new Date());
//                cameraCompany.setDelFlag(false);
//
//                cameraCompanyService.insert(cameraCompany);
//            }
//            else if(exist && !dto.getEnabled()){
//                cameraCompanyService.deleteByKey(dto.getCameraId(),dto.getClassId());
//            }
//
//            messageResult.setResult(true);
//        }
//        catch (Exception ex){
//            logger.error(ex.getMessage(),ex);
//
//            messageResult.setResult(false);
//            messageResult.setMessage(ex.getMessage());
//        }
//
//        return messageResult;
//    }
}
