package com.oauth.system.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.framework.core.excel.listener.AuthExcelModelListener;
import com.framework.core.excel.util.EasyExcelUtils;
import com.framework.core.response.StarBosResult;
import com.framework.core.utils.AuthUtils;
import com.oauth.system.QueryWrapperGenerator;
import com.oauth.system.entity.SysRole;
import com.oauth.system.service.ISysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Api(tags = "角色管理")
@RestController
@Slf4j
@RequestMapping("role")
public class SysRoleController {
    @Autowired
    ISysRoleService roleService;

    @GetMapping("list")
    @ApiOperation(value = "role-分页列表查询", notes = "role-分页列表查询")
    public StarBosResult<IPage<SysRole>> list(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        StarBosResult<IPage<SysRole>> result = new StarBosResult<IPage<SysRole>>();
        Page<SysRole> page = new Page<SysRole>(pageNo, pageSize);
        IPage<SysRole> pageList = roleService.page(page, null);
        result.setCode(200);
        result.setData(pageList);
        return result;
    }


    /**
     * 添加角色
     *
     * @param role
     * @return
     */
    @PostMapping(value = "/add")
    @ApiOperation(value = "添加角色", httpMethod = "POST", produces = "application/json", notes = "添加角色")
    public StarBosResult<SysRole> add(@RequestBody SysRole role) {
        log.info(role.toString());
        StarBosResult<SysRole> result = new StarBosResult<SysRole>();
        try {
            role.setFdate(new Date());
            role.setFcreator(AuthUtils.getUsername());
            roleService.save(role);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    @ApiOperation(value = "删除角色", httpMethod = "DELETE", produces = "", notes = "删除角色")
    public StarBosResult<?> delete(@RequestParam(name = "id", required = true) String id) {
        roleService.deleteRole(id);
        return StarBosResult.ok("删除角色成功");
    }

    /**
     * 编辑
     *
     * @param role
     * @return
     */
    @ApiOperation(value = "编辑角色", httpMethod = "PUT", produces = "", notes = "编辑角色")
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public StarBosResult<?> edit(@RequestBody SysRole role) {
        log.info("\r\n" + role);
        StarBosResult<SysRole> result = new StarBosResult<SysRole>();
        SysRole sysrole = roleService.getById(role.getId());
        if (sysrole == null) {
            result.error500("未找到对应实体");
        } else {
//            role.setUpdateTime(new Date());
            role.setFmodify(AuthUtils.getUsername());
            boolean ok = roleService.updateById(role);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    @ApiOperation(value = "获取全部角色", httpMethod = "GET", produces = "", notes = "获取全部角色")
    @GetMapping(value = "/queryAll")
    public StarBosResult<List<SysRole>> queryAll() {
        StarBosResult<List<SysRole>> result = new StarBosResult<>();
        List<SysRole> list = roleService.list();
        if (list == null || list.size() <= 0) {
            result.error500("未找到角色信息");
        } else {
            result.successOk(list);
        }
        return result;
    }

    @ApiOperation(value = "导出为excel", httpMethod = "GET", produces = "", notes = "导出为excel")
    @GetMapping(value = "/export")
//    @ApiParam(name = "pageNo&pageSize", value = "pageNo&pageSize")
    public void exportExcel( @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                              HttpServletRequest request, HttpServletResponse response) {
        try {
            QueryWrapper<SysRole> queryWrapper = QueryWrapperGenerator.initQueryWrapper(new SysRole(), request);
            //获取数据
            List<SysRole> data = roleService.list(queryWrapper);
            if (CollectionUtils.isEmpty(data)) {
                data.add(new SysRole());
            }
            //attachment指定独立文件下载  不指定则回浏览器中直接打开
            String fileName = "role_列表_" + DateUtil.formatDate(new Date());
//            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            //导出excel
            EasyExcelUtils.exportByExcel(response, data, fileName, SysRole.class);
            log.info("业务订单导出end");
        } catch (Exception e) {
            log.error("业务订单导出异常打印:", e);
        } finally {
            try {
                response.flushBuffer();
            } catch (IOException e) {
                log.error("业务订单导出输出流关闭失败: {}", e);
            }
        }
    }

    @ApiOperation(value = "通过excel导入数据", httpMethod = "POST", produces = "", notes = "通过excel导入数据")
    @PostMapping(value = "/importExcel")
    public void importExcel(@RequestParam("file") MultipartFile multipartFile) {
        try {
            AuthExcelModelListener authExcelModelListener = new AuthExcelModelListener<SysRole>(this.roleService);
            EasyExcel.read(multipartFile.getInputStream(), SysRole.class, authExcelModelListener).doReadAll();
            log.info("excel导入end");
        } catch (Exception e) {
            log.error("excel导入异常打印:", e);
        } finally {
            try {

            } catch (Exception e) {
                log.error("excel导入流关闭失败: {}", e);
            }
        }
    }
}
