package com.platform.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.platform.enums.ResultCodeEnum;
import com.platform.exception.CommonBaseException;
import com.platform.vos.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ZhiHouseService {
    private static Logger logger = LoggerFactory.getLogger(ZhiHouseService.class);

    @Value("${scenePath}")
    private String zhiHouseHost;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 登录指房宝
     * @param username
     * @param password
     * @return
     */
    public ResponseEntity<String> login(String username, String password) {
        ZhiHouseUserLoginVo userLoginVo = new ZhiHouseUserLoginVo();
        userLoginVo.setUserName(username);
        userLoginVo.setUserPassword(password);
        userLoginVo.setArea("1234");
        String url = zhiHouseHost + "api/platform/login";
        return restTemplate.postForEntity(url, userLoginVo, String.class);
    }

    public ReturnDTO generateSceneEditToken(String token, String userName, String sceneNum) {
        if(ObjectUtils.isEmpty(token)){
            throw new CommonBaseException(ResultCodeEnum.D101);
        }
        Map<String, String> param = new HashMap<>();
        param.put("userName",userName);
        param.put("sceneNum",sceneNum);
        String url = zhiHouseHost + "api/platform/generateSceneEditToken";
        HttpHeaders headers = new HttpHeaders();
        headers.add("token", token);
        HttpEntity<Object> formEntity = new HttpEntity<>(param, headers);
        ResponseEntity<ReturnDTO> responseEntity = restTemplate.postForEntity(url,formEntity,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100,"连接失败");
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }

        return responseEntity.getBody();
    }

    /**
     * 获取四维看看场景数据
     * @param username
     * @return
     */
    public ReturnDTO sync4dkkSceneData(String username) {
        Map<String ,Object> params = new HashMap<>(1);
        params.put("phone",username);
        String url = zhiHouseHost + "api/platform/sync4dkkSceneData";
        ResponseEntity<ReturnDTO> responseEntity = restTemplate.postForEntity(url, params, ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100);
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
        return responseEntity.getBody();
    }

    public JSONObject getSceneFromZhiHouse(RequestScene requestScene){
        String url = zhiHouseHost + "scene/list";
        if(org.apache.commons.lang3.StringUtils.isBlank(url )){
            throw new CommonBaseException(ResultCodeEnum.D101 , "入参不全，无法获取四维场景列表");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("token", requestScene.getToken());
        HttpEntity<Object> formEntity = new HttpEntity<>(requestScene, headers);
        ResponseEntity<ReturnDTO> responseEntity = restTemplate.postForEntity(url,formEntity,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100);
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
        //把信息封装为json
        return JSONObject.parseObject(JSONObject.toJSONString(responseEntity.getBody().getMessage()));
    }

    public void bind4dkkUser(String fdkkUser, String fdkkPassword, String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("token", token);
        Map<String ,Object> params = new HashMap<>(1);
        params.put("fdkkUser",fdkkUser);
        params.put("fdkkPassword",fdkkPassword);
        HttpEntity<Object> formEntity = new HttpEntity<>(params, headers);
        String url = null;
        if (ObjectUtils.isEmpty(fdkkUser) || ObjectUtils.isEmpty(fdkkPassword)) {
            url = zhiHouseHost.concat("/user/unBind4dkkUser");
        } else {
            url = zhiHouseHost.concat("/user/bind4dkkUser");
        }
        ResponseEntity<ReturnDTO> responseEntity = restTemplate.postForEntity(url, formEntity, ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100);
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
    }

    public ReturnDTO wcLogin(String appId,String userName,String nickName,String avatar) {
        String url = zhiHouseHost + "wcLogin";
        if(org.apache.commons.lang3.StringUtils.isBlank(appId)){
            throw new CommonBaseException(ResultCodeEnum.D101 , "入参不全");
        }
        Map<String ,Object> params = new HashMap<>(1);
        params.put("appid",appId);
        params.put("userName",userName);
        params.put("nickName",nickName);
        params.put("head",nickName);
        ResponseEntity<ReturnDTO> responseEntity = restTemplate.postForEntity(url,params,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100,"登录失败");
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }

        return responseEntity.getBody();
    }

    public Object increaseViewCount(Integer sceneId) {
        String url = zhiHouseHost + "/api/scene/updateViewCount?sceneId=" + sceneId;
        if(ObjectUtils.isEmpty(sceneId)){
            return 0;
        }
        ResponseEntity<ReturnDTO> responseEntity = restTemplate.getForEntity(url,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100,"登录失败");
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }

        return responseEntity.getBody();
    }

    public JSONObject queryBySceneNum(String sceneNum,String token) {
        RequestScene requestScene = new RequestScene();
        requestScene.setNums("'"+sceneNum+"'");
        requestScene.setUserId(-1L);
        requestScene.setToken(token);
        JSONObject mySceneJsonData = getSceneFromZhiHouse(requestScene);
        List<Object> mySceneList = mySceneJsonData.getJSONArray("list");
        if(CollectionUtils.isEmpty(mySceneList)){
            return null;
        }
        return JSONObject.parseObject(JSONObject.toJSONString(mySceneList.get(0)));
    }

    public Object generateDefaultLiveRoom(String sceneNum,Boolean lived) {
        String url = zhiHouseHost + "scene/generateDefaultLiveRoom";
        logger.info("请求地址：{}",url);
        Map<String ,Object> params = new HashMap<>(1);
        params.put("sceneNum",sceneNum);
        params.put("lived",lived);
        ResponseEntity<ReturnDTO> responseEntity = restTemplate.postForEntity(url,params,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100,"生成直播间失败");
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
        logger.info("返回结果：{}",JSONObject.toJSONString(responseEntity.getBody().getMessage()));
        return responseEntity.getBody().getMessage();
    }


    public List<TbUser> getSysUserListByDeptIds(Long deptId) {
        Map<String, Object> mp = new HashMap<>();
        mp.put("deptId", deptId);
        String url = zhiHouseHost + "api/shop/getUserByDeptId";
        ResponseEntity<ReturnDTO>  responseEntity = restTemplate.postForEntity(url, mp,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100);
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
        List<TbUser> message = JSONArray.parseArray(JSONArray.toJSONString(responseEntity.getBody().getMessage()),TbUser.class);
        return message;
    }

    public TbUser queryByUserMobile(String phone) {
        Map<String, Object> mp = new HashMap<>();
        mp.put("phone", phone);
        String url = zhiHouseHost + "api/shop/queryByUserMobile";
        ResponseEntity<ReturnDTO>  responseEntity = restTemplate.postForEntity(url, mp,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100);
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
        return JSONObject.parseObject(JSONObject.toJSONString(responseEntity.getBody().getMessage()),TbUser.class);
    }

    public TbUser getByUserId(Long userId) {
        Map<String, Object> mp = new HashMap<>();
        mp.put("userId", userId);
        String url = zhiHouseHost + "api/shop/getByUserId";
        ResponseEntity<ReturnDTO>  responseEntity = restTemplate.postForEntity(url, mp,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100);
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
        TbUser tbUser =  JSONObject.parseObject(JSONObject.toJSONString(responseEntity.getBody().getMessage()),TbUser.class);
        return tbUser;
    }

    public List<Long> queryDeptIdListByUserId(Long userId) {
        Map<String, Object> mp = new HashMap<>();
        mp.put("userId", userId);
        String url = zhiHouseHost + "api/shop/queryCompanyIdListByUserId";
        ResponseEntity<ReturnDTO>  responseEntity = restTemplate.postForEntity(url, mp,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100);
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
        List<Long> longs = (List) responseEntity.getBody().getMessage();
        return longs;
    }

    public CurrentUserLoginVo getCurrentUser() {
        Map<String, Object> mp = new HashMap<>();
        String url = zhiHouseHost + "api/shop/getCurrentUser";
        ResponseEntity<ReturnDTO>  responseEntity = restTemplate.postForEntity(url, mp,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100);
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
        CurrentUserLoginVo user = (CurrentUserLoginVo) responseEntity.getBody().getMessage();
        return user;
    }

    public List<String> getAllPerms(Long userId) {
        Map<String, Object> mp = new HashMap<>();
        if(userId!=null){
            mp.put("userId",userId);
        }
        String url = zhiHouseHost + "api/shop/getAllPerms";
        ResponseEntity<ReturnDTO>  responseEntity = restTemplate.postForEntity(url, mp,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100);
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
        List<String> list = (List<String>) responseEntity.getBody().getMessage();
        return list;
    }

    public Collection<JSONObject> queryRecomendsByType(Integer type){
        Map<String, Object> mp = new HashMap<>();
        mp.put("type", type);
        String url = zhiHouseHost + "recommend/selectWxByType";
        ResponseEntity<ReturnDTO>  responseEntity = restTemplate.postForEntity(url, mp,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100);
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
        List<JSONObject> message = JSONArray.parseArray(JSONArray.toJSONString(responseEntity.getBody().getMessage()),JSONObject.class);
        return message;
    }

    public JSONObject getSysUserListPageByDeptIdsAndUserName(Long deptId,Long page,Long limit, String username,String token) {
        Map<String, Object> mp = new HashMap<>();
        mp.put("username", username);
        mp.put("companyId", deptId);
        mp.put("page", page);
        mp.put("limit", limit);
        HttpHeaders headers = new HttpHeaders();
        headers.add("token", token);
        String url = zhiHouseHost + "api/shop/queryAllUserPageByDeptIdAndUserName";
        HttpEntity<Object> formEntity = new HttpEntity<>(mp, headers);
        ResponseEntity<ReturnDTO> responseEntity = restTemplate.postForEntity(url,formEntity,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100);
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
        //把信息封装为json
        return JSONObject.parseObject(JSONObject.toJSONString(responseEntity.getBody().getMessage()));
    }

    public List<String> getBindUserNameList(List<Long> userIds, String token) {

        Map<String, Object> mp = new HashMap<>();
        mp.put("userIds", userIds);
        String url = zhiHouseHost + "api/shop/getBindUserNameList";
        ResponseEntity<ReturnDTO>  responseEntity = restTemplate.postForEntity(url, mp,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100);
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
        //把信息封装为json

        List<String> list = (List<String>) responseEntity.getBody().getMessage();
        return list;
    }

    public JSONObject getCompanyId(Long companyId) {
        if(companyId == null){
            throw new CommonBaseException(ResultCodeEnum.D101 , "入参不全，无法获取四维场景列表");
        }
        String url = zhiHouseHost + "company/getCompony";
        Map<String ,Object> params = new HashMap<>(1);
        params.put("id",companyId);
        ResponseEntity<ReturnDTO> responseEntity = restTemplate.postForEntity(url,params,ReturnDTO.class);
        if(responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new CommonBaseException(ResultCodeEnum.D100);
        }
        if (responseEntity.getBody().getCode() != 200) {
            throw new CommonBaseException(ResultCodeEnum.D100,responseEntity.getBody().getError());
        }
        //把信息封装为json
        return JSONObject.parseObject(JSONObject.toJSONString(responseEntity.getBody().getMessage()));
    }
}
