package com.bootdo.system.controller;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.bootdo.common.domain.DictDO;
import com.bootdo.common.token.TokenUtil;
import com.bootdo.common.utils.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.Constant;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.Tree;
import com.bootdo.common.service.DictService;
import com.bootdo.system.domain.DeptDO;
import com.bootdo.system.domain.RoleDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.RoleService;
import com.bootdo.system.service.UserService;
import com.bootdo.system.vo.UserVO;

@RequestMapping("/sys/user")
@Controller
public class UserController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private String prefix = "system/user";
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    DictService dictService;
    @Resource
    private TokenUtil tokenUtil;

    @Value("${sysProvince:#{null}}")
    public String sysProvince;

    @Value("${sysCity:#{null}}")
    public String sysCity;

    @Value("${back_manange_sso_url:#{null}}")
    public String backManangeSsoUrl;

    @Log("访问用户管理")
    @RequiresPermissions("sys:user:user")
    @GetMapping("")
    String user(Model model) {
        return prefix + "/user";
    }

    @GetMapping("/list")
    @ResponseBody
    PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        List<UserDO> sysUserList = userService.list(query);
        log.info("sysUserList size:" + sysUserList.size());
        log.info("count:" + userService.count(query));
        int total = userService.count(query);
        // sysUserList.size();
        PageUtils pageUtil = new PageUtils(sysUserList, total);
        return pageUtil;
    }

    @RequiresPermissions("sys:user:add")
    @Log("添加用户")
    @GetMapping("/add")
    String add(Model model) {
        List<RoleDO> roles = roleService.list();
        model.addAttribute("roles", roles);
        return prefix + "/add";
    }

    @RequiresPermissions("sys:user:edit")
    @Log("编辑用户")
    @GetMapping("/edit/{id}")
    String edit(Model model, @PathVariable("id") Long id) {
        UserDO userDO = userService.get(id);
        model.addAttribute("user", userDO);
        List<RoleDO> roles = roleService.list(id);
        model.addAttribute("roles", roles);
        return prefix + "/edit";
    }

    @RequiresPermissions("sys:user:add")
    @Log("保存用户")
    @PostMapping("/save")
    @ResponseBody
    R save(UserDO user) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));
        if (userService.save(user) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/update")
    @ResponseBody
    R update(UserDO user) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (userService.update(user) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/updatePeronal")
    @ResponseBody
    R updatePeronal(UserDO user) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (userService.updatePersonal(user) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions("sys:user:remove")
    @Log("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    R remove(Long id) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (userService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions("sys:user:batchRemove")
    @Log("批量删除用户")
    @PostMapping("/batchRemove")
    @ResponseBody
    R batchRemove(@RequestParam("ids[]") Long[] userIds) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        int r = userService.batchremove(userIds);
        if (r > 0) {
            return R.ok();
        }
        return R.error();
    }

    @PostMapping("/exit")
    @ResponseBody
    boolean exit(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !userService.exit(params);
    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("请求更改用户密码")
    @GetMapping("/resetPwd/{id}")
    String resetPwd(@PathVariable("id") Long userId, Model model) {

        UserDO userDO = new UserDO();
        userDO.setUserId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }

    @Log("提交更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    R resetPwd(UserVO userVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        try {
            userService.resetPwd(userVO, getUser());
            return R.ok();
        } catch (Exception e) {
            return R.error(1, e.getMessage());
        }

    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("admin提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    R adminResetPwd(UserVO userVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        try {
            userService.adminResetPwd(userVO);
            return R.ok();
        } catch (Exception e) {
            return R.error(1, e.getMessage());
        }

    }

    @GetMapping("/tree")
    @ResponseBody
    public Tree<DeptDO> tree() {
        Tree<DeptDO> tree = new Tree<DeptDO>();
        tree = userService.getTree();
        return tree;
    }

    @GetMapping("/treeView")
    String treeView() {
        return prefix + "/userTree";
    }

    @GetMapping("/personal")
    String personal(Model model) {
        UserDO userDO = userService.get(getUserId());
        model.addAttribute("user", userDO);
        model.addAttribute("hobbyList", dictService.getHobbyList(userDO));
        model.addAttribute("sexList", dictService.getSexList());
        return prefix + "/personal";
    }

    @ResponseBody
    @PostMapping("/uploadImg")
    R uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request) {
        if ("test".equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        Map<String, Object> result = new HashMap<>();
        try {
            result = userService.updatePersonalImg(file, avatar_data, getUserId());
        } catch (Exception e) {
            return R.error("更新图像失败！");
        }
        if (result != null && result.size() > 0) {
            return R.ok(result);
        } else {
            return R.error("更新图像失败！");
        }
    }


    @ResponseBody
    @GetMapping("/listProvince")
    public List<DictDO> listProvince() {
        String province = getUser().getProvince();

        if(StringUtils.isNotEmpty(province)){
            List<DictDO> dictList = new ArrayList<>();
            // 查询列表数据
            DictDO dictDO= new DictDO();
            dictDO.setName(province);
            dictDO.setValue(province);
            dictList.add(dictDO);
            return dictList;
        }
        if(StringUtils.isNotEmpty(sysProvince)){
            List<DictDO> dictList = new ArrayList<>();
            // 查询列表数据
            DictDO dictDO= new DictDO();
            dictDO.setName(sysProvince);
            dictDO.setValue(sysProvince);
            dictList.add(dictDO);
            return dictList;
        } else {
            // 查询列表数据
            Map<String, Object> map = new HashMap<>(16);
            map.put("type", "data_province");
            List<DictDO> dictList = dictService.list(map);
            return dictList;
        }

    }

    @ResponseBody
    @GetMapping("/listCityByProvince")
    public List<DictDO> listCityByProvince(String province) {
        String city = getUser().getCity();
        if(StringUtils.isNotEmpty(city)) {
            List<DictDO> dictList = new ArrayList<>();
            // 查询列表数据
            DictDO dictDO= new DictDO();
            dictDO.setName(city);
            dictDO.setValue(city);
            dictList.add(dictDO);
            return dictList;
        }
        if(StringUtils.isNotEmpty(sysCity)){
            List<DictDO> dictList = new ArrayList<>();
            // 查询列表数据
            DictDO dictDO= new DictDO();
            dictDO.setName(sysCity);
            dictDO.setValue(sysCity);
            dictList.add(dictDO);
            return dictList;
        } else {
            // 查询列表数据
            Map<String, Object> map = new HashMap<>(16);
            map.put("description", province);//描述
            List<DictDO> dictList = dictService.list(map);
            return dictList;
        }

    }

    @ResponseBody
    @GetMapping("/hasBackManangePerm")
    public boolean hasBackManangePerm() {
        try {
            //获取当前登录账号信息
            UserDO currUser = ShiroUtils.getUser();
            if (ObjectUtils.isEmpty(currUser)) {
                return false;
            }
            List<Integer> list = userService.getCurrUserSysList(currUser.getUserId());
            if(!ObjectUtils.isEmpty(list) && list.contains(0)){
                return true;
            } else {
                return false;
            }

        } catch (Exception e){
            e.printStackTrace();
            return false;
        }

    }

    @GetMapping("/getBackManangeSSoUrl")
    public String getBackManangeSSoUrl() {
        try {
            //获取当前登录账号信息
            UserDO currUser = ShiroUtils.getUser();
            if (ObjectUtils.isEmpty(currUser)) {
                return null;
            }

            List<Integer> list = userService.getCurrUserSysList(currUser.getUserId());
            if(ObjectUtils.isEmpty(list) || !list.contains(0)){
                return null;
            }

            String cacheToken = tokenUtil.getLoginUser(currUser.getUsername());
            if (ObjectUtils.isEmpty(cacheToken)) {
                return null;
            }
            String tokenStr = cacheToken.split("_")[0];
            return "redirect:" + backManangeSsoUrl + "?token=" + URLEncoder.encode(tokenStr);
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }


}
