/*
*  Copyright 2019-2025 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 com.aircraft.modules.system.controller;

import com.aircraft.annotation.Log;
import com.aircraft.annotation.rest.AnonymousPostMapping;
import com.aircraft.config.properties.RsaProperties;
import com.aircraft.exception.BadRequestException;
import com.aircraft.modules.security.config.LoginProperties;
import com.aircraft.modules.security.config.SecurityProperties;
import com.aircraft.modules.security.security.TokenProvider;
import com.aircraft.modules.security.service.OnlineUserService;
import com.aircraft.modules.security.service.UserDetailsServiceImpl;
import com.aircraft.modules.security.service.dto.AuthUserDto;
import com.aircraft.modules.security.service.dto.JwtUserDto;
import com.aircraft.modules.system.domain.EmArea;
import com.aircraft.modules.system.domain.EmEmployees;
import com.aircraft.modules.system.domain.User;
import com.aircraft.modules.system.domain.dto.EmEmployeesQueryCriteria;
import com.aircraft.modules.system.domain.dto.UserPassVo;
import com.aircraft.modules.system.domain.vo.EmEmployeesDetailVo;
import com.aircraft.modules.system.domain.vo.EmEmployeesVo;
import com.aircraft.modules.system.service.EmEmployeesService;
import com.aircraft.modules.system.service.UserService;
import com.aircraft.utils.*;
import com.aircraft.utils.enums.UserTypeEnum;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;

import java.util.Collections;
import java.util.HashMap;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
* @author lhb
* @date 2025-07-08
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "飞行员管理")
@RequestMapping("/api/emEmployees")
public class EmEmployeesController {

    private final SecurityProperties properties;
    private final RedisUtils redisUtils;
    private final OnlineUserService onlineUserService;
    private final TokenProvider tokenProvider;
    private final LoginProperties loginProperties;
    private final PasswordEncoder passwordEncoder;
    private final UserDetailsServiceImpl userDetailsService;
    private final EmEmployeesService emEmployeesService;
    private final UserService userService;

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

//    @GetMapping
//    @ApiOperation("查询员工管理")
//    @PreAuthorize("@el.check('emEmployees:list')")
//    public ResponseEntity<PageResult<EmEmployees>> queryEmEmployees(EmEmployeesQueryCriteria criteria){
//        Page<Object> page = new Page<>(criteria.getPage(), criteria.getSize());
//        return new ResponseEntity<>(emEmployeesService.queryAll(criteria,page),HttpStatus.OK);
//    }

    @PostMapping
    @Log("新增员工管理")
    @ApiOperation("新增员工管理")
    @PreAuthorize("@el.check('emEmployees:add')")
    public ResponseEntity<Object> createEmEmployees(@Validated @RequestBody EmEmployeesVo resources){
        emEmployeesService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改员工信息")
    @ApiOperation("修改员工信息")
    public ResponseEntity<Object> updateEmEmployees(@Validated @RequestBody EmEmployees resources){
        emEmployeesService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("查询详细信息")
    @ApiOperation(value = "查询详细信息")
    @RequestMapping(value = "{id}", method = {RequestMethod.GET})
    @ApiImplicitParam(name = "id", value = "飞行员id", required = true, paramType = "path")
    public ResponseEntity<Object> one(@PathVariable final Integer id) {
        try {
            EmEmployeesDetailVo entity = emEmployeesService.findById(id);
            return new ResponseEntity<>(entity,HttpStatus.OK);
        } catch (Exception e) {
            throw new RuntimeException("查询详细信息失败");
        }
    }

    @ApiOperation("修改密码")
    @PostMapping(value = "/updatePass")
    public ResponseEntity<Object> updateUserPass(@RequestBody UserPassVo passVo) throws Exception {
        EmEmployees emEmployees = emEmployeesService.findByUserName(SecurityUtils.getCurrentUsername());
        String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getOldPass());
        String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getNewPass());

        if(!passwordEncoder.matches(oldPass, emEmployees.getPassword())){
            throw new BadRequestException("修改失败，旧密码错误");
        }
        if(passwordEncoder.matches(newPass, emEmployees.getPassword())){
            throw new BadRequestException("新密码不能与旧密码相同");
        }
        emEmployeesService.updatePass(emEmployees.getUsername(),passwordEncoder.encode(newPass));
        return new ResponseEntity<>(HttpStatus.OK);
    }


    @DeleteMapping
    @Log("删除员工管理")
    @ApiOperation("删除员工管理")
    @PreAuthorize("@el.check('emEmployees:del')")
    public ResponseEntity<Object> deleteEmEmployees(@ApiParam(value = "传ID数组[]") @RequestBody List<Long> ids) {
        emEmployeesService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping("findByPage")
    @ApiOperation("分页查询员工管理")
    public ResponseEntity<PageResult<EmEmployeesDetailVo>> findByPage(final EmEmployeesDetailVo example, final Page page){
        PageResult<EmEmployeesDetailVo> records    = emEmployeesService.page(example,page);
        return new ResponseEntity<>(records,HttpStatus.OK);
    }

    @ApiOperation(value = "条件查询全部飞行员")
    @RequestMapping(value = "all", method = RequestMethod.GET)
    public ResponseEntity<Object> all(EmEmployees example) {
        List<EmEmployees> entitys = emEmployeesService.list(example);
        if (null != entitys) {
            return new ResponseEntity<>(entitys, HttpStatus.OK);
        }
        return new ResponseEntity<>(Collections.emptyList(), HttpStatus.OK);
    }

}