package com.lideeyunji.service.system.controller;

import cn.hutool.core.collection.CollUtil;
import com.lideeyunji.service.system.config.convert.user.UserConvert;
import com.lideeyunji.service.system.controller.vo.user.user.*;
import com.lideeyunji.service.system.controller.vo.user.user.*;
import com.lideeyunji.service.system.entity.AdminUserDO;
import com.lideeyunji.service.system.enums.SexEnum;
import com.lideeyunji.service.system.service.IAdminUserService;
import com.lideeyunji.service.system.service.IDeptService;
import com.lideeyunji.tool.framework.common.enums.CommonStatusEnum;
import com.lideeyunji.tool.framework.common.pojo.CommonResult;
import com.lideeyunji.tool.framework.common.pojo.PageParam;
import com.lideeyunji.tool.framework.common.pojo.PageResult;
import com.lideeyunji.tool.framework.common.util.object.BeanUtils;
import com.lideeyunji.tool.framework.common.util.string.StrUtils;
import com.lideeyunji.tool.framework.excel.core.util.ExcelUtils;
import com.lideeyunji.tool.framework.operatelog.core.annotations.OperateLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import static com.lideeyunji.tool.framework.common.pojo.CommonResult.success;
import static com.lideeyunji.tool.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 用户")
@RestController
@RequestMapping("/system/user")
@Validated
public class UserController {

    @Resource
    private IAdminUserService userService;
    @Resource
    private IDeptService deptService;

    @PostMapping("/create")
    @Operation(tags = "用户管理",summary = "新增用户")
    @PreAuthorize("@ss.hasPermission('system:user:create')")
    public CommonResult<Long> createUser(@Valid @RequestBody UserSaveReqVO reqVO) {
        Long id = userService.createUser(reqVO);
        return success(id);
    }

    @PutMapping("update")
    @Operation(tags = "用户管理",summary = "修改用户")
    @PreAuthorize("@ss.hasPermission('system:user:update')")
    public CommonResult<Boolean> updateUser(@Valid @RequestBody UserSaveReqVO reqVO) {
        userService.updateUser(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(tags = "用户管理",summary = "删除用户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user:delete')")
    public CommonResult<Boolean> deleteUser(@RequestParam("id") Long id) {
        userService.deleteUser(id);
        return success(true);
    }

    @PutMapping("/update-password")
    @Operation(tags = "用户管理",summary = "重置用户密码")
    @PreAuthorize("@ss.hasPermission('system:user:update-password')")
    public CommonResult<Boolean> updateUserPassword(@Valid @RequestBody UserUpdatePasswordReqVO reqVO) {
        userService.updateUserPassword(reqVO.getId(), reqVO.getPassword());
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(tags = "用户管理",summary = "修改用户状态")
    @PreAuthorize("@ss.hasPermission('system:user:update')")
    public CommonResult<Boolean> updateUserStatus(@Valid @RequestBody UserUpdateStatusReqVO reqVO) {
        userService.updateUserStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @GetMapping("/page")
    @Operation(tags = "用户管理",summary = "获得用户分页列表")
    @PreAuthorize("@ss.hasPermission('system:user:list')")
    public CommonResult<PageResult<UserRespVO>> getUserPage(@Valid UserPageReqVO pageReqVO) {
        // 获得用户分页列表
        PageResult<AdminUserDO> pageResult = userService.getUserPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }
        List<UserRespVO> voList=new ArrayList<>();
        List<AdminUserDO> adminUserDOList = pageResult.getList();
        for(AdminUserDO adminUserDO:adminUserDOList){
            Set<Long> deptId = StrUtils.str2setLong(adminUserDO.getDeptId());
            List<UserRespVO.DeptInfo> deptInfoList = userService.getDeptInfo(adminUserDO.getId(), deptId);
            UserRespVO userVO = BeanUtils.toBean(adminUserDO, UserRespVO.class);
            userVO.setDeptInfoList(deptInfoList);
            userVO.setSupAdminFlag(userService.isSupAdmin(userVO.getId()));
            userVO.setTenantAdminFlag(userService.isTenantAdmin(userVO.getId()));
            voList.add(userVO);
        }
        // 拼接数据
        return success(new PageResult<>(voList, pageResult.getTotal()));
    }

    @GetMapping({"/list-all-simple", "/simple-list"})
    @Operation(tags = "用户管理",summary = "获取用户精简信息列表", description = "只包含被开启的用户，主要用于前端的下拉选项")
    public CommonResult<List<UserSimpleRespVO>> getSimpleUserList() {
        List<AdminUserDO> list = userService.getUserListByStatus(CommonStatusEnum.ENABLE.getStatus());
        // 拼接数据
        return success(UserConvert.INSTANCE.convertSimpleList(list));
    }

    @GetMapping("/get")
    @Operation(tags = "用户管理",summary = "获得用户详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<UserRespVO> getUser(@RequestParam("id") Long id) {
        AdminUserDO user = userService.getUser(id);
        Set<Long> deptId = StrUtils.str2setLong(user.getDeptId());
        List<UserRespVO.DeptInfo> deptInfoList = userService.getDeptInfo(user.getId(), deptId);
        List<UserRespVO.IdName> rankInfoList = userService.getRankInfo(user.getId());

        //处理部门数据
        UserRespVO vo = UserConvert.INSTANCE.convert(user);
        vo.setDeptInfoList(deptInfoList);
        vo.setRankInfoList(rankInfoList);
        vo.setSupAdminFlag(userService.isSupAdmin(vo.getId()));
        vo.setTenantAdminFlag(userService.isTenantAdmin(vo.getId()));
        return success(vo);
    }

    @GetMapping("/export")
    @Operation(tags = "用户管理",summary = "导出用户")
    @PreAuthorize("@ss.hasPermission('system:user:export')")
    @OperateLog(type = EXPORT)
    public void exportUserList(@Validated UserPageReqVO exportReqVO,
                               HttpServletResponse response) throws IOException {
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<AdminUserDO> list = userService.getUserPage(exportReqVO).getList();
        // 输出 Excel
        ExcelUtils.write(response, "用户数据.xls", "数据", UserRespVO.class,
                UserConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/get-import-template")
    @Operation(tags = "用户管理",summary = "获得导入用户模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<UserImportExcelVO> list = Arrays.asList(
                UserImportExcelVO.builder().username("lidee").email("lidee@lidee.cn").mobile("15601691300")
                        .nickname("云玑").status(CommonStatusEnum.ENABLE.getStatus()).sex(SexEnum.MALE.getSex()).build(),
                UserImportExcelVO.builder().username("lidee").email("lidee@lidee.cn").mobile("15601701300")
                        .nickname("源码").status(CommonStatusEnum.DISABLE.getStatus()).sex(SexEnum.FEMALE.getSex()).build()
        );
        // 输出
        ExcelUtils.write(response, "用户导入模板.xls", "用户列表", UserImportExcelVO.class, list);
    }

    @PostMapping("/import")
    @Operation(tags = "用户管理",summary = "导入用户")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    @PreAuthorize("@ss.hasPermission('system:user:import')")
    public CommonResult<UserImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
                                                      @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<UserImportExcelVO> list = ExcelUtils.read(file, UserImportExcelVO.class);
        return success(userService.importUserList(list, updateSupport));
    }

}
