package com.younike.admin.controller.system;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.younike.admin.service.SysPasswordService;
import com.younike.admin.utils.ShiroUtils;
import com.younike.common.annotation.OpLog;
import com.younike.common.annotation.RestAuth;
import com.younike.common.bean.APIResult;
import com.younike.common.bean.ResultGenerator;
import com.younike.common.constant.BusinessType;
import com.younike.common.constant.OperatorType;
import com.younike.common.constant.ResultPacketCode;
import com.younike.common.constant.UserConstants;
import com.younike.common.core.controller.BaseController;
import com.younike.common.core.dto.AjaxResult;
import com.younike.common.core.page.PageDomain;
import com.younike.common.core.page.PageParam;
import com.younike.common.core.page.TableSupport;
import com.younike.common.id.IDUtils;
import com.younike.common.utils.oss.service.IStorageService;
import com.younike.service.pojo.SysUser;
import com.younike.service.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.Optional;

/**
 * 用户信息
 *
 * @author Andrew
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysPasswordService sysPasswordService;

    @Autowired
    private IStorageService storageService;
    @Value("${oss.filehost}")
    private String fileHost;

    /**
     * 获取用户列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/list")
    public Page list(SysUser sysUser) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        PageParam pageParam = new PageParam(pageNum,pageSize);

        Page<SysUser> sysUserIPage = sysUserService.selectUserList(pageParam, sysUser);
        return sysUserIPage;
    }

    /**
     * 新增用户
     *
     * @param map 用户信息
     */
    @RequiresPermissions("system:user:add")
    @PostMapping("")

    @OpLog(type = BusinessType.INSERT, operatorType = OperatorType.MANAGE, title = "新增用户")
    public APIResult addUser(@RequestBody Map<String, Object> map) {
        SysUser user = SysUser.mapToUser(map);
        user.setPassword((String) map.get("password"));
        //检查唯一性
        if (!sysUserService.checkPhoneUnique(user).equals(UserConstants.USER_PHONE_UNIQUE)) {
            return ResultGenerator.getFailResult("该手机号码已存在");
        }
        if (!sysUserService.checkEmailUnique(user).equals(UserConstants.USER_EMAIL_UNIQUE)) {
            return ResultGenerator.getFailResult("该邮箱已存在");
        }
        if (!sysUserService.checkLoginNameUnique(user.getLoginName()).equals(UserConstants.LOGIN_NAME_UNIQUE)) {
            return ResultGenerator.getFailResult("该用户名称已存在");
        }
        user.setUserId(IDUtils.nextLongId());
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(sysPasswordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        user.setUpdateBy(ShiroUtils.getLoginName());
        sysUserService.insertUser(user);
        return ResultGenerator.getSuccessResult();
    }


    /**
     * 修改物业管理员
     * @param user
     * @return
     */
    @PostMapping("updateOrAdd")

    @OpLog(type = BusinessType.INSERT, operatorType = OperatorType.MANAGE, title = "新增物业管理员")
    public APIResult updateOrAdd(@RequestBody SysUser user) {

        //检查唯一性
        /*if (!sysUserService.checkPhoneUnique(user).equals(UserConstants.USER_PHONE_UNIQUE)) {
            return ResultGenerator.getFailResult("该手机号码已存在");
        }*/

        SysUser userByLoginName = sysUserService.selectUserByLoginName(user.getLoginName());
        if( userByLoginName != null && userByLoginName.getUserId().longValue() != Optional.ofNullable(user.getUserId()).orElse(0L).longValue()){
            return ResultGenerator.getFailResult("该用户名称已存在");
        }

        //当前用户已存在
        if(user.getUserId() != null){
            SysUser oldUser = sysUserService.selectUserById(user.getUserId());
            //重置密码
            user.setSalt(ShiroUtils.randomSalt());
            if(!oldUser.getPassword().equals(user.getPassword())){
                user.setPassword(sysPasswordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
            }
            //更新
            sysUserService.updateUserInfo(user);
            return ResultGenerator.getSuccessResult();
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(sysPasswordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        user.setUserType("01");
        user.setUserName("运营管理员");
        user.setPhonenumber("-");
        Long[] roleIds = {131L};
        user.setRoleIds(roleIds);
        int row = sysUserService.insertUser(user);
        SysUser sysUser = sysUserService.selectUserByLoginName(user.getLoginName());

        return ResultGenerator.getSuccessResult();
    }



    /**
     * 根据id查找用户
     */
    @GetMapping(value = "/{userId}")
    public SysUser getUser(@PathVariable Long userId) {
        return sysUserService.selectUserById(userId);
    }

    /**
     * 查询用户个人信息
     */
    @GetMapping(value = "/profile")
    public AjaxResult getUserProfile() {
        Long userId = ShiroUtils.getUserId();
        SysUser user = sysUserService.selectUserById(userId);
        AjaxResult result = AjaxResult.success();
        result.put("data", user);
        result.put("roleGroup", sysUserService.selectUserRoleGroup(userId));
        return result;
    }

    /**
     * 更新用户
     */
    @PutMapping("")

    public APIResult updateUser(@RequestBody Map<String, Object> map) {
        SysUser user = SysUser.mapToUser(map);
        user.setUserId(Long.parseLong(map.get("userId").toString()));
        sysUserService.checkUserAllowed(user);

        //检查唯一性
        if (!sysUserService.checkPhoneUnique(user).equals(UserConstants.USER_PHONE_UNIQUE)) {
            return ResultGenerator.getFailResult("该手机号码已存在");
        }
        /*if (!sysUserService.checkEmailUnique(user).equals(UserConstants.USER_EMAIL_UNIQUE)) {
            return ResultGenerator.getFailResult("该邮箱已存在");
        }*/
        user.setUpdateBy(ShiroUtils.getLoginName());
        sysUserService.updateUser(user);



        return ResultGenerator.getSuccessResult();
    }

    /**
     * 修改用户个人信息
     */
    @PutMapping("/profile")

    public APIResult updateUserProfile(@RequestBody Map<String, Object> map) {
        SysUser user = SysUser.mapToUser(map);
        user.setUserId(ShiroUtils.getUserId());
        //检查唯一性
        if (!sysUserService.checkPhoneUnique(user).equals(UserConstants.USER_PHONE_UNIQUE)) {
            return ResultGenerator.getFailResult("该手机号码已存在");
        }
        if (!sysUserService.checkEmailUnique(user).equals(UserConstants.USER_EMAIL_UNIQUE)) {
            return ResultGenerator.getFailResult("该邮箱已存在");
        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        sysUserService.updateUser(user);
        return ResultGenerator.getSuccessResult();
    }

    /**
     * 删除用户
     */
    @DeleteMapping(value = "/{userId}")

    public APIResult deleteUsers(@PathVariable String userId) {
        try {
            sysUserService.deleteUserByIds(userId);
        } catch (Exception e) {
            return ResultGenerator.getFailResult(e.getMessage());
        }
        return ResultGenerator.getSuccessResult();
    }

    /**
     * 更改状态
     */
    @PutMapping("/changeStatus")

    public APIResult changeStatus(@RequestBody Map<String, Object> data) {
        String userIdS = (String) data.get("userId");
        String status = (String) data.get("status");
        Long userId = Long.parseLong(userIdS);
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setStatus(status);
        try {
            sysUserService.checkUserAllowed(user);
        } catch (Exception e) {
            return ResultGenerator.getFailResult(e.getMessage());
        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        sysUserService.changeStatus(user);
        return ResultGenerator.getSuccessResult();
    }

    /**
     * 重置密码
     */
    @PutMapping("/resetPwd")

    public APIResult resetPassword(@RequestBody Map<String, Object> data) {
        String userLoginNameS = (String) data.get("loginName");
        String userIdS = (String) data.get("userId");
        String password = (String) data.get("password");
        Long userId = Long.parseLong(userIdS);
        SysUser sysUser = sysUserService.selectUserById(userId);
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setPassword(password);
        user.setLoginName(userLoginNameS);
        try {
            sysUserService.checkUserAllowed(user);
        } catch (Exception e) {
            return ResultGenerator.getFailResult(e.getMessage());
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(sysPasswordService.encryptPassword(sysUser.getLoginName(), password, user.getSalt()));
        user.setUpdateBy(ShiroUtils.getLoginName());
        sysUserService.resetUserPwd(user);
        return ResultGenerator.getSuccessResult();
    }

    /**
     * 修改用户密码
     */
    @PutMapping("/profile/updatePwd")

    public APIResult updatePwd(@RequestParam String oldPassword, @RequestParam String newPassword) {
        Long userId = ShiroUtils.getUserId();
        SysUser user = sysUserService.selectUserById(userId);
        if (!sysPasswordService.matches(user, oldPassword)) {
            return ResultGenerator.getFailResult("旧密码错误，修改失败");
        }
        user.setPassword(newPassword);
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(sysPasswordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setUpdateBy(ShiroUtils.getLoginName());
        sysUserService.resetUserPwd(user);
        return ResultGenerator.getSuccessResult();
    }

    /**
     * 单文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/profile/avatar")
    @RestAuth(isPublic = true)
//    @SentinelResource(value = "avatarUpload", blockHandlerClass = SentinelBlockHandler.class,blockHandler = "handlerException")
    @ApiOperation("头像上传")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "请求成功"),
            @ApiResponse(responseCode = "150", description = "请求参数不正确"),
            @ApiResponse(responseCode = "404", description = "请求路径没有或页面跳转路径不对")
    })
    public APIResult<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        SysUser sysUser = ShiroUtils.getSysUser();
        if (sysUser == null) {
            return ResultGenerator.getFailResult("未获取到用户信息");
        }

        APIResult<String> result = new APIResult<String>();
        // 保存文件
        String path = storageService.storeBlob(file);

        // 保存用户头像
        SysUser user = sysUserService.selectUserById(sysUser.getUserId());
        user.setAvatar(fileHost + path);
        if (sysUserService.updateUserInfo(user) != 1) {
            return ResultGenerator.getFailResult("修改用户头像 失败");
        }

        result.setCode(path == null ? ResultPacketCode.APIResultCode.Fail.getCode() : ResultPacketCode.APIResultCode.Success.getCode());
        result.setResult(fileHost + path);
        return result;
    }

}
