package com.platform.controller;

import com.alibaba.fastjson.JSONObject;
import com.platform.MysqlTest;
import com.platform.entity.BrandEntity;
import com.platform.entity.Result;
import com.platform.entity.SysUserBrand;
import com.platform.service.BrandService;
import com.platform.service.custom.MySysUserBrandService;
import com.platform.service.impl.ZhiHouseService;
import com.platform.utils.PageUtilsPlus;
import com.platform.utils.RRException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统用户
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2016年10月31日 上午10:40:10
 */
@RestController
@RequestMapping("/sys/user")
@Slf4j
public class SysUserController extends AbstractController {

    @Autowired
    private MySysUserBrandService mySysUserBrandService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private ZhiHouseService zhiHouseService;

    /**
     * 店铺绑定的用户列表
     */
    @PostMapping("/bindList")
    public Result userBindList( @RequestHeader String token ,@RequestBody JSONObject param) {
        // 查询用户信息
        if(param.get("brandId") == null){
            throw new RRException("缺少必要参数");
        }
        BrandEntity brandEntity = brandService.queryObject(param.getInteger("brandId"));
        if(brandEntity == null){
            throw new RRException("直播间为空");
        }
        if(brandEntity.getCreateUserDeptId() == null){
            throw new RRException("直播归属公司为空");
        }
        JSONObject result = zhiHouseService.getSysUserListPageByDeptIdsAndUserName(brandEntity.getCreateUserDeptId(),
                param.getLong("page"),param.getLong("limit"), param.getString("username"),token);
        List<Object> users = result.getJSONArray("list");
        if(!ObjectUtils.isEmpty(users)){
            users = users.stream().map(object -> {
                JSONObject user = JSONObject.parseObject(JSONObject.toJSONString(object));
                // 查找直播间数据
                SysUserBrand userBrand = mySysUserBrandService.getUserBrandById(user.getLong("id"), param.getInteger("brandId"));
                if (!ObjectUtils.isEmpty(userBrand)){
                    user.put("isBind", 1);
                    user.put("canShow", userBrand.getCanShow());
                }
                return user;
            }).collect(Collectors.toList());
        }
        // 处理场景数据
        PageUtilsPlus pageResult = PageUtilsPlus.page(users, result.getLong("totalCount"), param.getLong("limit"), param.getLong("page"));
        return Result.success(pageResult);
    }
}
