package com.cftech.questionnaire.core.questionscategory.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.core.util.SystemConfig;
import com.cftech.questionnaire.core.questionscategory.model.Questionscategory;
import com.cftech.questionnaire.core.questionscategory.service.QuestionscategoryService;
import com.cftech.sys.model.User;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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


/**
 * 问题分类Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String QUESTIONSCATEGORY_VIEW = "qy:questionscategory:view"
 * 查看:public static final String QUESTIONSCATEGORY_EDIT = "qy:questionscategory:edit"
 *
 * @author Neil
 * @date: 2017-05-23 13:24
 */
@Slf4j
@Controller
@RequestMapping("/a/questionscategory")
public class QuestionscategoryController {

    public static final String QUESTIONSCATEGORY_VIEW = "qy:questionscategory:view";
    public static final String QUESTIONSCATEGORY_EDIT = "qy:questionscategory:edit";
    private final static String rootQCName = SystemConfig.p.getProperty("ROOT_QUESTIONSCATEGORY_NAME");
    @Autowired
    private QuestionscategoryService papercategoryService;


    //列表页面
    @RequiresPermissions(value = QUESTIONSCATEGORY_VIEW)
    @RequestMapping(value = "/list",method = {RequestMethod.POST,RequestMethod.GET})
    public String list(HttpServletRequest request, Model model) {
        return "questionscategory/questionscategorylist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = QUESTIONSCATEGORY_VIEW)
    @RequestMapping(value = "/form",method = {RequestMethod.POST,RequestMethod.GET})
    public String form(HttpServletRequest request, Questionscategory paperCategory, Model model) {
        Long id=paperCategory.getId();
        if (!StringUtils.isEmpty(id)) {
            paperCategory = papercategoryService.fetchById(id);
            if (paperCategory.getParentId() == 0) {
               paperCategory.setParentName(rootQCName);
            } else {
                Questionscategory parentPaperCategory = papercategoryService.fetchById(paperCategory.getParentId());
                paperCategory.setParentName(parentPaperCategory.getName());
            }
        }
        model.addAttribute("data", paperCategory);
        return "questionscategory/questionscategoryform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = QUESTIONSCATEGORY_EDIT)
    @RequestMapping(value = "/formData",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject formData(Questionscategory papercategory, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (papercategory != null && papercategory.getId() != null) {
                papercategory.setUpdateBy(UserUtils.getUser().getId());
                Questionscategory parentCategory = null;
                if (papercategory.getParentId() != 0) {
                    parentCategory = papercategoryService.fetchById(papercategory.getParentId());
                    papercategory.setParentIds(parentCategory.getParentIds() + papercategory.getId() + ",");
                } else {
                    papercategory.setParentIds("0," + papercategory.getId() + ",");
                }
                papercategoryService.update(papercategory);
                rtnJson.put("errorNo", 0);
            } else {
                Questionscategory parentCategory = null;
                if (!StringUtils.isEmpty(papercategory.getParentId())) {
                    parentCategory = papercategoryService.fetchById(papercategory.getParentId());
                }

                papercategory.setParentIds(parentCategory == null ? 0 + ",": parentCategory.getParentIds());
                papercategory.setAccountsId(accountsId);
                //papercategory.setAccountsId(UserUtils.getmpaccounts(request));
                papercategory.setDelFlag(false);
                papercategory.setCreateBy(UserUtils.getUser().getId());
                papercategory.setUpdateBy(UserUtils.getUser().getId());
                papercategoryService.save(papercategory);
                papercategory.setParentIds(papercategory.getParentIds() + papercategory.getId() + ",");
                papercategoryService.update(papercategory);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = QUESTIONSCATEGORY_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Questionscategory papercategory, HttpServletRequest request) {
        User user = UserUtils.getUser();
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("create_by", user.getId());
        Sort sort = new Sort("create_time", OrderType.DESC);

        Long parentId = null;
        if (papercategory.getParentId() != null) {
            parentId = papercategory.getParentId();
        } else {
            parentId = 0L;
        }


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

    //删除数据
    @RequiresPermissions(value = QUESTIONSCATEGORY_EDIT)
    @RequestMapping(value = "/delete",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject delete(String id) {
        User user = UserUtils.getUser();
        JSONObject rtnJosn = new JSONObject();
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("create_by", user.getId());
        Integer counts = papercategoryService.count(Long.valueOf(id), conds);
        if (counts > 0) {
            rtnJosn.put("errorNo", 2);
            rtnJosn.put("errorMsg", "还有下级分类未删除");
        } else {
            try {
                papercategoryService.delete(id);
                rtnJosn.put("errorNo", 0);
            } catch (Exception e) {
                rtnJosn.put("errorNo", 1);
            }
        }

        return rtnJosn;
    }


    @RequestMapping(value = "treeData",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public JSONObject getTreeData(HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        JSONArray array = new JSONArray();
        Sort sort = new Sort("parent_id", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        if(!UserUtils.isAdmin()){
            conds.equal("create_by", UserUtils.getUser().getId());
        }
        /*User user = UserUtils.getUser();
        conds.equal("create_by", user.getId());*/
        List<Questionscategory> papercategories = papercategoryService.fetchTreeByPage(conds, sort, 0, 0);
        JSONObject t = new JSONObject();
        t.put("id", 0);
        t.put("pId", -1);
        t.put("name", "问题类型");
        t.put("open", true);
        array.add(t);
        for (Questionscategory papercategory : papercategories) {
            JSONObject tmp = new JSONObject();
            tmp.put("id", papercategory.getId());
            tmp.put("pId", papercategory.getParentId());
            tmp.put("name", papercategory.getName());
            array.add(tmp);
        }
        rtnJson.put("aaData", array);
        return rtnJson;
    }

}
