package com.zcxk.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zcxk.dao.CameraManageMapper;
import com.zcxk.dao.SceneMapper;
import com.zcxk.dto.CameraDto;
import com.zcxk.entity.CameraManage;
import com.zcxk.entity.SceneEntity;
import com.zcxk.model.LoginUser;
import com.zcxk.model.ProgramItem;
import com.zcxk.service.CameraManageService;
import com.zcxk.util.OrgInfoUtil;
import com.zcxk.util.RedisUtil;
import com.zcxk.util.UserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;

import static com.google.common.collect.Lists.newArrayList;

/**
 * (CameraManage表)服务实现类
 *
 * @author makejava
 * @since 2020-11-26 10:25:14
 */
@Service("cameraManageService")
public class CameraManageServiceImpl implements CameraManageService {
    @Autowired
    private CameraManageMapper cameraManageMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrgInfoUtil util;
    @Autowired
    private SceneMapper sceneMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public CameraManage selectById(Integer id) {
        CameraManage cameraManage = this.cameraManageMapper.selectById(id);

        String baseUrl="https://open.ys7.com/ezopen/h5/iframe_se?url=ezopen://open.ys7.com/";
        if(cameraManage==null){
            return null;
        }
        String token= getToken(cameraManage.getAppkey(),cameraManage.getScrert());
        cameraManage.setToken(token);
        if(cameraManage.getChannelNo()==null){
            cameraManage.setChannelNo(1);
        }
        if(token!=null){
            String play=".live";
            String replay=".rec";
            baseUrl=baseUrl+cameraManage.getDeviceSerial()+
                    "/"+cameraManage.getChannelNo()+"${type}&autoplay=0&audio=1&templete=2&accessToken="
                    +token;

            cameraManage.setPalyUrl(baseUrl.replace("${type}",play));
            cameraManage.setReplayUrl(baseUrl.replace("${type}",replay));
        }
        Map<String, String> allOrgName = util.getAllOrgName();
        cameraManage.setDepartName(allOrgName.get(String.valueOf(cameraManage.getDeptOrgId())));
        cameraManage.setCompanyName(allOrgName.get(String.valueOf(cameraManage.getCompanyOrgId())));

        return cameraManage;
    }


    /**
     * 查询所有
     *
     * @return 实例对象的集合
     */
    @Override
    public List<CameraManage> selectAll() {
        return this.cameraManageMapper.selectAll();
    }

    /**
     * 根据条件查询
     *
     * @return 实例对象的集合
     */
    @Override
    public List<CameraManage> selectList(CameraManage cameraManage) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        cameraManage.setTenantId(currentUser.getTenantId());
        cameraManage.setProgramItems(currentUser.getProgramItemList());
        cameraManage.setPermissonType(currentUser.getPermissonType());
        return this.cameraManageMapper.selectList(cameraManage);
    }


    /**
     * 新增数据
     *
     * @param cameraManage 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(CameraManage cameraManage) {

        LoginUser currentUser = UserUtil.getCurrentUser();
        cameraManage.setTenantId(currentUser.getTenantId());
        if(!isOrgCorrect(cameraManage.getCompanyOrgId(),cameraManage.getDeptOrgId(),
                currentUser.getProgramItemList())){
            return 2;
        }
        cameraManage.setDateCreate(new Date());
        cameraManage.setCreateBy(currentUser.getUsername());
        updateCameraName(cameraManage);

            this.cameraManageMapper.insert(cameraManage);





        return 1;
    }
    private boolean isOrgCorrect(Integer companyId, Integer departmentId, List<ProgramItem>items){
        boolean result=false;
        Set<Integer>companyIds=new HashSet<>();
        Set<Integer>departmentIds=new HashSet<>();
        items.forEach(item->{
            companyIds.add(item.getOrgCompanyId());
            departmentIds.add(item.getOrgDeparmtmentId());
        });
        if(departmentId!=null){
            if(companyIds.contains(companyId)&&departmentIds.contains(departmentId)){
                result=true;
            }
        }else{
            if(companyIds.contains(companyId)){
                result=true;
            }
        }


        return result;
    }
    private int updateCameraName(CameraManage cameraManage){
        int result=1;
        String token = getToken(cameraManage.getAppkey(), cameraManage.getScrert());
        if(token==null){
            result=3;
        }
        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, Object> params= new LinkedMultiValueMap<>();
        params.add("accessToken",token);
        params.add("deviceSerial",cameraManage.getDeviceSerial());
        params.add("name",cameraManage.getName());

        params.add("channelNo",cameraManage.getChannelNo());
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        String url="https://open.ys7.com/api/lapp/camera/name/update";
        //String result = restTemplate.postForObject(url, "accessToken=at.d01poowjc4bwrwpyc3czs53nbc8m7v0a-39jm695wjp-14xe4rj-xbsmxw8en&deviceSerial=E40848837&deviceName=888&name=888&channelNo=1", String.class);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
        JSONObject info = JSONObject.parseObject(stringResponseEntity.getBody());
        Integer code = info.getInteger("code");
        if(code!=200){
            result=4;
        }
        return result;

    }
    private String getToken (String appKey,String secret){
        String token = redisUtil.get(appKey);
        if(token==null){
            HttpHeaders headers = new HttpHeaders();
//  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//  封装参数，千万不要替换为Map与HashMap，否则参数无法传递
            MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
//  也支持中文
            params.add("appKey",appKey);
            params.add("appSecret",secret);
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
//  执行HTTP请求
            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity("https://open.ys7.com/api/lapp/token/get", requestEntity, String.class);
            JSONObject info = JSONObject.parseObject(stringResponseEntity.getBody());
            Integer code = info.getInteger("code");
            JSONObject data = info.getJSONObject("data");
            if(code==200){
                token=data.getString("accessToken");
                long expireTime=data.getLong("expireTime");
                redisUtil.set(appKey,token);
                redisUtil.set(appKey,token);
                expireTime=expireTime-new Date().getTime();
                expireTime=expireTime/1000-60;
                redisUtil.setExpire(appKey,expireTime);
            }

        }

        return token;
    }

    /**
     * 批量新增
     *
     * @param cameraManages 实例对象的集合
     * @return 生效的条数
     */
    @Override
    public int batchInsert(List<CameraManage> cameraManages) {
        return this.cameraManageMapper.batchInsert(cameraManages);
    }

    /**
     * 修改数据
     *
     * @param cameraManage 实例对象
     * @return 实例对象
     */
    @Override
    public int update(CameraManage cameraManage) {

        LoginUser currentUser = UserUtil.getCurrentUser();
        if(!isOrgCorrect(cameraManage.getCompanyOrgId(),cameraManage.getDeptOrgId(),
                currentUser.getProgramItemList())){
            return 2;
        }
        cameraManage.setDateUpdate(new Date());
        cameraManage.setUpdateBy(currentUser.getUsername());

        updateCameraName(cameraManage);

            this.cameraManageMapper.update(cameraManage);

        return 1;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public int deleteById(Integer id) {
        return this.cameraManageMapper.deleteById(id);
    }

    /**
     * 查询总数据数
     *
     * @return 数据总数
     */
    @Override
    public int count() {
        return this.cameraManageMapper.count();
    }

    /**
     * 分页查询
     *
     * @return 对象列表
     */
    @Override
    public IPage<CameraManage> selectPage(CameraManage cameraManage, IPage<CameraManage> page) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        cameraManage.setTenantId(currentUser.getTenantId());
        cameraManage.setProgramItems(currentUser.getProgramItemList());
        cameraManage.setPermissonType(currentUser.getPermissonType());
        Map<String, String> allOrgName = util.getAllOrgName();
        IPage<CameraManage> cameraManageIPage = this.cameraManageMapper.selectPage(page, cameraManage);
        cameraManageIPage.getRecords().forEach(record->{
            record.setDepartName(allOrgName.get(String.valueOf(record.getDeptOrgId())));
            record.setCompanyName(allOrgName.get(String.valueOf(record.getCompanyOrgId())));
        });
        return cameraManageIPage;
    }


    @Override
    public IPage<CameraManage> appSelectPage(CameraManage cameraManage, IPage<CameraManage> page){
        LoginUser currentUser = UserUtil.getCurrentUser();
        cameraManage.setTenantId(currentUser.getTenantId());
        cameraManage.setProgramItems(currentUser.getProgramItemList());
        cameraManage.setPermissonType(currentUser.getPermissonType());
        Map<String, String> allOrgName = util.getAllOrgName();
        IPage<CameraManage> cameraManageIPage = this.cameraManageMapper.appSelectPage(page, cameraManage);
        cameraManageIPage.getRecords().forEach(record->{
            record.setDepartName(allOrgName.get(String.valueOf(record.getDeptOrgId())));
            record.setCompanyName(allOrgName.get(String.valueOf(record.getCompanyOrgId())));
        });
        return cameraManageIPage;
    }

    @Override
    public int deleteAll(List<Integer> ids) {
        cameraManageMapper.deleteAll(ids);
        return 0;
    }

    @Override
    public List<CameraDto> getCameraTree(Long typeId) {

        LoginUser currentUser = UserUtil.getCurrentUser();
        SceneEntity searchSceneEntity = new SceneEntity();
        searchSceneEntity.setTenantId(currentUser.getTenantId());
        searchSceneEntity.setProgramItems(currentUser.getProgramItemList());
        searchSceneEntity.setUserType(currentUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        searchSceneEntity.setPermissonType(currentUser.getPermissonType());
        searchSceneEntity.setParentSceneId(0l);
        List<SceneEntity> sceneEntities = sceneMapper.findList(searchSceneEntity);
        CameraManage searchCameraManage=new CameraManage();
        searchCameraManage.setStatus(1);
        searchCameraManage.setTenantId(currentUser.getTenantId());
        List<CameraManage> cameraManages = cameraManageMapper.selectAllCameras(searchCameraManage);
        List<CameraDto>cameraDtos=new ArrayList<>();
        sceneEntities.forEach(sceneEntity -> {
                CameraDto cameraDto=new CameraDto();
                cameraDto.setId(sceneEntity.getId());
                cameraDto.setKey(sceneEntity.getId()+"_senceType");
                cameraDto.setParentKey(sceneEntity.getParentSceneId()+"_senceType");
                cameraDto.setSceneTypeName(sceneEntity.getSceneTypeName());
                //cameraDto.setPid(sceneEntity.getParentSceneId());
                cameraDto.setSceneName(sceneEntity.getSceneName());
                cameraDtos.add(cameraDto);
        });
        cameraManages.forEach(cameraManage ->{
            CameraDto cameraDto=new CameraDto();

            cameraDto.setId(Long.valueOf(cameraManage.getId()) );
            cameraDto.setKey(cameraManage.getId()+"_cameraType");
            String[] parentIds = cameraManage.getParentSceneIds().split(",");
            if(parentIds.length>1){
                cameraDto.setParentKey(parentIds[1]+"_senceType");
            }
            cameraDto.setSceneName(cameraManage.getName());
            cameraDtos.add(cameraDto);
        } );
        List<CameraDto>cameraTree=getCameraTree(cameraDtos,0+"_senceType",1);
        return cameraTree;
    }

    @Override
    public List<CameraManage> getAllCameras(Integer id) {
         ;
        return cameraManageMapper.getAllCameras(id);
    }

    public  List<CameraDto> getCameraTree(List<CameraDto> list, String key, Integer leve) {
        List<CameraDto> temList = newArrayList();
        if (list != null) {
            for (CameraDto cameraDto : list) {
                if (key.equals(cameraDto.getParentKey())) {
                    List<CameraDto> chidren = getCameraTree(list, cameraDto.getKey(), ++leve);
                    CameraDto temMeanu = new CameraDto();
                    BeanUtils.copyProperties(cameraDto, temMeanu);
                    temMeanu.setChildren(chidren);
                    temList.add(temMeanu);
                    leve--;
                }
            }
        }
        if (temList.size() > 0) {
            return temList;
        } else {
            return null;
        }
    }

}