package com.platform.api;

import com.github.pagehelper.PageInfo;
import com.platform.annotation.IgnoreAuth;
import com.platform.entity.*;
import com.platform.service.ApiBrandService;
import com.platform.service.ApiRecommendService;
import com.platform.service.ApiSceneService;
import com.platform.service.ApiUserService;
import com.platform.service.custom.MyApiTmBrandTypeService;
import com.platform.service.custom.MySysUserBrandService;
import com.platform.service.impl.SysUserServiceImpl;
import com.platform.util.ApiBaseAction;
import com.platform.util.ApiPageUtils;
import com.platform.utils.Query;
import com.platform.utils.R;
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 ApiSceneService sceneService;

    @Autowired
    private MyApiTmBrandTypeService myApiTmBrandTypeService;

    @Autowired
    private MySysUserBrandService mySysUserBrandService;

    @Autowired
    private ApiUserService apiUserService;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Autowired
    private ApiRecommendService recommendService;

    /**
     * 分页获取品牌
     *
     * 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(defaultValue = "10")Integer size,
                       @RequestParam(defaultValue = "-1")Integer type,String address,String name) {
        Long userId = null;
        if (type == 31 || type == 32) {
            userId = getUserId();
            if (ObjectUtils.isEmpty(userId)) {
                return toResponsObject(401, "请先登录", "");
            }
            // 获取用户手机号
            UserVo userVo = apiUserService.queryObject(userId);
            String phone = userVo.getMobile();
            if(ObjectUtils.isEmpty(phone)){
                logger.error("用户未绑定手机号：{}",userId);
                return toResponsSuccess(new ApiPageUtils(new PageInfo(new ArrayList<BrandVo>())));
            }
            // 根据手机号获取系统用户ID
            SysUserEntity userEntity = sysUserService.queryByUserMobile(phone);
            if(ObjectUtils.isEmpty(userEntity)){
                logger.error("获取系统用户失败：{}",phone);
                return toResponsSuccess(new ApiPageUtils(new PageInfo(new ArrayList<BrandVo>())));
            }
            userId = userEntity.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:
                params.put("type",type);
                Query query = new Query(params);
                List<BrandVo> list = recommendService.queryList(query).parallelStream().map(entity->{
                    BrandVo vo = new BrandVo();
                    vo.setName(entity.getTitle());
                    vo.setId(entity.getConnectId().intValue());
                    vo.setAppListPicUrl(entity.getImage());
                    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{
            params.put("fields", "id,name,app_list_pic_url,pv_total_num");
            Query query = new Query(params);
            List<BrandVo> brandVos = sceneService.queryList(query);
            int total = sceneService.queryTotal(query);
            // 处理场景数据
            result = new ApiPageUtils(brandVos, total, query.getLimit(), query.getPage());
        }
        return toResponsSuccess(result);

    }

    /**
     * 品牌详情
     */
    @ApiOperation(value = "品牌详情")
    @IgnoreAuth
    @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());
            // 获取场景数据
            BrandVo sceneVo = sceneService.queryByScene(entity.getSceneNum());
            if(!ObjectUtils.isEmpty(sceneVo)){
                entity.setSceneName(sceneVo.getName());
            }
            Long userId = getUserId();
            int canshow = 0;
            UserVo userVo = apiUserService.queryObject(userId);
            if(null != userVo && org.apache.commons.lang.StringUtils.isNotBlank(userVo.getMobile())){
                //检查是否有带看权限，并更新
                SysUserEntity sysUserEntity = sysUserService.queryByUserMobile(userVo.getMobile());
                if(null != sysUserEntity){
                    SysUserBrand sysUserBrand = mySysUserBrandService.getUserBrandById(sysUserEntity.getUserId() , entity.getId());
                    if(null != sysUserBrand){
                        canshow = null != sysUserBrand.getCanShow() ? sysUserBrand.getCanShow() : 0;
                    }
                }

            }
            entity.setCanShow(canshow);
        } else {
            entity = sceneService.queryObject(id);
        }
        resultObj.put("brand", entity);
        return toResponsSuccess(resultObj);
    }


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

    /**
     * 品牌详情
     */
    @ApiOperation(value = "通过场景码获取品牌详情")
    @IgnoreAuth
    @PostMapping("getByScene")
    public Object getDetailBySceneNum(@RequestParam String sceneNum) {
        if(StringUtils.isEmpty(sceneNum)){
            return R.error("场景码不能为空");
        }
        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);
    }
}
