package cn.ftebox.controller.admin;

import cn.ftebox.entity.*;
import cn.ftebox.service.BloggerService;
import cn.ftebox.util.Const;
import cn.ftebox.util.CryptographyUtil;
import cn.ftebox.util.DateUtil;
import cn.ftebox.util.ResponseUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping({"/admin/blogger"})
public class BloggerAdminController {
    @Resource
    private BloggerService bloggerService;


    /**
     * 友情链接列表
     */
    @RequestMapping({"/list.do"})
    public String list(@RequestParam(value = "page", required = false) String page, @RequestParam(value = "rows", required = false) String rows, HttpServletResponse response) throws IOException {
        PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
        Map<String, Object> map = new HashMap<>();
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        // 查询友情链接列表
        List<Link> bloggerList = bloggerService.list(map);
        // 查询总共有多少条数据
        Long total = bloggerService.getTotal(map);
        // 将数据写入response
        org.json.JSONObject result = new org.json.JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(bloggerList);
        result.put("rows", jsonArray);
        result.put("total", total);
        ResponseUtil.write(response, result);
        return null;
    }


    /**
     * 保存用户信息
     */
    @RequestMapping({"/save.do"})
    public String save(@RequestParam("imageFile") MultipartFile imageFile, Blogger blogger, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (!imageFile.isEmpty()) {
            String filePath = request.getServletContext().getRealPath("/");
            String imageName = DateUtil.getCurrentDateStr() + "." + Objects.requireNonNull(imageFile.getOriginalFilename()).split("\\.")[1];
            imageFile.transferTo(new File(filePath + "static/uploader/image/" + imageName));
            blogger.setImageName(imageName);
        }
        int resultTotal = bloggerService.update(blogger);
        StringBuffer result = new StringBuffer();
        if (resultTotal > 0) {
            result.append("<script language='javascript'>alert('修改成功')</script>");
        } else {
            result.append("<script language='javascript'>alert('修改失败')</script>");
        }
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping({"/modify.do"})
    public String save(Blogger blogger, HttpServletResponse response) throws IOException {
        int resultTotal = bloggerService.update(blogger);
        // 将数据写入response
        org.json.JSONObject result = new org.json.JSONObject();
        if (resultTotal > 0) {
            result.put("success", Boolean.valueOf(true));
        } else {
            result.put("success", Boolean.valueOf(true));
        }
        ResponseUtil.write(response, result);
        return null;
    }

    /**
     * 获取博主的JSON格式
     */
    @RequestMapping({"/find.do"})
    public String find(HttpServletResponse response) throws IOException {
        Blogger blogger = (Blogger) SecurityUtils.getSubject().getSession().getAttribute(Const.CURRENT_USER);
        JSONObject result = JSONObject.fromObject(blogger);
        ResponseUtil.write(response, result);
        return null;
    }

    /**
     * 修改密码
     */
    @RequestMapping({"/modifyPassword.do"})
    public String modifyPassword(@RequestParam("id") String id, @RequestParam("newPassword") String newPassword, HttpServletResponse response) throws IOException {
        Blogger blogger = new Blogger();
        blogger.setId(Integer.parseInt(id));
        blogger.setPassword(CryptographyUtil.md5(newPassword, "java1234"));
        int resultTotal = bloggerService.update(blogger);
        JSONObject result = new JSONObject();
        if (resultTotal > 0) {
            result.put("success", Boolean.TRUE);
        } else {
            result.put("success", Boolean.FALSE);
        }
        ResponseUtil.write(response, result);
        return null;
    }

    /**
     * 用户退出
     */
    @RequestMapping({"/logout.do"})
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/login.jsp";
    }

    @RequestMapping({"/delete.do"})
    public String delete(@RequestParam("ids") String ids, HttpServletResponse response) throws IOException {
        String[] idsStr = ids.split(",");
        org.json.JSONObject result = new org.json.JSONObject();
        for (String id : idsStr) {
            bloggerService.delete(Integer.valueOf(id));
        }
        result.put("success", Boolean.TRUE);
        ResponseUtil.write(response, result);
        return null;
    }

    /**
     * 修改角色
     */
    @RequestMapping({"/review.do"})
    public String review(@RequestParam("ids") String ids, @RequestParam("state") String state, HttpServletResponse response) throws IOException {
        String[] idsStr = ids.split(",");
        Blogger blogger = new Blogger();
        for (String id : idsStr) {
            blogger.setId(Integer.parseInt(id));
            blogger.setUserTag(Integer.parseInt(state));
            bloggerService.update(blogger);
        }
        org.json.JSONObject result = new org.json.JSONObject();
        result.put("success", Boolean.TRUE);
        ResponseUtil.write(response, result);
        return null;
    }
}
