package com.cftech.cos.uploader.category.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.cos.uploader.category.model.MaterialCategory;
import com.cftech.cos.uploader.category.service.MaterialCategoryService;
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.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/materialCategory")
public class MaterialCategoryController {

    public static final String MATERIALCATEGORY_VIEW = "qy:materialCategory:view";
    public static final String MATERIALCATEGORY_EDIT = "qy:materialCategory:edit";
    private final static String rootQCName = SystemConfig.p.getProperty("ROOT_MATERIALCATEGORY_NAME");
    @Autowired
    private MaterialCategoryService materialCategoryService;


    //列表页面
    @RequiresPermissions(value = MATERIALCATEGORY_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model) {
        return "materialCategory/materialcategorylist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = MATERIALCATEGORY_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, MaterialCategory paperCategory, Model model) {
        Long id=paperCategory.getId();
        if (!StringUtils.isEmpty(id)) {
            paperCategory = materialCategoryService.fetchById(id);
            if (paperCategory.getParentId() == 0) {
                paperCategory.setParentName(rootQCName);
            } else {
                MaterialCategory parentPaperCategory = materialCategoryService.fetchById(paperCategory.getParentId());
                paperCategory.setParentName(parentPaperCategory.getName());
            }
        }
        model.addAttribute("data", paperCategory);
        return "materialCategory/materialcategoryform";
    }

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

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

    //获取列表数据
    @RequiresPermissions(value = MATERIALCATEGORY_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, MaterialCategory materialCategory, HttpServletRequest request) {
        //User user = UserUtils.getUser();
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        /*conds.equal("create_by", user.getId());*/
        conds.equal("accounts_id",UserUtils.getmpaccounts(request));
        Sort sort = new Sort("create_time", OrderType.DESC);
        JSONObject rtnJson = new JSONObject();
        try{
            Long parentId = null;
            if (materialCategory.getParentId() != null) {
                parentId = materialCategory.getParentId();
            } else {
                parentId = 0L;
            }

            List<MaterialCategory> list = materialCategoryService.fetchSearchByPage(parentId, conds, sort, iDisplayStart, iDisplayLength);
            Integer counts = materialCategoryService.count(parentId, conds);
            rtnJson.put("iTotalRecords", counts);
            rtnJson.put("iTotalDisplayRecords", counts);
            rtnJson.put("aaData", list);
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return rtnJson;
    }


    //删除数据
    @RequiresPermissions(value = MATERIALCATEGORY_EDIT)
    @RequestMapping("/delete")
    @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 = materialCategoryService.count(Long.valueOf(id), conds);
        if (counts > 0) {
            rtnJosn.put("errorNo", 2);
            rtnJosn.put("errorMsg", "还有下级分类未删除");
        } else {
            try {
                materialCategoryService.deleteAndFile(id);

                rtnJosn.put("errorNo", 0);
            } catch (Exception e) {
                rtnJosn.put("errorNo", 1);
            }
        }

        return rtnJosn;
    }


    @RequestMapping("treeData")
    @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);
        conds.equal("accounts_id", UserUtils.getmpaccounts(request));
        List<MaterialCategory> papercategories = materialCategoryService.fetchTreeByPage(conds, sort, 0, 0);
        JSONObject t = new JSONObject();
        t.put("id", 0);
        t.put("pId", -1);
        t.put("name", rootQCName);
        t.put("open", true);
        array.add(t);
        for (MaterialCategory materialCategory : papercategories) {
            JSONObject tmp = new JSONObject();
            tmp.put("id", materialCategory.getId());
            tmp.put("pId", materialCategory.getParentId());
            tmp.put("name", materialCategory.getName());
            array.add(tmp);
        }
        rtnJson.put("aaData", array);
        return rtnJson;
    }

}
