/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.dm.user.rest;

import cn.hutool.core.collection.CollectionUtil;
import me.zhengjie.annotation.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.dm.user.domain.DmUser;
import me.zhengjie.modules.dm.user.service.DmUserService;
import me.zhengjie.modules.dm.user.service.dto.DmUserQueryCriteria;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.service.DataService;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @author shiguangji
* @date 2021-03-09
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "IOT会议系统-用户管理")
@RequestMapping("/api/dmUser")
public class DmUserController {

    private final DmUserService dmUserService;
    private final UserService userService;
    private final DataService dataService;
    private final DeptService deptService;

    private static final String ENTITY_NAME = "dmUser";


    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('dmUser:list')")
    public void download(HttpServletResponse response, DmUserQueryCriteria criteria) throws IOException {
        dmUserService.download(dmUserService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询会议用户")
    @ApiOperation("查询会议用户")
    @PreAuthorize("@el.check('dmUser:list')")
    public ResponseEntity<Object> query(DmUserQueryCriteria criteria, Pageable pageable){
        if (!ObjectUtils.isEmpty(criteria.getDeptId())) {
            criteria.getDeptIds().add(criteria.getDeptId());
            criteria.getDeptIds().addAll(deptService.getDeptChildren(deptService.findByPid(criteria.getDeptId())));
        }
        // 数据权限
        List<String> dataScopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUsername()));
        // criteria.getDeptIds() 不为空并且数据权限不为空则取交集
        if (!CollectionUtils.isEmpty(criteria.getDeptIds()) && !CollectionUtils.isEmpty(dataScopes)){
            // 取交集
            criteria.getDeptIds().retainAll(dataScopes);
            if(!CollectionUtil.isEmpty(criteria.getDeptIds())){
                return new ResponseEntity<>(dmUserService.queryAll(criteria,pageable),HttpStatus.OK);
            }
        } else {
            // 否则取并集
            criteria.getDeptIds().addAll(dataScopes);
            return new ResponseEntity<>(dmUserService.queryAll(criteria,pageable),HttpStatus.OK);
        }
        return new ResponseEntity<>(dmUserService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增会议用户")
    @ApiOperation("新增会议用户")
    @PreAuthorize("@el.check('dmUser:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody DmUser resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        return new ResponseEntity<>(dmUserService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改会议用户")
    @ApiOperation("修改会议用户")
    @PreAuthorize("@el.check('dmUser:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody DmUser resources) throws Exception{
        dmUserService.update(resources);
        //同步关联的账号权限
        List<User> users = userService.findByDmUserId(resources.getId(),null);
        if(users != null && users.size() > 0){
           User user = users.get(0);
           userService.update(user);
        }
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除会议用户")
    @ApiOperation("删除会议用户")
    @PreAuthorize("@el.check('dmUser:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody String[] ids) {
        //判断是否关联账号
        for(String id : ids){
            List<User> users = userService.findByDmUserId(id,null);
            if(users != null && users.size() > 0){
                throw new BadRequestException("删除的用户存在关联的账号,请先解绑账号");
            }
        }
        dmUserService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping(value="/findNotBindUser")
    @Log("查询未绑定账号的会议用户")
    @ApiOperation("查询未绑定账号的会议用户")
    public ResponseEntity<Object> findNotBindUser(Long userId){
        return new ResponseEntity<>(dmUserService.findNotBindUser(userId),HttpStatus.OK);
    }
}