package com.jiayue.ipp.idp.controller;

import com.jiayue.ipp.common.data.entity.SysUser;
import com.jiayue.ipp.common.security.user.impl.SysUserServiceImpl;
import com.jiayue.ipp.idp.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 用户信息restful接口
 *
 * @author bizy
 * @version 3.0
 * @since 2020/6/28 10:12
 */
@RestController
@Slf4j
public class SysUserController {


    @Autowired
    SysUserServiceImpl sysUserServiceImpl;

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */

    @GetMapping(value = "sysUser/")
    public R getAll() {
        try {
            List<SysUser> ps = sysUserServiceImpl.getAll();
            return R.ok(ps);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(" 获取所有用户异常");
            return R.failed(null);
        }

    }

    /**
     * 保存用户信息
     *
     * @param sysUser 参数
     * @return 执行结果
     */
    @PostMapping(value = "sysUser/")
    public R save(@RequestBody SysUser sysUser) {
        try {
          // 用户名密码md5
          sysUser = md5User(sysUser);
            sysUserServiceImpl.save(sysUser);
          return R.ok("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(" 保存用户信息异常");
            return R.failed(" 保存用户信息异常");
        }

    }

    /**
     * 更新用户信息
     *
     * @param sysUser 参数
     * @return 执行结果
     */
    @PutMapping(value = "sysUser/")
    public R update(@RequestBody SysUser sysUser) {
        try {
          // 用户名密码md5
          sysUser = md5User(sysUser);
            sysUserServiceImpl.updateById(sysUser);
          return R.ok("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(" 更新用户信息异常");
            return R.failed();
        }
    }

    /**
     * 删除用户信息
     *
     * @param ids 删除id
     * @return 执行结果
     */
    @DeleteMapping(value = "sysUser/{ids}")
    public R delete(@PathVariable("ids") String ids) {
        try {
            sysUserServiceImpl.delete(ids);
            return R.ok("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(" 删除用户信息异常");
            return R.failed("删除用户信息异常");
        }

    }

  /**
   * 用户名密码加密
   * @param sysUser
   * @return
   */
    public SysUser md5User(SysUser sysUser){
      String userPassWord = sysUser.getPassWord();
      String passwordMD5;
      passwordMD5 = DigestUtils.md5DigestAsHex(userPassWord.getBytes())+"SYJY!";
      sysUser.setPassWord(passwordMD5);
      return sysUser;
    }

}
