package cn.exploring.engine.server.admin.web;

import cn.exploring.engine.server.admin.annotation.RequiresPermissionsDesc;
import cn.exploring.engine.server.core.util.ResponseUtil;
import cn.exploring.engine.server.core.util.bcrypt.BCryptPasswordEncoder;
import cn.exploring.engine.server.core.validator.Order;
import cn.exploring.engine.server.core.validator.Sort;
import cn.exploring.engine.server.db.domain.WxUser;
import cn.exploring.engine.server.db.service.WxUserService;
import cn.exploring.engine.server.db.util.RegexUtil;
import com.github.pagehelper.PageInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.exploring.engine.server.admin.util.AdminResponseCode.*;

@RestController
@RequestMapping("/admin/user")
@Validated
public class AdminUserController {
    private final Log logger = LogFactory.getLog(AdminUserController.class);

    @Autowired
    private WxUserService userService;

    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu={"会员管理" , "会员信息管理"}, button="查询")
    @GetMapping("/list")
    public Object list(WxUser user,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<WxUser> userList = userService.querySelective(user, page, limit, sort, order);
        long total = PageInfo.of(userList).getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", userList);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/username")
    public Object username(@NotEmpty String username) {
        boolean exist = userService.checkByUsername(username);
        if (exist) {
            return ResponseUtil.ok("已存在");
        }
        return ResponseUtil.ok("不存在");
    }

    private Object validate(WxUser user) {
        String username = user.getUsername();
        if (StringUtils.isEmpty(user)) {
            return ResponseUtil.badArgument();
        }
        /*if (!RegexUtil.isUsername(username)) {
            return ResponseUtil.fail(USER_INVALID_NAME, "用户名不符合规定");   注释此处的原因是，用户名必须大于6位，名字一般为3个汉字
        }*/
        String password = user.getPassword();
        if (StringUtils.isEmpty(password) || password.length() < 6) {
            return ResponseUtil.fail(USER_INVALID_PASSWORD, "用户密码长度不能小于6");
        }
        String mobile = user.getMobile();
        if (StringUtils.isEmpty(mobile)) {
            return ResponseUtil.badArgument();
        }
        if (!RegexUtil.isMobileExact(mobile)) {
            return ResponseUtil.fail(USER_INVALID_MOBILE, "用户手机号码格式不正确");
        }
        return null;
    }


    @RequiresPermissions("admin:user:create")
    @RequiresPermissionsDesc(menu={"会员管理" , "会员信息管理"}, button="添加")
    @PostMapping("/create")
    public Object create(@RequestBody WxUser user) {
        Object error = validate(user);
        if (error != null) {
            return error;
        }
        String username = user.getUsername();
        String mobile = user.getMobile();
        List<WxUser> userList = userService.queryByUsername(username);
        if (userList.size() > 0) {
            return ResponseUtil.fail(USER_NAME_EXIST, "用户名已注册");
        }
        userList = userService.queryByMobile(mobile);
        if (userList.size() > 0) {
            return ResponseUtil.fail(USER_MOBILE_EXIST, "手机号已注册");
        }
        if (!RegexUtil.isMobileExact(mobile)) {
            return ResponseUtil.fail(USER_INVALID_MOBILE, "手机号格式不正确");
        }

        if(user.getScores() != null && !RegexUtil.isNumeric(String.valueOf(user.getScores()))){
            return ResponseUtil.fail(USER_SCORES_ERROR, "积分必须是大于或等于0的整数");
        }

        String password = user.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(password);
        user.setPassword(encodedPassword);

        userService.add(user);
        return ResponseUtil.ok(user);
    }

    @RequiresPermissions("admin:user:update")
    @RequiresPermissionsDesc(menu={"会员管理" , "会员信息管理"}, button="编辑")
    @PostMapping("/update")
    public Object update(@RequestBody WxUser user) {
        Object error = validate(user);
        if (error != null) {
            return error;
        }
        // 如果已加密，则不加密，否则加密
        String password = user.getPassword();

       // System.out.println("*****前端***************:"+password+"***********后端*************:"+userDB.getPassword().trim());
       if(password != null && password.trim().length() <= 22){
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encodedPassword = encoder.encode(password);
            user.setPassword(encodedPassword);
        }

        if(user.getScores() != null && !RegexUtil.isNumeric(String.valueOf(user.getScores()))){
            return ResponseUtil.fail(USER_SCORES_ERROR, "积分必须是大于或等于0的整数");
        }

        if (userService.updateById(user) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        return ResponseUtil.ok(user);
    }

    //批量删除
    @RequiresPermissions("admin:user:delete")
    @RequiresPermissionsDesc(menu={"会员管理" , "会员信息管理"}, button="删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody Integer[] ids) {
        return userService.deleteByIds(ids);
    }
}
