package com.cftech.questionnaire.core.papercategory.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.papercategory.model.Papercategory;
import com.cftech.questionnaire.core.papercategory.service.PapercategoryService;
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 PAPERCATEGORY_VIEW = "qy:papercategory:view"
 * 查看:public static final String PAPERCATEGORY_EDIT = "qy:papercategory:edit"
 *
 * @author Neil
 * @date: 2017-05-23 13:24
 */
@Slf4j
@Controller
@RequestMapping("/a/papercategory")
public class PapercategoryController {

    public static final String PAPERCATEGORY_VIEW = "qy:papercategory:view";
    public static final String PAPERCATEGORY_EDIT = "qy:papercategory:edit";
    private final static String rootPCName = SystemConfig.p.getProperty("ROOT_PAPERCATEGORY_NAME");
    @Autowired
    private PapercategoryService papercategoryService;


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

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

    //提交数据（新增、修改）
    @RequiresPermissions(value = PAPERCATEGORY_EDIT)
    @RequestMapping(value = "/formData",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject formData(Papercategory 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());
                Papercategory 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 {
                Papercategory 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 = PAPERCATEGORY_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Papercategory 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<Papercategory> 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 = PAPERCATEGORY_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);
        User user = UserUtils.getUser();
        conds.equal("create_by", user.getId());
        List<Papercategory> 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 (Papercategory 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;
    }

}
