package com.cftech.cms.specialarticle.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.cms.specialarticle.model.SpecialArticle;
import com.cftech.cms.specialarticle.service.SpecialArticleService;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * CMS专题文章管理Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String SPECIALARTICLE_VIEW = "qy:specialArticle:view"
 * 查看:public static final String SPECIALARTICLE_EDIT = "qy:specialArticle:edit"
 *
 * @author lisw
 * @date: 2017-05-04 10:03
 */
@Slf4j
@Controller
@RequestMapping("/a/specialArticle")
public class SpecialArticleController {

    public static final String SPECIALARTICLE_VIEW = "qy:specialArticle:view";
    public static final String SPECIALARTICLE_EDIT = "qy:specialArticle:edit";

    @Autowired
    private SpecialArticleService specialArticleService;


    /**
     * 获取专题已经绑定的文章ID
     * @param id
     * @return
     */
    @RequestMapping(value = "/specialBindArticle/{id}",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject rtnJson(@PathVariable("id") Long id){
        String ids = specialArticleService.getSpecialArticle(id);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("ids",ids);
        return rtnJson;
    }

    /**
     * 为某专题绑定文章
     * @param specialId
     * @param articles
     * @return
     */
    @RequestMapping(value = "specialArticle",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject specialArticle(Long specialId,String articles){
        JSONObject rtnJson = new JSONObject();
        try {
            String [] articlesStr = articles.split(",");
            specialArticleService.saveBatchSpecialArticle(specialId,articlesStr);
            rtnJson.put("errorNo", 0);
        } catch (Exception e) {
            rtnJson.put("errorNo",1);
        }
        return rtnJson;
    }


    //列表页面
    @RequiresPermissions(value = SPECIALARTICLE_VIEW)
    @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST})
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "specialArticle/specialArticlelist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = SPECIALARTICLE_VIEW)
    @RequestMapping(value = "/form",method = {RequestMethod.GET,RequestMethod.POST})
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            SpecialArticle specialArticle = specialArticleService.fetchById(id);
            model.addAttribute("data", specialArticle);
        }
        return "specialArticle/specialArticleform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = SPECIALARTICLE_EDIT)
    @RequestMapping(value = "/formData",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject formData(SpecialArticle specialArticle, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (specialArticle != null && specialArticle.getId() != null) {
                specialArticle.setUpdateBy(UserUtils.getUser().getId());
                specialArticleService.update(specialArticle);
                rtnJson.put("errorNo", 0);
            } else {
                specialArticle.setAccountsId(accountsId);
                specialArticle.setDelFlag(false);
                specialArticle.setAccountsId(UserUtils.getmpaccounts(request));
                specialArticle.setCreateBy(UserUtils.getUser().getId());
                specialArticle.setUpdateBy(UserUtils.getUser().getId());
                specialArticleService.save(specialArticle);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = SPECIALARTICLE_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, SpecialArticle specialArticle, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        if (!StringUtils.isEmpty(specialArticle.getSpecial_id())) {
            conds.equal("special_id", specialArticle.getSpecial_id());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

        List<SpecialArticle> list = specialArticleService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = specialArticleService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //删除数据
    @RequiresPermissions(value = SPECIALARTICLE_EDIT)
    @RequestMapping(value = "/delete",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            specialArticleService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

}
