package com.ruoyi.cms.controller.cms;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.cms.domain.AppReviewJob;
import com.ruoyi.cms.domain.vo.AppUserLky;
import com.ruoyi.cms.service.IAppReviewJobService;
import com.ruoyi.cms.util.DateValidateUtil;
import com.ruoyi.cms.util.RoleUtils;
import com.ruoyi.cms.util.StringUtil;
import com.ruoyi.common.annotation.BussinessLog;
import com.ruoyi.common.core.domain.entity.AppUserShow;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SiteSecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.cms.service.IAppUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * APP用户Controller
 * 
 * @author lishundong
 * @date 2024-09-03
 */
@RestController
@RequestMapping("/cms/appUser")
@Api(tags = "后台：APP用户管理")
public class CmsAppUserController extends BaseController
{
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IAppReviewJobService appReviewJobService;

    /**
     * 查询APP用户列表
     */
    @ApiOperation("查询APP用户列表")
    @PreAuthorize("@ss.hasPermi('cms:appUser:list')")
    @GetMapping("/list")
    public TableDataInfo list(AppUser appUser)
    {
        startPage();
        List<AppUser> list = appUserService.selectAppUserList(appUser);
        //身份证脱敏
        list.forEach(it->{
            it.setIdCard(StringUtil.desensitizeIdCard(it.getIdCard()));
        });
        return getDataTable(list);
    }

    /**
     * 导出APP用户列表
     */
    @ApiOperation("导出APP用户列表")
    @PreAuthorize("@ss.hasPermi('cms:appUser:export')")
    @Log(title = "APP用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AppUser appUser)
    {
        List<AppUser> list = appUserService.selectAppUserList(appUser);
        ExcelUtil<AppUser> util = new ExcelUtil<AppUser>(AppUser.class);
        util.exportExcel(response, list, "APP用户数据");
    }

    /**
     * 获取APP用户详细信息
     */
    @ApiOperation("获取APP用户详细信息")
    @PreAuthorize("@ss.hasPermi('bussiness:user:query')")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId)
    {
        return success(appUserService.selectAppUserByUserId(userId));
    }

    /**
     * 新增APP用户
     */
    @ApiOperation("新增APP用户")
    @PreAuthorize("@ss.hasPermi('bussiness:user:add')")
    @Log(title = "APP用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppUser appUser)
    {
        return toAjax(appUserService.insertAppUser(appUser));
    }

    /**
     * 修改APP用户
     */
    @ApiOperation("修改APP用户")
    @Log(title = "APP用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppUser appUser)
    {
        if(appUser.getUserId()==null){
            return AjaxResult.error("参数userId为空");
        }
        return toAjax(appUserService.updateAppUser(appUser));
    }

    /**
     * 删除APP用户
     */
    @ApiOperation("删除APP用户")
    @PreAuthorize("@ss.hasPermi('bussiness:user:remove')")
    @Log(title = "APP用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(appUserService.deleteAppUserByUserIds(userIds));
    }

    /**
     * 获取APP用户详细信息（pc端获取移动端简历信息）
     */
    @ApiOperation("pc端个人简历信息-获取APP用户详细信息")
    @GetMapping(value = "/getUserInfo")
    public AjaxResult getUserInfo()
    {
        if(!SecurityUtils.isLogin()){
            return AjaxResult.error("未登录!");
        }
        return success(appUserService.getUserInfo());
    }

    /**
     * 修改用户简历信息-(技能信息、经历信息)
     */
    @ApiOperation("修改用户简历信息")
    @PostMapping("/editRegisterUser")
    @BussinessLog(title = "保存简历")
    public AjaxResult editRegisterUser(@RequestBody RegisterBody registerBody)
    {
        if (registerBody == null) {
            return AjaxResult.error("入参registerBody不能为空!");
        }
        if(registerBody.getAppUser()==null){
            return AjaxResult.error("用户信息为空!");
        }
        return AjaxResult.success(appUserService.editRegisterUser(registerBody));
    }

    @ApiOperation("查询APP用户列表")
    @GetMapping("/noTmlist")
    public TableDataInfo noTmlist(AppUser appUser)
    {
        startPage();
        List<AppUser> list = appUserService.selectNoTmAppUserList(appUser);
        //身份证脱敏
        list.forEach(it->{
            it.setIdCard(StringUtil.desensitizeIdCard(it.getIdCard()));
        });
        return getDataTable(list);
    }

    @ApiOperation("查询我的中（已经投递的，收藏的，足迹，预约）")
    @GetMapping("/getMyTj")
    public AjaxResult getMyTj()
    {
        if(!SecurityUtils.isLogin()){
            return AjaxResult.error("未登录!");
        }
        if(StringUtils.isEmpty(RoleUtils.getCurrentUseridCard())){
            return AjaxResult.error("用户信息为空!");
        }
        AppUser appUser=appUserService.selectAppuserByIdcard(RoleUtils.getCurrentUseridCard());
        if (Objects.isNull(appUser)) {
            return AjaxResult.error("未查询到用户信息（身份证号：" + RoleUtils.getCurrentUseridCard() + "）!");
        }
        return AjaxResult.success(appUserService.getMyTj(appUser.getUserId()));
    }

    @ApiOperation("返回求职者劳科院-当前职位名称、技能标签")
    @GetMapping("/appUserInfo")
    public AjaxResult appUserInfo(AppUser appUser)
    {
        if(!SecurityUtils.isLogin()){
            return AjaxResult.error("未登录！");
        }
        if(StringUtils.isEmpty(RoleUtils.getCurrentUseridCard())){
            return AjaxResult.error("用户信息为空!");
        }
        appUser=appUserService.selectAppuserByIdcard(RoleUtils.getCurrentUseridCard());
        if (Objects.isNull(appUser)) {
            return AjaxResult.error("未查询到用户信息（身份证号：" + RoleUtils.getCurrentUseridCard() + "）!");
        }
        AppUserLky appUserLky = appUserService.selectAppUserInfo(appUser);
        return AjaxResult.success(appUserLky);
    }

    @ApiOperation("查询APP申请用户列表")
    //@PreAuthorize("@ss.hasPermi('cms:appUser:userApplyList')")
    @GetMapping("/userApplyList")
    public TableDataInfo userApplyList(AppUser appUser)
    {
        String birthDateError = DateValidateUtil.validateBirthDate(appUser.getBirthDate());

        if (birthDateError != null) {
            TableDataInfo errorResult = new TableDataInfo();
            errorResult.setCode(400);
            errorResult.setMsg(birthDateError);
            errorResult.setRows(null);
            errorResult.setTotal(0);
            return errorResult;
        }
        startPage();
        List<AppUserShow> list = appUserService.selectUserApplyList(appUser);
        return getDataTable(list);
    }

    /**
     * 添加足迹信息
     * @param appReviewJob
     * @return
     */
    @PostMapping("/browse")
    @ApiOperation("用户浏览")
    public AjaxResult browse(@RequestBody AppReviewJob appReviewJob)
    {
        if (Objects.isNull(appReviewJob) || Objects.isNull(appReviewJob.getJobId())) {
            return AjaxResult.error("岗位id为空");
        }

        if (!SecurityUtils.isLogin()) {
            return AjaxResult.error("用户未登录!");
        }

        Long frontUserId = appReviewJob.getUserId();
        String useridCard = RoleUtils.getCurrentUseridCard();

        Long targetUserId;
        if (Objects.nonNull(frontUserId)) {
            targetUserId = frontUserId;
        } else {
            if (StringUtils.isEmpty(useridCard)) {
                return AjaxResult.error("用户身份证信息为空，无法获取用户ID!");
            }
            AppUser appUser = appUserService.selectAppuserByIdcard(useridCard);
            if (Objects.isNull(appUser)) {
                return AjaxResult.error("未查询到用户信息（身份证号：" + useridCard + "）!");
            }
            targetUserId = appUser.getUserId();
        }

        appReviewJob.setUserId(targetUserId);
        if(StringUtils.isEmpty(appReviewJob.getReviewDate())){
            appReviewJob.setReviewDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,new Date()));
        }
        return toAjax(appReviewJobService.insertAppReviewJob(appReviewJob));
    }
}
