package com.dayou.controller;

import com.dayou.annotation.DataPermission;
import com.dayou.annotation.OperLog;
import com.dayou.bo.PrivilegeTreeBO;
import com.dayou.condition.LoginCondition;
import com.dayou.dto.LoginDTO;
import com.dayou.dto.UpdatePasswordDTO;
import com.dayou.dto.UserBaseDetailDTO;
import com.dayou.enums.OperationTypeEnum;
import com.dayou.vo.DepartmentUserVO;
import com.dayou.vo.IdNameVO;
import com.dayou.vo.UserVO;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.RestController;
import com.dayou.service.IUserService;
import com.dayou.entity.User;
import com.dayou.common.RestResponse;
import org.springframework.web.bind.annotation.*;
import com.dayou.common.PullDownModel;
import com.dayou.utils.ConvertUtil;
import com.dayou.utils.HttpKit;
import com.dayou.exception.ErrorCode;

import java.util.List;
import java.util.Set;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import static com.dayou.common.Constants.FINANCE_DEPARTMENT;
import static com.dayou.common.Constants.MANAGER_OFFICE;
import static com.dayou.constants.JwtConstants.REST_TOKEN;

/**
 * 基础用户
 *
 * @author wucl
 * @since 2022-11-29
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;

    /**
    * 基础用户列表 部门
    */
    @DataPermission(department=true,ignoreDepartment = {MANAGER_OFFICE})
    @GetMapping("")
    public RestResponse<Page<UserVO>> page(UserVO userVO, Page page){
        Page<UserVO> pages=userService.xPage(page,userVO);
        return RestResponse.data(pages);
    }

    /**
     * 基础用户详情
     */
    @GetMapping("/{id}")
    public RestResponse<UserVO> detail(@PathVariable Long id){
        UserVO xUser =userService.detail(id);
        return RestResponse.data(xUser);
     }

    /**
     * 基础用户新增
     */
    @OperLog(title = "用户新增")
    @PostMapping("")
    public RestResponse<Boolean> save(@RequestBody @Valid UserVO user) {
        Boolean ret = userService.xSave(user);
        return RestResponse.data(ret);
    }

    /**
     * 基础用户更新
     */
    @OperLog(title = "用户更新")
    @PutMapping("")
    public RestResponse<Boolean> update(@RequestBody @Valid UserVO user) {
        Boolean ret = userService.xUpdate(user);
        return RestResponse.data(ret);
    }

    /**
     * 基础用户删除
     */
    @OperLog(title = "用户删除")
    @DeleteMapping("/{id}")
    public RestResponse<Boolean> delete(@PathVariable Long id) {
        Boolean ret = userService.delete(id);
        return RestResponse.data(ret);
    }


    /**
     * 基础用户下拉列表
     */
    @GetMapping("/simpleAll")
    public RestResponse<List<PullDownModel>> simpleAll(){
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<User>()
        .select(User::getId,User::getName)
        .eq(User::getDeleted,false);
        List<User> list= userService.list(lambdaQueryWrapper);
        List<PullDownModel> ret=ConvertUtil.copyList(list, PullDownModel.class);
        return RestResponse.data(ret);
    }
    /**
     * 基础用户模板下载
     */
    @OperLog(title = "基础用户模板下载",businessType = OperationTypeEnum.EXPORT)
    @GetMapping(value = "/download/importTemplate")
    public void importTemplate() {
        try {
            XSSFWorkbook wb = userService.generateImportTemplate();

            String fileName = "基础用户导入模板" + System.currentTimeMillis() + ".xlsx";

            writeXss2Response(HttpKit.getRequest(), HttpKit.getResponse(), wb, fileName);
        } catch (Exception e) {
            log.error("生成基础用户导入模板异常", e);
            ErrorCode.throwBusinessException(ErrorCode.DEFAULTERROR);
        }
    }

    /**
     * 基础用户导入
     */
    @OperLog(title = "基础用户模板导入",businessType = OperationTypeEnum.IMPORT)
    @PostMapping("/importExcel")
    public RestResponse<Boolean> importExcel(@RequestPart("file") MultipartFile file) {
        userService.importExcel(file);
        return RestResponse.data(true);
    }

    /**
     * 基础用户导出
     */
    @GetMapping(value = "/download/exportExcel")
    public void export(User user) {
        try {
            XSSFWorkbook wb =  userService.exportExcel(user);

            String fileName = "基础用户" + System.currentTimeMillis() + ".xlsx";

            writeXss2Response(HttpKit.getRequest(), HttpKit.getResponse(), wb, fileName);
        } catch (Exception e) {
            log.error("导出基础用户", e);
            ErrorCode.throwBusinessException(ErrorCode.DEFAULTERROR);
        }

    }

    /**
     * 登录
     *
     * @param loginCondition
     * @return
     */
    @PostMapping("/login")
    @OperLog(title = "登录", businessType = OperationTypeEnum.LOGIN)
    public RestResponse<LoginDTO> login(@RequestBody @Valid LoginCondition loginCondition, HttpServletRequest request) {
        LoginDTO loginDTO = userService.login(loginCondition,request);
        return RestResponse.data(loginDTO);
    }

    /**
     * 根据token获取基本信息
     *
     * @return
     */
    @GetMapping("/baseInfo")
    public RestResponse<UserBaseDetailDTO> baseInfo() {
        String token = HttpKit.getHeaderValue(REST_TOKEN);
        UserBaseDetailDTO userBaseDetailDTO = userService.baseInfo(token);
        return RestResponse.data(userBaseDetailDTO);
    }

    /**
     * 根据token获取用户权限
     *
     * @return
     */
    @GetMapping("/privilegesTree")
    public RestResponse<Set<PrivilegeTreeBO>> privilegesTree() {
        String token = HttpKit.getHeaderValue(REST_TOKEN);
        Set<PrivilegeTreeBO> list = userService.privilegesTree(token);
        return RestResponse.data(list);
    }

    /**
     * 重置密码
     * @param id
     * @return
     */
    @OperLog(title = "重置密码",businessType = OperationTypeEnum.RESET)
    @PutMapping("/resetPassword/{id}")
    public RestResponse<Boolean> restPassword(@PathVariable Long id){
        Boolean result = userService.restPassword(id);
        return RestResponse.data(result);
    }

    /**
     * 修改密码
     * @param passwordDTO
     * @return
     */
    @OperLog(title = "修改密码",businessType = OperationTypeEnum.SET)
    @PutMapping("/updatePassword")
    public RestResponse<Boolean> updatePassword(@RequestBody UpdatePasswordDTO passwordDTO){
        Boolean result = userService.updatePassword(passwordDTO);
        return RestResponse.data(result);
    }

    /**
     * 重置提成查询密码
     * @param id
     * @return
     */
    @OperLog(title = "重置提成查询密码",businessType = OperationTypeEnum.RESET)
    @PutMapping("/resetSettlePassword/{id}")
    public RestResponse<Boolean> resetSettlePassword(@PathVariable Long id){
        Boolean result = userService.resetSettlePassword(id);
        return RestResponse.data(result);
    }

    /**
     * 修改提成查询密码
     * @param passwordDTO
     * @return
     */
    @OperLog(title = "修改提成查询密码",businessType = OperationTypeEnum.SET)
    @PutMapping("/updateSettlePassword")
    public RestResponse<Boolean> updateSettlePassword(@RequestBody UpdatePasswordDTO passwordDTO){
        Boolean result = userService.updateSettlePassword(passwordDTO);
        return RestResponse.data(result);
    }
    /**
     * 岗位用户下拉列表
     */
    @GetMapping("/simple/{postName}")
    public RestResponse<List<PullDownModel>> simplePostName(@PathVariable("postName") String postName){
        List<User> list = userService.simplePostName(postName);
        List<PullDownModel> ret=ConvertUtil.copyList(list, PullDownModel.class);
        return RestResponse.data(ret);
    }


    /**
     * 岗位用户列表
     */
    @GetMapping("/list/{postName}")
    public RestResponse<List<UserVO>> listPostName(@PathVariable("postName") String postName){
        List<UserVO> list = userService.listPostName(postName);
        return RestResponse.data(list);
    }

    /**
     * 根据部门名称获取部门员工列表
     * @param departmentName
     * @return
     */
    @GetMapping("/departmentName/{departmentName}")
    public RestResponse<List<IdNameVO>> usersByDepartment(@PathVariable("departmentName") String departmentName){
        List<IdNameVO> list = userService.usersByDepartment(departmentName);
        return RestResponse.data(list);
    }

    /**
     * 项目提成二级密码验证
     * @param settlePassword
     * @return
     */
    @PostMapping("/validSettlePassword/{settlePassword}")
    public RestResponse<Boolean> validSettlePassword(@PathVariable("settlePassword")String settlePassword){
        Boolean result = userService.validSettlePassword(settlePassword);
        return RestResponse.data(result);
    }

    @GetMapping("/userLeader")
    public RestResponse<Long> getCurrentUserLeader(){
        Long leaderByCurrentUser = userService.getLeaderByCurrentUser();
        return RestResponse.data(leaderByCurrentUser);
    }

    /**
     * 根据部门id获取员工下拉列表
     */
    @GetMapping("/departmentId/{id}")
    public RestResponse<List<PullDownModel>> byDepartmentId(@PathVariable("id") Long id){
        List<User> list= userService.byDepartmentId(id);
        List<PullDownModel> ret=ConvertUtil.copyList(list, PullDownModel.class);
        return RestResponse.data(ret);
    }

    /**
     * 分单部门人员集合（按业务类型）
     * @return
     */
    @GetMapping("/allotDepartment/{businessType}")
    public RestResponse<List<PullDownModel>> allotDepartmentUsers(@PathVariable("businessType") String businessType){
        List<PullDownModel> list = userService.allotDepartmentUsers(businessType);
        return RestResponse.data(list);
    }

    /**
     * 岗位用户信息
     */
    @GetMapping("/info/{postName}")
    public RestResponse<List<User>> infoPostName(@PathVariable("postName") String postName){
        List<User> list = userService.infoPostName(postName);
        return RestResponse.data(list);
    }

    /**
     * 和当前登录人同部门的人员
     * @return
     */
    @GetMapping("/depart/users")
    public RestResponse<List<DepartmentUserVO>> departmentUsers(){
        List<DepartmentUserVO> ret = userService.departmentUsers();
        return RestResponse.data(ret);
    }

    /**
     * 获取资产评估师用户
     * @return RestResponse<List<PullDownModel>>
     */
    @GetMapping("/byAssetEvaluator")
    public RestResponse<List<PullDownModel>> byAssetEvaluator(){
        return RestResponse.data(ConvertUtil.copyList(userService.byAssetEvaluator(), PullDownModel.class));
    }

    /**
     * 根据部门名称获取部门及其下辖部门人员
     * @param depName 部门
     * @return RestResponse<List<PullDownModel>>
     */
    @GetMapping("/byDepartmentName/{depName}")
    public RestResponse<List<PullDownModel>> byDepartmentName(@PathVariable("depName") String depName) {
        return RestResponse.data(ConvertUtil.copyList(userService.byDepartmentName(depName), PullDownModel.class));
    }

    /**
     * 不再提示修改登录密码
     * @return
     */
    @GetMapping("/notRemind")
    public RestResponse<Boolean> notRemind(){
        Boolean ret = userService.notRemind();
        return RestResponse.data(ret);
    }

}

