package cn.ftebox.controller.admin;

import cn.ftebox.entity.Link;
import cn.ftebox.entity.PageBean;
import cn.ftebox.service.LinkService;
import cn.ftebox.util.ResponseUtil;
import net.sf.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 友情链接管理
 */
@Controller
@RequestMapping({"/admin/link"})
public class LinkAdminController {
    @Resource
    private LinkService linkService;

    /**
     * 友情链接列表
     */
    @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> linkList = linkService.list(map);
        // 查询总共有多少条数据
        Long total = linkService.getTotal(map);
        // 将数据写入response
        JSONObject result = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(linkList);
        result.put("rows", jsonArray);
        result.put("total", total);
        ResponseUtil.write(response, result);
        return null;
    }

    /**
     * 保存友情链接信息
     */
    @RequestMapping({"/save.do"})
    public String save(Link link, HttpServletResponse response) throws IOException {
        int resultTotal = 0;
        if (link.getId() == null) {
            // 添加
            resultTotal = linkService.add(link);
        } else {
            // 更新
            resultTotal = linkService.update(link);
        }

        // 将数据写入response
        JSONObject result = new JSONObject();
        if (resultTotal > 0) {
            result.put("success", Boolean.valueOf(true));
        } else {
            result.put("success", Boolean.valueOf(true));
        }
        ResponseUtil.write(response, result);
        return null;
    }

    /**
     * 删除友情链接
     */
    @RequestMapping({"/delete.do"})
    public String delete(@RequestParam("ids") String ids, HttpServletResponse response) throws IOException {
        String[] idsStr = ids.split(",");
        JSONObject result = new JSONObject();
        for (String id : idsStr) {
            linkService.delete(Integer.valueOf(id));
        }
        result.put("success", Boolean.TRUE);
        ResponseUtil.write(response, result);
        return null;
    }

}
