package com.platform.api;

import com.alibaba.fastjson.JSONObject;
import com.platform.annotation.IgnoreAuth;
import com.platform.entity.*;
import com.platform.interceptor.AuthorizationInterceptor;
import com.platform.service.ApiBrandService;
import com.platform.service.ApiRecommendService;
import com.platform.service.ApiUserService;
import com.platform.service.custom.MyApiTmBrandTypeService;
import com.platform.service.custom.MySysUserBrandService;
import com.platform.service.impl.ZhiHouseService;
import com.platform.util.ApiBaseAction;
import com.platform.util.ApiPageUtils;
import com.platform.utils.Query;
import com.platform.vos.RequestScene;
import com.platform.vos.TbUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-08-11 08:32<br>
 * @gitee https://gitee.com/fuyang_lipengjun/platform
 * 描述: ApiIndexController <br>
 */
@Api(tags = "品牌")
@RestController
@RequestMapping("/api/brand")
public class ApiBrandController extends ApiBaseAction {

    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ApiBrandService brandService;

    @Autowired
    private MyApiTmBrandTypeService myApiTmBrandTypeService;

    @Autowired
    private MySysUserBrandService mySysUserBrandService;


    @Autowired
    private ZhiHouseService zhiHouseService;

    /**
     * 分页获取品牌
     *
     * type :-1:所有；0：新房；1:二手房；2:公寓；3:民宿；4：社区
     * 11:新上房源；12:热门房源;13:热门企业；
     * 21:商家列表；
     * 31：VR场景；32：VR直播间
     *
     1、新上房源，场景创建时间倒序
     2、热门房源，浏览量前三 -》场景创建时间倒序的房源
     3、热门企业，获取场景数前三的企业，点击后，跳转至对应企业的最多点击数量的界面
     4、为您推荐，根据 场景的排序  + ID倒序  进行输出。
     */
    @ApiOperation(value = "分页获取品牌")
    @IgnoreAuth
    @PostMapping("list")
    public Object list(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(value = "limit",defaultValue = "10")Integer size,
                       @RequestParam(defaultValue = "-1")Integer type,String address,String name) {

        Long userId = null;
        if (type == 31 || type == 32) {
            userId = getUserId();
        }
        ApiPageUtils result = null;
        //查询列表数据
        Map params = new HashMap();
        params.put("page", page);
        params.put("limit", size);
        if(!ObjectUtils.isEmpty(address)){
            params.put("address", address);
        }
        params.put("sidx", "");
        params.put("order", "");
        switch (type){
            case -1:
                params.put("livestreamStatus", "1");
                if(!StringUtils.isEmpty(name)){
                    params.put("name", name);
                }
                break;
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
                params.put("livestreamStatus", "1");
                params.put("type", type);
                if(!StringUtils.isEmpty(name)){
                    params.put("name", name);
                }
                break;
            case 11:
            case 12:
            case 13:
                List<BrandVo> list = zhiHouseService.queryRecomendsByType(type).parallelStream().map(entity->{
                    BrandVo vo = new BrandVo();
                    vo.setName(entity.getString("title"));
                    vo.setId(entity.getInteger("connectId"));
                    vo.setAppListPicUrl(entity.getString("image"));
                    return vo;
                }).collect(Collectors.toList());
                return toResponsSuccess(new ApiPageUtils(list, 3, 3, 1));
            case 21:
                userId = null;
                params.put("isShow", 1);
            case 31:
            case 32:
                if(!ObjectUtils.isEmpty(userId)){
                    params.put("userId", userId);
                }
                if(!StringUtils.isEmpty(name)){
                    params.put("name", name);
                }
                break;
        }
        //  处理直播间数据
        if (params.containsKey("livestreamStatus") || type == 32) {
            params.put("fields", "nideshop_brand.id, nideshop_brand.name,nideshop_brand.app_list_pic_url, nideshop_brand.type," +
                    " nideshop_brand.address");
            Query query = new Query(params);
            List<BrandVo> brandEntityList = brandService.queryList(query);
            // 格式化地址
            brandEntityList.parallelStream().filter(brand->!ObjectUtils.isEmpty(brand.getAddress()))
                    .forEach(brand-> brand.setAddress(brand.getAddress().trim()
                            .substring(brand.getAddress().indexOf(",")+1).replaceAll(",| "," | ")));
            int total = brandService.queryTotal(query);
            result = new ApiPageUtils(brandEntityList, total, query.getLimit(), query.getPage());
        }else{
            RequestScene requestScene = new RequestScene();
            if(params.containsKey("isShow")){
                requestScene.setIsShow(1);
            }
           if(params.containsKey("userId")){
                requestScene.setUserId(getUserId());
            }else{
               requestScene.setUserId(-1L);
           }

            if(params.containsKey("name"))
                requestScene.setSceneName(name);{
            }
            requestScene.setPage(Long.valueOf(page));
            requestScene.setLimit(Long.valueOf(size));
            requestScene.setToken(request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY));
            JSONObject mySceneJsonData = zhiHouseService.getSceneFromZhiHouse(requestScene);
            logger.info("token：{}",requestScene.getToken());
            logger.info("请求结果：{}",mySceneJsonData.toJSONString());
            List<Object> mySceneList = mySceneJsonData.getJSONArray("list");
            // 处理场景数据
            result = new ApiPageUtils(mySceneList, mySceneJsonData.getInteger("totalCount"), size, page);
        }
        return toResponsSuccess(result);

    }

    /**
     * 品牌详情
     */
    @ApiOperation(value = "品牌详情")
    @PostMapping("detail")
    public Object detail(@RequestParam Integer id,@RequestParam(required = false) Integer type) {
        Map<String, Object> resultObj = new HashMap();
        BrandVo entity = null;
        if (!(ObjectUtils.isEmpty(type) || type == 21 || type == 31)) {
            //查询列表数据
            entity = brandService.queryObject(id);
            if(ObjectUtils.isEmpty(entity)){
                resultObj.put("brand", entity);
                return toResponsSuccess(resultObj);
            }
            entity.setSceneUrl(entity.getLiveRoomUrl());
            // 获取场景数据
            JSONObject sceneRes = zhiHouseService.queryBySceneNum(entity.getSceneNum(),request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY));
            if(!ObjectUtils.isEmpty(sceneRes)){
                entity.setSceneName(sceneRes.getString("sceneName"));
            }
            int canshow = 0;
            //检查是否有带看权限，并更新
            SysUserBrand sysUserBrand = mySysUserBrandService.getUserBrandById(getUserId() , entity.getId());
            if(null != sysUserBrand){
                canshow = null != sysUserBrand.getCanShow() ? sysUserBrand.getCanShow() : 0;
            }
            entity.setCanShow(canshow);
        } else {
            RequestScene requestScene = new RequestScene();
            requestScene.setSceneId(Long.valueOf(id));
            requestScene.setUserId(-1L);
            requestScene.setToken(request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY));
            JSONObject mySceneJsonData = zhiHouseService.getSceneFromZhiHouse(requestScene);
            List<Object> mySceneList = mySceneJsonData.getJSONArray("list");
            entity = new BrandVo();
            if(!ObjectUtils.isEmpty(mySceneList)){
                JSONObject sceneRes = JSONObject.parseObject(JSONObject.toJSONString(mySceneList.get(0)));
                entity.setSceneUrl(sceneRes.getString("webSite"));
                entity.setSceneName(sceneRes.getString("sceneName"));
                entity.setAppListPicUrl(sceneRes.getString("appListPicUrl"));
                entity.setSceneNum(sceneRes.getString("num"));
            }
        }
        resultObj.put("brand", entity);
        return toResponsSuccess(resultObj);
    }


    /**
     * 增加访问次数
     */
    @ApiOperation(value = "增加访问次数")
    @IgnoreAuth
    @GetMapping("increaseViewCount")
    public Object increaseViewCount(@RequestParam Integer brandId,@RequestParam(required = false) Integer type) {
        if(!(ObjectUtils.isEmpty(type) || type == 21 || type == 31)) {
            return toResponsSuccess(brandService.increaseViewCount(brandId+""));
        }
        return toResponsSuccess(zhiHouseService.increaseViewCount(brandId));
    }

    /**
     * 品牌详情
     */
    @ApiOperation(value = "通过场景码获取品牌详情")
    @IgnoreAuth
    @PostMapping("getByScene")
    public Object getDetailBySceneNum(@RequestParam String sceneNum) {
        if(StringUtils.isEmpty(sceneNum)){
            return Result.failure("场景码不能为空");
        }
        Map<String, Object> resultObj = new HashMap();
        //查询列表数据
        BrandVo entity = brandService.queryByScene(sceneNum);

        Long userId = getUserId();
        if(null != userId && null != entity){
            SysUserBrand sysUserBrand = mySysUserBrandService.getUserBrandById(userId , entity.getId());
            if(null != sysUserBrand){
                int canshow = null != sysUserBrand.getCanShow() ? sysUserBrand.getCanShow() : 0;
                entity.setCanShow(canshow);
            }else{
                entity.setCanShow(0);
            }
        }else{
            entity.setCanShow(0);
        }
        resultObj.put("brand", entity);
        return toResponsSuccess(resultObj);
    }

    /**
     * 品牌详情
     */
    @ApiOperation(value = "获取品牌的类型列表")
    @IgnoreAuth
    @PostMapping("brandTypeList")
    public Object brandTypeList() {
        List<ApiTmBrandTypeVo> brandTypeList = myApiTmBrandTypeService.getAllList();
        List<Map<String , Object>> resultList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(brandTypeList)){
            brandTypeList.forEach(brandType -> {
                if(null != brandType){
                    Map<String , Object> mp = new HashMap<>();
                    mp.put(brandType.getName() , brandType.getBrandType());
                    resultList.add(mp);
                }
            });

        }
        return toResponsSuccess(resultList);
    }
}
