package com.izouma.wenlvju.web;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.izouma.wenlvju.domain.User;
import com.izouma.wenlvju.dto.ExpertDTO;
import com.izouma.wenlvju.dto.OrganizationRegDTO;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.dto.UserRegister;
import com.izouma.wenlvju.enums.AuthorityName;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.UserRepo;
import com.izouma.wenlvju.security.Authority;
import com.izouma.wenlvju.security.JwtTokenUtil;
import com.izouma.wenlvju.security.JwtUserFactory;
import com.izouma.wenlvju.service.UserService;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.SecurityUtils;
import com.izouma.wenlvju.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@AllArgsConstructor
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    private final UserRepo     userRepo;
    private final UserService  userService;
    private final JwtTokenUtil jwtTokenUtil;

    @PostMapping("/register")
    public User register(@RequestParam String username,
                         @RequestParam String password) {
        UserRegister user = UserRegister.builder()
                .username(username)
                .nickname(username)
                .password(new BCryptPasswordEncoder().encode(password))
                .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
                .build();
        return userService.create(user);
    }

    @PostMapping("/regOrganization")
    public User regOrganization(@RequestBody OrganizationRegDTO dto) {
//        LocalDate start = Convert.convert(LocalDate.class, "2021-6-3");
//        if (LocalDate.now().isBefore(start)) {
//            throw new AuthenticationException("系统暂未开放注册", null);
//        }
        return userService.regOrganization(dto);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/create")
    public User create(@RequestBody UserRegister userRegister) {
        return userService.create(userRegister);
    }

    @PreAuthorize("hasAnyRole('ADMIN,ORGANIZER')")
    @PostMapping("/save")
//    @Transactional
    public User save(@RequestBody User user) {
        if (user.getId() != null) {
            User orig = userRepo.findById(user.getId()).orElseThrow(new BusinessException("无记录"));
            if (StrUtil.isNotEmpty(user.getPhone())) {
                User byPhone = userRepo.findByPhoneAndDelFalseAndIdIsNot(user.getPhone(), user.getId());
                if (ObjectUtil.isNotNull(byPhone)) {
                    throw new BusinessException("该手机号已绑定");
                }
            }
            ObjUtils.merge(orig, user);
            return userRepo.save(orig);
        }
        return userRepo.save(user);
    }

    @GetMapping("/my")
    public User my() {
        return userRepo.findById(SecurityUtils.getAuthenticatedUser().getId())
                .orElseThrow(new BusinessException("用户不存在"));
    }

    @GetMapping("/myAdmin")
    @PreAuthorize("hasRole('ADMIN')")
    public User myAdmin() {
        return userRepo.findById(SecurityUtils.getAuthenticatedUser().getId())
                .orElseThrow(new BusinessException("用户不存在"));
    }

    //    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<User> all(@RequestBody PageQuery pageQuery) {
        return userService.all(pageQuery);
    }

    @PostMapping("/all2")
    public Page<User> all2(@RequestBody PageQuery pageQuery) {
        List<Authority> authorities = new ArrayList<>();
        authorities.add(Authority.get(AuthorityName.ROLE_DISTRICT));
        authorities.add(Authority.get(AuthorityName.ROLE_ORGANIZER));
        authorities.add(Authority.get(AuthorityName.ROLE_ADMIN));
        authorities.add(Authority.get(AuthorityName.ROLE_DEV));
        authorities.add(Authority.get(AuthorityName.ROLE_SUPERVISOR));
        authorities.add(Authority.get(AuthorityName.ROLE_USER));
        authorities.add(Authority.get(AuthorityName.ROLE_DISTRICT_STAFF));
        return userService.byAuthority(pageQuery, authorities);
    }

    @PostMapping("/all1")
    public Page<ExpertDTO> all1(@RequestBody PageQuery pageQuery) {
        return userService.toArtType(pageQuery, Collections.singletonList(Authority.get(AuthorityName.ROLE_EXPERT)));
    }

    @PostMapping("/expert")
    public Page<ExpertDTO> expert(@RequestBody PageQuery pageQuery) {
        List<Authority> authorities = new ArrayList<>();
        authorities.add(Authority.get(AuthorityName.ROLE_DISTRICT_STAFF));
        authorities.add(Authority.get(AuthorityName.ROLE_EXPERT));
        return userService.toArtType(pageQuery, authorities);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/get/{id}")
    public User get(@PathVariable Long id) {
        return userRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        userService.del(id);
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<User> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }

    @PostMapping("/getMaUserInfo")
    @ApiOperation(value = "获取小程序用户信息")
    public User getMaUserInfo(String sessionKey, String rawData, String signature, String encryptedData, String iv) {
        User user = userService.getMaUserInfo(sessionKey, rawData, signature, encryptedData, iv);
        if (user != null) {
            return user;
        }
        throw new BusinessException("获取用户信息失败");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/setPasswordAdmin")
    public String setPasswordAdmin(@RequestParam Long userId, @RequestParam String password) {
        return userService.setPassword(userId, password);
    }

    @PostMapping("/changePassword")
    public String changePassword(@RequestParam String password, @RequestParam String key, @RequestParam String code) {
        return userService.setPassword(SecurityUtils.getAuthenticatedUser().getId(), key, code, password);
    }

    @PostMapping("/setPassword")
    public String setPassword(@RequestParam String password) {
        return userService.setPassword(SecurityUtils.getAuthenticatedUser().getId(), password);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/getToken/{userId}")
    public String getToken(@PathVariable Long userId) {
        return jwtTokenUtil.generateToken(JwtUserFactory.create(userRepo.findById(userId)
                .orElseThrow(new BusinessException("用户不存在"))));
    }

    @PostMapping("/authority")
    public List<User> authority(@RequestParam String authorityName) {
        return userRepo.findAllByAuthoritiesContainsAndDelFalse(Authority.builder().name(authorityName).build());
    }

    /**
     * 判断密码
     *
     * @return true 密码为123456需要改密码
     */
    @ApiOperation("判断密码")
    @PostMapping("/isEditPw")
    public boolean isEditPw() {
        User user = userRepo.findById(SecurityUtils.getAuthenticatedUser().getId())
                .orElseThrow(new BusinessException("无用户"));
        return new BCryptPasswordEncoder().matches("123456", user.getPassword());
    }

}
