package com.github.wxiaoqi.security.admin.rest;

import com.github.wxiaoqi.security.admin.biz.GroupBiz;
import com.github.wxiaoqi.security.admin.biz.MenuBiz;
import com.github.wxiaoqi.security.admin.biz.UserBiz;
import com.github.wxiaoqi.security.admin.entity.Menu;
import com.github.wxiaoqi.security.admin.entity.User;
import com.github.wxiaoqi.security.admin.rpc.service.PermissionService;
import com.github.wxiaoqi.security.admin.vo.FrontUser;
import com.github.wxiaoqi.security.admin.vo.GroupUsers;
import com.github.wxiaoqi.security.admin.vo.MenuTree;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.auth.client.jwt.UserAuthUtil;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.rest.CommonBaseController;
import com.github.wxiaoqi.security.common.util.Query;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

import static com.github.wxiaoqi.security.auth.common.constatns.CommonConstants.DATA_ALL_TRUE;
import static com.github.wxiaoqi.security.auth.common.constatns.CommonConstants.DATA_ALL_FALSE;
/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-08 11:51
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController extends CommonBaseController {

    public final static Integer CURRENT_COMPANY = 1;
    public final static Integer CURRENT_ZONE = 2;
    public final static Integer DATA_ALL = 3;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private MenuBiz menuBiz;

    @Autowired
    private GroupBiz groupBiz;

    @Autowired
    private UserBiz userBiz;

    @Autowired
    private UserAuthUtil userAuthUtil;

    @Autowired
    private UserAuthConfig userAuthConfig;

    //内部类

    @Data
    public static class UserVO extends User {
        //        List<Integer> dataLimit;
        Integer dataLimit;
        List<Integer> members;
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    @IgnoreClientToken
    public ObjectRestResponse<User> add(@RequestBody UserVO vo) {
        handleDataLimit(vo);
        String username = vo.getUsername();
        if (StringUtils.isNotBlank(username)) {
            List<User> list = userBiz.getCountByUsername(username);
            if (list.size() > 0) {
                throw new RuntimeException("用户名不能重复");
            }
        }
        userBiz.insertSelective(vo);
        //添加权限关系
        groupBiz.modifyUserGroups(vo.getId(), vo.getMembers());
        return new ObjectRestResponse();
    }

    private void handleDataLimit(@RequestBody UserVO dto) {
        if (null != dto.getDataLimit()) {
            dto.setDataCompany("");
            dto.setDataAll(DATA_ALL_FALSE);
            dto.setDataZone("");
            if (dto.getDataLimit()>=CURRENT_COMPANY && dto.getCompanyId() != null) {
                dto.setDataCompany(dto.getCompanyId().toString());

            }
            if (dto.getDataLimit()>=CURRENT_ZONE && dto.getZoneId() != null) {
                dto.setDataZone(dto.getZoneId().toString());
            }
            if (dto.getDataLimit()>=DATA_ALL) {
                dto.setDataAll(DATA_ALL_TRUE);
            }
        }
    }

    @RequestMapping(value = "/front/info", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<?> getUserInfo(String token) throws Exception {
        FrontUser userInfo = permissionService.getUserInfo(token);
        if(userInfo==null) {
            return ResponseEntity.status(401).body(false);
        } else {
            return ResponseEntity.ok(userInfo);
        }
    }


    @RequestMapping(value = "/front/menus", method = RequestMethod.GET)
    public @ResponseBody
    List<MenuTree> getMenusByUsername(String token) throws Exception {
        return permissionService.getMenusByUsername(token);
    }

    @RequestMapping(value = "/front/menu/all", method = RequestMethod.GET)
    public @ResponseBody
    List<Menu> getAllMenus() throws Exception {
        return menuBiz.selectListAll();
    }

    @RequestMapping(value = "/page",method = RequestMethod.GET)
    @ResponseBody
    public TableResultResponse<User> list(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);
        try {
            return userBiz.selectPage(query, userBiz.getUserByUsername(userAuthUtil.getInfoFromToken(userAuthConfig.getToken(request)).getUniqueName()));
        }catch (Exception e) {
            log.error(e.getMessage());
            return new TableResultResponse<User>();
        }
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<User> get(@PathVariable int id) {
        ObjectRestResponse<User> entityObjectRestResponse = new ObjectRestResponse<>();
        User o = userBiz.selectById(id);
        entityObjectRestResponse.data(o);
        return entityObjectRestResponse;
    }

    @RequestMapping(value = "/{id}/group", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<GroupUsers> getGroup(@PathVariable int id) {
        return new ObjectRestResponse<GroupUsers>().rel(true).data(groupBiz.getUserGroups(id));
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public ObjectRestResponse<User> update(@RequestBody UserVO vo) {
        handleDataLimit(vo);
        String username = vo.getUsername();
        if (StringUtils.isNotBlank(username)) {
            List<User> list = userBiz.getCountByUsername(username);
            if (list.size() > 1) {
                throw new RuntimeException("用户名不能重复");
            }
            if (list.size() == 1) {
                User user = list.get(0);
                if (!user.getId().equals(vo.getId())) {
                    throw new RuntimeException("用户名不能重复");
                }
            }
        }
        userBiz.updateSelectiveById(vo);
        //添加权限关系
        groupBiz.modifyUserGroups(vo.getId(), vo.getMembers());
        return new ObjectRestResponse<User>();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public ObjectRestResponse<User> remove(@PathVariable int id) {
        userBiz.deleteById(id);
        return new ObjectRestResponse<User>();
    }

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public List<User> all() {
        return userBiz.selectListAll();
    }
}
