package com.zxdmy.excite.admin.controller.cloud.role;


import com.zxdmy.excite.common.base.BaseResult;
import com.zxdmy.excite.common.entity.PageList;
import com.zxdmy.excite.framework.aop.AnnotationSaveReLog;
import com.zxdmy.excite.system.entity.SysRole;
import com.zxdmy.excite.system.entity.cloud.role.CloudRole;
import com.zxdmy.excite.system.entity.dto.RoleTreeDTO;
import com.zxdmy.excite.system.entity.req.role.ReqRole;
import com.zxdmy.excite.system.entity.vo.role.RoleVo;
import com.zxdmy.excite.system.service.ISysUserService;
import com.zxdmy.excite.system.service.cloud.role.ICloudRoleService;
import com.zxdmy.excite.system.service.cloud.role.ICloudRoleUserService;
import lombok.AllArgsConstructor;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import com.zxdmy.excite.common.base.BaseController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 云盘权限表 前端控制器
 * </p>
 *
 * @author ss
 * @since 2026-01-27
 */
@Controller
@AllArgsConstructor
@RequestMapping("/cloud/role/")
public class CloudRoleController extends BaseController {
    private ICloudRoleService iCloudRoleService;
    private ISysUserService iSysUserService;
    private ICloudRoleUserService iCloudRoleUserService;


    @RequestMapping("index")
    public String index() {
        return "cloud/role/role/index";
    }

    @GetMapping("/list")
    @ResponseBody
    public BaseResult getRoleList(Integer page, Integer limit, ReqRole data) {
        try {
            PageList<RoleVo> dataPage = iCloudRoleService.queryByPage(page, limit, data);
            return success("获取数据成功", dataPage.getList(), (int) dataPage.getTotal());
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }

    @RequestMapping("add")
    public String add() {
        return "cloud/role/role/add";
    }

    @PostMapping("/addSave")
    @ResponseBody
    @AnnotationSaveReLog
    public BaseResult addSave(@Validated ReqRole data) {
        try {
            if(null == iCloudRoleService.getByData(data)){
                if(iCloudRoleService.saveData(data)==1){
                    return success("操作成功");
                }else{
                    return error(400, "操作失败，系统错误");
                }
            }else{
                return error(400, "操作失败，数据已存在");
            }
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }

    @RequestMapping("edit/{id}")
    public String edit(@PathVariable String id, ModelMap map) {
        CloudRole data = iCloudRoleService.getById(id);
        // 加载至前端
        if (data == null) {
            map.put("code", 404);
            map.put("msg", "数据不存在！");
            return "error/error";
        }
        map.put("id", id);
        return "cloud/role/role/edit";
    }

    @GetMapping("/getData")
    @ResponseBody
    public BaseResult getData(String id) {
        try {
            CloudRole data = iCloudRoleService.getById(id);
            if(null!=data){
                return success("获取数据成功",data);
            }else{
                return error(400, "数据不存在！");
            }


        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }

    @PostMapping("/editSave")
    @ResponseBody
    @AnnotationSaveReLog
    public BaseResult editSave(@Validated ReqRole data) {
        try {
            RoleVo roleVo =iCloudRoleService.getByData(data);
            CloudRole cloudRole = iCloudRoleService.getById(data.getId());
            if(roleVo==null){
                if(iCloudRoleService.updateData(data)==1){
                    return success(200,"操作成功");
                }else{
                    return error(400, "操作失败，系统错误");
                }
            }else{
                if(cloudRole.getRoleName().equals(roleVo.getRoleName())){
                    if(iCloudRoleService.updateData(data)==1){
                        return success(200,"操作成功");
                    }else{
                        return error(400, "操作失败，系统错误");
                    }
                }else{
                    return error(400, "操作失败，数据已存在");
                }
            }
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }

    @PostMapping("/delete")
    @ResponseBody
    @AnnotationSaveReLog
    public BaseResult delete(String id) {
        try {
            int result = iCloudRoleService.deleteById(id);
            if (result == 1) {
                return success(200, "删除成功！");
            }else{
                return error("删除失败！");
            }
        } catch (Exception e) {
            return error("发生错误:" + e.getMessage());
        }
    }

    @PostMapping(value = "/changeUploadStatus/{status}")
    @ResponseBody
    public BaseResult changeUploadStatus(@PathVariable String status, String[] ids) {
        try {
            int[] result = iCloudRoleService.changeUploadStatus(Integer.parseInt(status), ids);
            // 没有失败
            if (result[0] != 0 && result[1] == 0) {
                return success(200, "修改成功！");
            }
            // 有成功的
            else if (result[0] != 0) {
                return success(200, result[0] + "个更新成功，" + result[1] + "个失败！");
            } else {
                return success(500, "修改失败，请重试！");
            }
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }
    @PostMapping(value = "/changeDownStatus/{status}")
    @ResponseBody
    public BaseResult changeDownStatus(@PathVariable String status, String[] ids) {
        try {
            int[] result = iCloudRoleService.changeDownStatus(Integer.parseInt(status), ids);
            // 没有失败
            if (result[0] != 0 && result[1] == 0) {
                return success(200, "修改成功！");
            }
            // 有成功的
            else if (result[0] != 0) {
                return success(200, result[0] + "个更新成功，" + result[1] + "个失败！");
            } else {
                return success(500, "修改失败，请重试！");
            }
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }

    @PostMapping(value = "/changeDeleteStatus/{status}")
    @ResponseBody
    public BaseResult changeDeleteStatus(@PathVariable String status, String[] ids) {
        try {
            int[] result = iCloudRoleService.changeDeleteStatus(Integer.parseInt(status), ids);
            // 没有失败
            if (result[0] != 0 && result[1] == 0) {
                return success(200, "修改成功！");
            }
            // 有成功的
            else if (result[0] != 0) {
                return success(200, result[0] + "个更新成功，" + result[1] + "个失败！");
            } else {
                return success(500, "修改失败，请重试！");
            }
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }

    @RequestMapping("goShowUser/{id}")
    public String goShowUser(@PathVariable String id, ModelMap map) {
        try {
            CloudRole role = iCloudRoleService.getById(id);
            if (null == role) {
                map.put("code", 500);
                map.put("msg", "可能原因：该角色禁止编辑，该角色已被禁用！");
                return "error/error";
            } else {
                RoleVo roleVo = new RoleVo();
                BeanUtils.copyProperties(roleVo, role);
                map.put("role", roleVo);
                return "cloud/role/role/authUser";
            }
        } catch (Exception e) {
            // 发生异常，一般就是数字转换出错
            System.err.println(e.getMessage());
            return "error/500";
        }
    }

    @PostMapping("/authUser/{type}")
    @ResponseBody
    @AnnotationSaveReLog
    public BaseResult authForUser(@PathVariable("type") String type, String roleId, String[] userIds) {
        try {
            // 添加授权
            if (type.equals("auth")) {
                if (iCloudRoleService.authRoleForUsers(roleId, userIds))
                    return success(200, "添加授权成功！");
                else
                    return error("授权失败，请重试！");
            }
            // 取消授权
            else if (type.equals("revoke")) {
                int[] result = iCloudRoleService.revokeRoleForUsers(roleId, userIds);
                if (result[1] == 0)
                    return success(200, "取消授权成功！");
                else if (result[0] == 0)
                    return error("取消授权失败，请重试！");
                else
                    return success(result[0] + "个用户取消授权成功，" + result[1] + "个失败！");
            }
            return error("访问错误！");
        } catch (Exception e) {
            return error("发生错误：" + e.getMessage());
        }
    }


    @GetMapping("/listForUser/{userId}")
    @ResponseBody
    public BaseResult getRoleListForUser(@PathVariable String userId) {
        try {
            List<RoleTreeDTO> list = new ArrayList<>();
            List<CloudRole> roleList = iCloudRoleService.getListByUserId(Integer.parseInt(userId));
            for (CloudRole cloudRole:roleList) {
                RoleTreeDTO roleTreeDTO = new RoleTreeDTO();
                roleTreeDTO.setId(cloudRole.getId());
                roleTreeDTO.setName(cloudRole.getRoleName());
                list.add(roleTreeDTO);
            }
            return success("获取角色列表成功", list, list.size());
        } catch (Exception e) {
            return error(500, "error:" + e.getMessage());
        }
    }

}
