/*
*  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.dmuser.rest;

import cn.hutool.core.collection.CollectionUtil;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.dmuser.domain.DmUser;
import me.zhengjie.modules.dmuser.domain.Vo.DmUserVo;
import me.zhengjie.modules.dmuser.service.DmUserService;
import me.zhengjie.modules.dmuser.service.dto.DmUserQueryCriteria;
import me.zhengjie.modules.system.domain.Dept;
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.PageUtil;
import me.zhengjie.utils.SecurityUtils;
import org.apache.http.client.ClientProtocolException;
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 AndyCheung
* @date 2021-09-30
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "api/dmuser管理")
@RequestMapping("/api/dmUser")
public class DmUserController {

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

    @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("查询api/dmuser")
    @ApiOperation("查询api/dmuser")
    @PreAuthorize("@el.check('dmUser:list')")
    public ResponseEntity<Object> query(DmUserQueryCriteria criteria, Pageable pageable){
        criteria.setEnabled("1");
       // return new ResponseEntity<>(dmUserService.queryAll(criteria,pageable),HttpStatus.OK);
        if (!ObjectUtils.isEmpty(criteria.getDeptId())) {
            criteria.getDeptIds().add(criteria.getDeptId());
            // 先查找是否存在子节点
            List<Dept> data = deptService.findByPid(criteria.getDeptId());
            // 然后把子节点的ID都加入到集合中
            criteria.getDeptIds().addAll(deptService.getDeptChildren(data));
        }
        // 数据权限
        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<>(PageUtil.toPage(null,0),HttpStatus.OK);
    }

    @GetMapping(value = "/homePageYktUser")
    @Log("首页一卡通用户")
    @ApiOperation("首页一卡通用户")
    public ResponseEntity<Object> homePageYktUser(){
        return new ResponseEntity<>(dmUserService.homePageYktUser(),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增api/dmuser")
    @ApiOperation("新增api/dmuser")
    @PreAuthorize("@el.check('dmUser:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody DmUser resources){
        return new ResponseEntity<>(dmUserService.create(resources),HttpStatus.CREATED);
    }

    @PostMapping(value = "/createUserDevice")
    @Log("新增用户设备")
    @ApiOperation("新增用户设备")
    public ResponseEntity<Object> createUserDevice(@Validated @RequestBody DmUserVo resources){
        dmUserService.createUserDevice(resources);
        // 添加完成之后  进行同步数据
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改api/dmuser")
    @ApiOperation("修改api/dmuser")
    public ResponseEntity<Object> update(@Validated @RequestBody DmUser resources) throws Exception {
        dmUserService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除api/dmuser")
    @ApiOperation("删除api/dmuser")
    @PreAuthorize("@el.check('dmUser:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody String[] ids) {
        dmUserService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

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

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

    @GetMapping(value="/findUser")
    @Log("查询未绑定卡号的用户")
    @ApiOperation("查询未绑定卡号的用户")
    public ResponseEntity<Object> findUser(DmUserQueryCriteria dmUserQueryCriteria){
        return new ResponseEntity<>(dmUserService.findUser(),HttpStatus.OK);
    }

    @GetMapping(value="/findByUserNumber")
    @Log("根据用户工号查询用户信息")
    @ApiOperation("根据用户工号查询用户信息")
    public ResponseEntity<Object> findByUserNumber(String userNumber){
        return new ResponseEntity<>(dmUserService.findByCardId(userNumber),HttpStatus.OK);
    }
}