package cn.iocoder.yudao.module.staff.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.common.CommonErrorCodeConstants;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.security.config.SecurityProperties;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.label.entity.Label;
import cn.iocoder.yudao.module.staff.entity.CompanyStaff;
import cn.iocoder.yudao.module.staff.service.ApiAppLoginService;
import cn.iocoder.yudao.module.staff.service.CompanyStaffService;
import cn.iocoder.yudao.module.staff.vo.CompanyStaffReqVO;
import cn.iocoder.yudao.module.staff.vo.CompanyStaffRespVO;
import cn.iocoder.yudao.module.staff.vo.StaffLoginBody;
import cn.iocoder.yudao.module.system.api.permission.dto.RoleReqDTO;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthLoginReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.auth.AdminAuthService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 企业管理-员工信息表 控制层
 *
 * @author 小李
 * @date 17:14 2024/8/6
 **/
@RestController
@RequestMapping("/company/staff")
@Tag(name = "管理后台 - 企业管理 - 员工管理")
@Validated
public class CompanyStaffController {

    @Resource
    private CompanyStaffService staffService;
    @Resource
    private SecurityProperties securityProperties;
    @Resource
    private AdminAuthService loginService;
    @Autowired
    private ApiAppLoginService apiAppLoginService;

    /**
     * 分页查询
     *
     * @param pageReqVO 查询条件对象
     * @param pageNo    页码
     * @param pageSize  条数
     * @author 小李
     * @date 17:19 2024/8/6
     **/
    @GetMapping("/page")
    @Operation(summary = "获得企业管理-员工信息表信息分页")
    @PreAuthorize("@ss.hasPermission('company:staff:query')")
    public CommonResult<IPage<?>> getCompanyStaffPage(CompanyStaffReqVO pageReqVO,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<CompanyStaff> page = new Page<>(pageNo, pageSize);
        return success(staffService.queryListPage(pageReqVO, page));
    }

    /**
     * 新增员工
     *
     * @param staffRespVO 员工对象
     * @author 小李
     * @date 17:20 2024/8/6
     **/
    @PostMapping("/create")
    @Operation(summary = "创建企业管理-员工信息表信息")
    @PreAuthorize("@ss.hasPermission('company:staff:create')")
    public CommonResult<String> createCompanyStaff(@RequestBody CompanyStaffRespVO staffRespVO) {
        staffService.saveStaff(staffRespVO);
        return CommonResult.ok();
    }

    /**
     * 修改员工
     *
     * @param staffRespVO 员工对象
     * @author 小李
     * @date 17:24 2024/8/6
     **/
    @PutMapping("/update")
    @Operation(summary = "更新企业管理-员工信息表信息")
    @PreAuthorize("@ss.hasPermission('company:staff:update')")
    public CommonResult<Boolean> updateCompanyStaff(@RequestBody CompanyStaffRespVO staffRespVO) {
        staffService.updateStaff(staffRespVO);
        return CommonResult.ok();
    }

    /**
     * 删除员工
     *
     * @param id 员工id
     * @author 小李
     * @date 17:28 2024/8/6
     **/
    @DeleteMapping("/delete")
    @Operation(summary = "删除企业管理-员工信息表信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('company:staff:delete')")
    public CommonResult<Boolean> deleteCompanyStaff(@RequestParam("id") String id) {
        staffService.deleteStaff(id);
        return success(true);
    }

    /**
     * 查询员工
     *
     * @param id 员工ID
     * @author 小李
     * @date 17:59 2024/8/6
     **/
    @GetMapping("/get")
    @Operation(summary = "获得企业管理-员工信息表信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('company:staff:query')")
    public CommonResult<CompanyStaffRespVO> getCompanyStaff(@RequestParam("id") String id) {
        CompanyStaffRespVO staffRespVO = staffService.getCompanyStaffById(id);
        return success(staffRespVO);
    }

    /**
     * 给所有没有推广码的员工设置推广码
     * @author vinjor-M
     * @date 17:29 2024/10/15
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<cn.iocoder.yudao.module.staff.vo.CompanyStaffRespVO>
    **/
    @GetMapping("/setStaffUnicode")
    @Operation(summary = "给所有没有推广码的员工设置推广码")
    public CommonResult<CompanyStaffRespVO> setStaffUnicode() {
        staffService.setStaffUnicode();
        return CommonResult.ok();
    }

    /**
     * 查询员工单个 没有附加属性
     *
     * @param id 这里是userId
     * @author 小李
     * @date 17:59 2024/8/6
     **/
    @GetMapping("/getById")
    @Operation(summary = "获得企业管理-员工信息表信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<CompanyStaff> getCompanyStaffById(@RequestParam("id") String id) {
        return success(staffService.getOne(new LambdaQueryWrapper<CompanyStaff>().eq(CompanyStaff::getUserId, id)));
    }

    /**
     * 导出员工信息表
     *
     * @param pageReqVO 查询条件--暂时导出所有
     * @param response  响应体
     * @author 小李
     * @date 18:01 2024/8/6
     **/
    @GetMapping("/export-excel")
    @Operation(summary = "导出企业管理-员工信息表 Excel")
    @PreAuthorize("@ss.hasPermission('company:staff:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportCompanyStaffExcel(CompanyStaffReqVO pageReqVO,
                                        HttpServletResponse response) throws IOException {
        int pageNo = 1, pageSize = 100;
        List<CompanyStaff> list = new ArrayList<>();
        while (true){
            Page<CompanyStaff> page = new Page<>(pageNo, pageSize);
            IPage<CompanyStaff> staffIPage = staffService.queryListPage(pageReqVO, page);
            if (ObjectUtil.isNotEmpty(staffIPage) && !staffIPage.getRecords().isEmpty()){
                list.addAll(staffIPage.getRecords());
                pageNo++;
            }else {
                break;
            }
        }
        // 导出 Excel
        Map<Integer, Integer> columnWidthMap = new HashMap<>();
        // 第一列的索引是0，宽度设置为20个字符宽
        columnWidthMap.put(9, 20);
        columnWidthMap.put(10, 20);
        ExcelUtils.write(response, "企业信息表.xls", "数据", CompanyStaff.class, list, columnWidthMap);
    }

    /**
     * 获取当前功能的标签
     *
     * @author 小李
     * @date 14:59 2024/8/7
     **/
    @GetMapping("/labels")
    @Operation(summary = "获取当前功能的标签")
    @PreAuthorize("@ss.hasPermission('company:staff:query')")
    public CommonResult<List<Label>> getLabels() {
        return success(staffService.getLabels());
    }

    /**
     * 获取当前登录用户部门下所有员工信息
     *
     * @author 小李
     * @date 15:54 2024/8/8
     **/
    @GetMapping("/list")
    @Operation(summary = "获取当前登录用户部门下所有员工信息")
//    @PreAuthorize("@ss.hasPermission('company:staff:query')")
    public CommonResult<List<CompanyStaff>> getStaffList(@RequestParam(value = "query", defaultValue = "", required = false) String query) {
        return success(staffService.getStaffList(query));
    }

    /**
     * 验证工号是否重复
     *
     * @param workNo 输入的工号
     * @author 小李
     * @date 14:03 2024/8/9
     **/
    @GetMapping("/checkWorkNo")
    @Operation(summary = "验证工号是否重复")
    @PreAuthorize("@ss.hasPermission('company:staff:query')")
    public CommonResult<Boolean> checkWorkNo(@RequestParam("workNo") String workNo) {
        return success(staffService.checkWorkNo(workNo));
    }

    /**
     * 重置员工登录密码
     *
     * @param staffRespVO 员工对象
     * @author 小李
     * @date 16:21 2024/8/9
     **/
    @PostMapping("/resetPassword")
    @Operation(summary = "重置员工登录密码")
    @PreAuthorize("@ss.hasPermission('company:staff:resetPassword')")
    public CommonResult<T> resetPassword(@RequestBody CompanyStaffRespVO staffRespVO) {
        staffService.resetPassword(staffRespVO);
        return CommonResult.ok();
    }

    /**
     * 获取角色列表
     * @author 小李
     * @date 15:08 2024/8/14
    **/
    @GetMapping("/roleList")
    @Operation(summary = "获取角色列表")
    @PreAuthorize("@ss.hasPermission('company:staff:query')")
    public CommonResult<List<RoleReqDTO>> getRoleList(){
        return success(staffService.getRoleList());
    }

    /**
     * 获取当前某个企业下所有员工信息
     *
     * @author 小李
     * @date 15:54 2024/8/8
     * @param id 企业ID
     **/
    @GetMapping("/listByCorpId")
    @Operation(summary = "获取当前登录用户部门下所有员工信息")
    @PreAuthorize("@ss.hasPermission('company:property-deal:query')")
    public CommonResult<List<CompanyStaff>> getStaffListByCorpId(String id){
        return success(staffService.list(new LambdaQueryWrapper<CompanyStaff>().eq(CompanyStaff::getCorpId, id)));
    }

    /**
     * 退出登录状态
     * @author vinjor-M
     * @date 17:55 2024/10/16
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
    **/
    @PostMapping("/logout")
    @Operation(summary = "登出系统")
    public CommonResult<Boolean> logout(HttpServletRequest request) {
        String token = SecurityFrameworkUtils.obtainAuthorization(request,
                securityProperties.getTokenHeader(), securityProperties.getTokenParameter());
        if (StrUtil.isNotBlank(token)) {
            loginService.logout(token,1);
        }
        return success(true);
    }

    /**
     * 员工登录方法
     * @author vinjor-M
     * @date 15:17 2024/10/16
     * @param loginBody 登录请求体
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult
     **/
    @PostMapping("/loginApp")
    public CommonResult<?> loginApp(@RequestBody StaffLoginBody loginBody) throws Exception {
        try {
            AdminUserDO user = apiAppLoginService.loginApp(loginBody);
            AuthLoginReqVO authLoginReqVO = new AuthLoginReqVO();
            authLoginReqVO.setUsername(loginBody.getUsername());
            authLoginReqVO.setPassword(loginBody.getPassword());
            Map<String,Object> rtnMap = new HashMap<>();
            rtnMap.put("userinfo",user);
            rtnMap.put("loginResult",loginService.loginApp(authLoginReqVO,loginBody.getTenantId()));
            return success(rtnMap);
        }catch (Exception e){
            return error(CommonErrorCodeConstants.LOGIN_ACCOUNT_NOT_EXIST);
        }
    }
}
