package com.vetti.web.controller.system;

import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.vetti.common.core.domain.R;
import com.vetti.common.enums.IsInterviewEnum;
import com.vetti.common.enums.UserOperStepsEnum;
import com.vetti.hotake.domain.HotakeComplianceInfo;
import com.vetti.hotake.domain.HotakeCvInfo;
import com.vetti.hotake.domain.HotakeProblemBaseInfo;
import com.vetti.hotake.service.IHotakeComplianceInfoService;
import com.vetti.hotake.service.IHotakeCvInfoService;
import com.vetti.hotake.service.IHotakeProblemBaseInfoService;
import com.vetti.web.entity.dto.SysUserDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.vetti.common.annotation.Log;
import com.vetti.common.config.RuoYiConfig;
import com.vetti.common.core.controller.BaseController;
import com.vetti.common.core.domain.AjaxResult;
import com.vetti.common.core.domain.entity.SysUser;
import com.vetti.common.core.domain.model.LoginUser;
import com.vetti.common.enums.BusinessType;
import com.vetti.common.utils.DateUtils;
import com.vetti.common.utils.SecurityUtils;
import com.vetti.common.utils.StringUtils;
import com.vetti.common.utils.file.FileUploadUtils;
import com.vetti.common.utils.file.FileUtils;
import com.vetti.common.utils.file.MimeTypeUtils;
import com.vetti.framework.web.service.TokenService;
import com.vetti.system.service.ISysUserService;

/**
 * 个人信息 业务处理
 * 
 * @author ruoyi
 */
@Api(tags ="个人信息完善")
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IHotakeCvInfoService cvInfoService;

    @Autowired
    private IHotakeProblemBaseInfoService problemBaseInfoService;

    @Autowired
    private IHotakeComplianceInfoService complianceInfoService;

    /**
     * 个人信息
     */
    @ApiOperation("个人信息")
    @GetMapping("/personalInfo")
    public R<SysUserDto> profile()
    {
        SysUserDto dto =new SysUserDto();
        LoginUser loginUser = getLoginUser();
        SysUser user = userService.selectUserById(loginUser.getUserId());
        BeanUtil.copyProperties(user,dto);
        HotakeCvInfo query = new  HotakeCvInfo();
        query.setUserId(user.getUserId());
        List<HotakeCvInfo> cvInfoList = cvInfoService.selectHotakeCvInfoList(query);
        dto.setCvInfoList(cvInfoList);

        HotakeComplianceInfo queryCompliance = new  HotakeComplianceInfo();
        queryCompliance.setUserId(user.getUserId());
        List<HotakeComplianceInfo> complianceInfoList = complianceInfoService.selectHotakeComplianceInfoList(queryCompliance);
        dto.setComplianceInfoList(complianceInfoList);

        //是否可以参加面试
        HotakeProblemBaseInfo queryProblemBaseInfo = new HotakeProblemBaseInfo();
        queryProblemBaseInfo.setUserId(user.getUserId());
        List<HotakeProblemBaseInfo> problemBaseInfoList = problemBaseInfoService.selectHotakeProblemBaseInfoList(queryProblemBaseInfo);
        if(CollectionUtil.isNotEmpty(problemBaseInfoList)){
            dto.setIsInterview(IsInterviewEnum.INTERVIEW_1.getCode());
        }else{
            dto.setIsInterview(IsInterviewEnum.INTERVIEW_0.getCode());
        }
//        ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
//        ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return R.ok(dto,"");
    }


    /**
     * 修改用户
     */
    @ApiOperation("个人信息完善(按照步骤完善信息)")
    @Log(title = "个人信息完善", businessType = BusinessType.UPDATE)
    @PutMapping("/completeInfo")
    public R personalInfoProfile(@RequestBody SysUser user)
    {
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = userService.selectUserById(loginUser.getUserId());
        if(UserOperStepsEnum.STEPS_1.getCode().equals(user.getSteps())){
            currentUser.setNickName(user.getNickName());
            currentUser.setEmail(user.getEmail());
            currentUser.setPhonenumber(user.getPhonenumber());
            currentUser.setSex(user.getSex());
        }else if (UserOperStepsEnum.STEPS_2.getCode().equals(user.getSteps())){
            currentUser.setJobPosition(user.getJobPosition());
            currentUser.setExperience(user.getExperience());
            currentUser.setCvUrl(user.getCvUrl());
            currentUser.setJobTitle(user.getJobTitle());
            currentUser.setCompanyName(user.getCompanyName());
        }else if (UserOperStepsEnum.STEPS_3.getCode().equals(user.getSteps())){
            currentUser.setLocation(user.getLocation());
            currentUser.setJobType(user.getJobType());
            currentUser.setRelocate(user.getRelocate());
        }else if (UserOperStepsEnum.STEPS_4.getCode().equals(user.getSteps())){
            //个人展示数据存储
            currentUser.setBestSideJson(JSONUtil.toJsonStr(user.getBestSideDtoList()));
        }
        currentUser.setUserOperStatus(user.getUserOperStatus());
        currentUser.setSteps(user.getSteps());
        if (userService.updateUserProfile(currentUser) > 0)
        {
            loginUser.setUser(currentUser);
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser);
        }
        return R.ok();
    }

    /**
     * 个人信息修改
     */
    @ApiOperation("个人信息修改")
    @Log(title = "个人信息修改", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePersonalInfo")
    public R updatePersonalInfoProfile(@RequestBody SysUser user)
    {
        //更新简历数据
        if("cvOper".equals(user.getOperFlag())){
            //查询简历数据
            HotakeCvInfo query = new  HotakeCvInfo();
            query.setUserId(user.getUserId());
            query.setCvFileType("cv");
            List<HotakeCvInfo> cvInfoList = cvInfoService.selectHotakeCvInfoList(query);
            if(CollectionUtil.isNotEmpty(cvInfoList)){
                HotakeCvInfo cvInfo = cvInfoList.get(0);
                user.setCvTemplateJson(cvInfo.getCvTemplateJson());
            }
        }
        userService.updateUserProfile(user);
        return R.ok();
    }


    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUser user)
    {
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getUser();
        currentUser.setNickName(user.getNickName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhonenumber(user.getPhonenumber());
        currentUser.setSex(user.getSex());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(currentUser))
        {
            return error("修改用户'" + loginUser.getUsername() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser))
        {
            return error("修改用户'" + loginUser.getUsername() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(currentUser) > 0)
        {
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(@RequestBody Map<String, String> params)
    {
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");
        LoginUser loginUser = getLoginUser();
        Long userId = loginUser.getUserId();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return error("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(userId, newPassword) > 0)
        {
            // 更新缓存用户密码&密码最后更新时间
            loginUser.getUser().setPwdUpdateDate(DateUtils.getNowDate());
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = getLoginUser();
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION, true);
            if (userService.updateUserAvatar(loginUser.getUserId(), avatar))
            {
                String oldAvatar = loginUser.getUser().getAvatar();
                if (StringUtils.isNotEmpty(oldAvatar))
                {
                    FileUtils.deleteFile(RuoYiConfig.getProfile() + FileUtils.stripPrefix(oldAvatar));
                }
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }
}
