package com.staffing.web.controller.employee;

import com.google.code.kaptcha.Producer;
import com.staffing.common.annotation.Log;
import com.staffing.common.config.StaffingConfig;
import com.staffing.common.constant.CacheConstants;
import com.staffing.common.constant.Constants;
import com.staffing.common.core.controller.BaseController;
import com.staffing.common.core.domain.AjaxResult;
import com.staffing.common.core.domain.entity.SysDept;
import com.staffing.common.core.domain.entity.SysMenu;
import com.staffing.common.core.domain.entity.SysRole;
import com.staffing.common.core.domain.entity.SysUser;
import com.staffing.common.core.domain.model.LoginBody;
import com.staffing.common.core.page.TableDataInfo;
import com.staffing.common.core.redis.RedisCache;
import com.staffing.common.enums.BusinessType;
import com.staffing.common.utils.SecurityUtils;
import com.staffing.common.utils.StringUtils;
import com.staffing.common.utils.poi.ExcelUtil;
import com.staffing.common.utils.sign.Base64;
import com.staffing.common.utils.uuid.IdUtils;
import com.staffing.custom.domain.StEmployee;
import com.staffing.custom.service.IStEmployeeService;
import com.staffing.custom.service.impl.StEmployeeServiceImpl;
import com.staffing.framework.web.service.SysLoginService;
import com.staffing.framework.web.service.SysPermissionService;
import com.staffing.framework.web.service.TokenService;
import com.staffing.system.service.*;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author staffing
 */
@RestController
@RequestMapping("/employee/user")
public class EmployeeUserController extends BaseController
{
    @Autowired
    private IStEmployeeService stEmployeeService;
    @Autowired
    private TokenService tokenService;
    /**
     * 修改用户
     */
    @PutMapping("profile")
    public AjaxResult edit(@RequestBody StEmployee stEmployeeParam)
    {
        StEmployee employee = new StEmployee();
        employee.setRealName(stEmployeeParam.getRealName());
        employee.setPhone(stEmployeeParam.getPhone());
        employee.setIdCard(stEmployeeParam.getIdCard());

        SysUser user = SecurityUtils.getLoginUser().getUser();
        user.setNickName(stEmployeeParam.getRealName());
        user.setPhonenumber(stEmployeeParam.getPhone());
        user.setIdCard(stEmployeeParam.getIdCard());
        tokenService.refreshToken( SecurityUtils.getLoginUser());

        employee.setId(user.getUserId());
        return toAjax(stEmployeeService.updateStEmployee(employee));
    }

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;
    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = StaffingConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }


    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * wx登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/wxlogin")
    public AjaxResult wxlogin(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.wxLogin(loginBody.getLoginCode(), loginBody.getPhoneCode(), 1);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }
    @GetMapping("verifyToken")
    public AjaxResult verifyToken()
    {
        AjaxResult ajax = AjaxResult.success();
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

}
