ztree 增删递归

package cn.com.shdmt.web.contorller;

import cn.com.shdmt.BizConstants;
import cn.com.shdmt.entity.ProductEntity;
import cn.com.shdmt.entity.ProductTypeEntity;
import cn.com.shdmt.framework.util.Constants;
import cn.com.shdmt.service.ProductService;
import cn.com.shdmt.service.ProductTypeService;
import cn.com.shdmt.web.vo.ProductTypeVo;
import cn.com.shdmt.web.vo.ZtreeVo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.google.common.collect.Lists;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.mapper.JsonMapper;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yaoyao on 2015/1/26.
 */
@Controller
@RequestMapping(value = "/productType")
public class ProductTypeController {

    private static final String PAGE_SIZE = "10";
    private Logger logger = LoggerFactory.getLogger(ProductTypeController.class);

    //当点击其他业务的时候 显示分类列表   有分类的id  标记他的父节点是 其他业务
    //当点击分类id名称 显示业务列表
    //如果没有父节点则显示直接显示 只可以选择叶子节点 不是父节点的都是叶子节点

    @Autowired
    private ProductTypeService productTypeService;
    @Autowired
    private ProductService productService;

    @Value("#{appProperties['upload.config.uploadURL']}")
    private String uploadURL;
    @Value("#{appProperties['upload.config.fileURLPrefix']}")
    private String fileURLPrefix;

    @RequestMapping(method = RequestMethod.GET)
    public String list(
            @RequestParam(value = "page", defaultValue = "1") int pageNumber,
            @RequestParam(value = "order", defaultValue = "") String order,
            @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
            Model model) {
        /*Page<ProductTypeEntity> page = productTypeService.getAllProductType(new PageRequest(pageNumber - 1, pageSize), ViewParamsConvertUtils.getOrder(order));
        if (!StringUtils.isBlank(order)) {
            model.addAttribute("order", order);
        }
        model.addAttribute("page", page);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("fileURLPrefix", fileURLPrefix);*/


        return "productType/productType_list";
    }

    @RequestMapping(value = "doAjax")
    @ResponseBody
    public String doAjax() {

        List<ProductTypeEntity> productTypeEntities = productTypeService.findAllByIsDeleted(Boolean.FALSE);
        List<ZtreeVo> ztreeVos = new ArrayList<ZtreeVo>();
        ZtreeVo zTree = new ZtreeVo();
        zTree.setId(0);
        zTree.setpId(-1);
        zTree.setName("服务分类管理");
        ztreeVos.add(zTree);

        for (ProductTypeEntity p : productTypeEntities) {
            ZtreeVo ztreeVo = new ZtreeVo();
            ztreeVo.setIsParent(!p.getIsLeaf());
            ztreeVo.setId(p.getId().intValue());
            ztreeVo.setpId(p.getParentId());
            ztreeVo.setName(p.getProductTypeName());
            ztreeVos.add(ztreeVo);
        }
        String json = new JsonMapper(JsonInclude.Include.ALWAYS).toJson(ztreeVos);
        return json;
    }


    @RequestMapping(value = "getproductById")
    @ResponseBody
    public ProductTypeVo getproductById(
            @RequestParam(value = "id", required = false) Long id
    ) {
        ProductTypeEntity productTypeEntity = productTypeService.getProductType(id);
        ProductTypeVo productTypeVo = new ProductTypeVo();
        productTypeVo.setProductType(productTypeEntity.getProductType());
        productTypeVo.setProductTypeName(productTypeEntity.getProductTypeName());
        productTypeVo.setDescription(productTypeEntity.getDescription());
        productTypeVo.setImageUrl(fileURLPrefix + productTypeEntity.getImageUrl());
        return productTypeVo;
    }

    @RequestMapping(value = "delById")
    @ResponseBody
    public Map delById(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "isParent", required = false) Boolean isParent
    ) {
        //如果是父节点  则删除他的所有子节点
        //如果是子节点  找到他的父节点  查看他的子节点数目是否大于1  如果不大于1 则把他的父节点变成子节点


        Map map = new HashMap();
        try {

            if (isParent) {
                DecimalToBinary(new Integer(id.intValue()));
                ProductTypeEntity productTypeEntity = productTypeService.getProductType(id);
                productTypeEntity.setIsDeleted(Boolean.TRUE);
                productTypeService.save(productTypeEntity);
            } else {

                ProductTypeEntity productTypeEntity = productTypeService.getProductType(id);
                //得到当前节点的父节点的id
                Integer parentId = productTypeEntity.getParentId();
                List<ProductTypeEntity> productTypeEntities = productTypeService.findAllByParentIdAndIsDeleted(parentId, Boolean.FALSE);
                System.out.println(productTypeEntities.size());
                if (productTypeEntities.size() <= 1) {
                    productTypeEntity.setIsDeleted(Boolean.TRUE);
                    productTypeService.save(productTypeEntity);
                    ProductTypeEntity productTypeEntity1 = productTypeService.getProductType(Long.valueOf(parentId));
                    productTypeEntity1.setIsLeaf(Boolean.TRUE);
                    productTypeService.save(productTypeEntity1);
                }else{
                    productTypeEntity.setIsDeleted(Boolean.TRUE);
                    productTypeService.save(productTypeEntity);
                }
            }


        } catch (Exception e) {
            logger.error("删除失败" + e);
            map.put("fail", "删除失败");
        }
        map.put("suc", "删除成功");
        return map;
    }


    public void DecimalToBinary(Integer id) {
        if (id == -1) {        //当num=0时,循环结束
            return;
        } else {
//            ProductTypeEntity productTypeEntity = productTypeService.getProductType(id);
            //找到该节点的子节点  保存该节点子节点的id 循环调用

            List<ProductTypeEntity> productTypeEntities = productTypeService.findAllByParentId(id);

            //如果有子节点 删除并记录子节点
            if (!productTypeEntities.isEmpty()) {

                for (ProductTypeEntity p1 : productTypeEntities) {
                    p1.setIsDeleted(Boolean.TRUE);
                    productTypeService.save(p1);
                }
                Integer parentId = new Integer(productTypeEntities.get(0).getId().intValue());
                DecimalToBinary(parentId);
            }
            id = -1;
        }
    }

    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("productType", productTypeService.getProductType(id));
        model.addAttribute("action", "update");
        return "productType/productType_edit";
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String createForm(Model model) {
        ProductTypeEntity productType = new ProductTypeEntity();
        productType.setSortNo(0);
        model.addAttribute("productType", productType);
        model.addAttribute("action", "create");
        return "productType/productType_edit";
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String create(@Valid ProductTypeEntity newProduct,
                         @RequestParam(value = "id", required = false) Long id,
                         @RequestParam(value = "isParent", required = false) Boolean isParent,
                         @RequestParam(value = "productTypeImageFile", required = false) MultipartFile productTypeImageFile,
                         RedirectAttributes redirectAttributes, HttpSession session) {
        String idStr = Constants.EMPTY_STRING;
        String filePath = null;
        //如果是父节点  则单纯添加一个子节点 他的父节点id 为treenode.id
        //如果是子节点treenode.id改为父节点 并且添加一个子节点他的父节点id为treenode.id
        if (productTypeImageFile != null && !productTypeImageFile.isEmpty()) {
            filePath = upload(productTypeImageFile, redirectAttributes, session);
        }
        if (id == null) {
            try {
                if (!isParent) {
                    ProductTypeEntity productTypeEntity = productTypeService.getProductType(Long.valueOf(newProduct.getParentId()));
                    productTypeEntity.setIsLeaf(Boolean.FALSE);
                    productTypeService.save(productTypeEntity);
                }
                newProduct.setImageUrl(filePath);
                newProduct.setIsLeaf(Boolean.TRUE);
                productTypeService.save(newProduct);
                redirectAttributes.addFlashAttribute("message", "创建服务类型成功");
            } catch (Exception e) {
                logger.error("创建服务类型失败", e);
                redirectAttributes.addFlashAttribute("error", "创建服务类型失败");
            }
        } else {
            ProductTypeEntity productTypeEntity = null;
            try {
                productTypeEntity = productTypeService.getProductType(id);
                productTypeEntity.setDescription(newProduct.getDescription());
                productTypeEntity.setProductType(newProduct.getProductType());
                productTypeEntity.setProductTypeName(newProduct.getProductTypeName());
                productTypeEntity.setImageUrl(filePath);
                productTypeService.save(productTypeEntity);
                idStr = productTypeEntity.getId().toString();
                redirectAttributes.addFlashAttribute("message", "更新服务类型【" + productTypeEntity.getProductTypeName() + "】成功");
            } catch (Exception e) {
                logger.error("更新服务类型失败", e);
                redirectAttributes.addFlashAttribute("error", "更新服务类型{" + productTypeEntity.getProductTypeName() + "}失败");
            }
        }
        return "redirect:/productType/" + idStr;
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(@Valid @ModelAttribute("productType") ProductTypeEntity productTypeEntity,
                         @RequestParam(value = "productTypeImageFile", required = false) MultipartFile productTypeImageFile,
                         RedirectAttributes redirectAttributes, HttpSession session) {
        String idStr = Constants.EMPTY_STRING;
        try {

            String filePath = null;
            if (productTypeImageFile != null && !productTypeImageFile.isEmpty()) {
                filePath = upload(productTypeImageFile, redirectAttributes, session);
            }
            productTypeEntity.setImageUrl(filePath);
            productTypeService.save(productTypeEntity);
            idStr = productTypeEntity.getId().toString();
            redirectAttributes.addFlashAttribute("message", "更新服务类型【" + productTypeEntity.getProductTypeName() + "】成功");
        } catch (Exception e) {
            logger.error("更新服务类型失败", e);
            redirectAttributes.addFlashAttribute("error", "更新服务类型{" + productTypeEntity.getProductTypeName() + "}失败");
        }
        return "redirect:/productType/" + idStr;
    }

    //上传文件
    private String upload(MultipartFile knowledgeFile, RedirectAttributes redirectAttributes, HttpSession session) {
        String filePath = null;
        try {
            // 保存文件
            String fileName = knowledgeFile.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName) && !knowledgeFile.isEmpty()) {
                //生成转发URL
                String url = uploadURL;
                //保存到本地
                File tempFile = new File(System.getProperty("java.io.tmpdir") + "/" + session.getId() +
                        fileName.substring(fileName.lastIndexOf('.')).toLowerCase());
                FileUtils.writeByteArrayToFile(tempFile, knowledgeFile.getBytes());
                //读取图片
                RestTemplate rest = new RestTemplate();
                FileSystemResource resource = new FileSystemResource(tempFile);

                MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
                //文件
                param.add("file", resource);
                //验证字符串
                param.add("validateString", BizConstants.UPLOAD_FILE_VALIDATE_STRING);
                //模块名,用于生成模块目录
                param.add("modeName", "link");
                //可选参数 fileType 文件类型,用于验证文件类型list,小写,默认{".jpg","png","gif"}
                //             fileMaxSize 文件大小上限Long,默认80000
                Map<String, String> message = rest.postForObject(url, param, Map.class);
                //删除临时文件
                if (tempFile.exists()) {
                    tempFile.delete();
                }
                if (message.containsKey("error")) {
                    redirectAttributes.addFlashAttribute("message", message.get("error"));
                }
                filePath = message.get("filePath");
            }
        } catch (Exception ex) {
            logger.error("获取图片路径失败", ex);
        }
        return filePath;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String info(@PathVariable("id") long id, Model model) {
        ProductTypeEntity productTypeEntity = productTypeService.getProductType(id);
        model.addAttribute("productType", productTypeEntity);
        model.addAttribute("fileURLPrefix", fileURLPrefix);
        return "productType/productType_info";
    }

    @RequestMapping(value = "delete/{id}")
    public String delete(@PathVariable("id") Long id, Model model, RedirectAttributes redirectAttributes) {
        ProductTypeEntity productTypeEntity = productTypeService.getProductType(id);
        //如果服务分类下有服务  提示不能删除
        List<ProductEntity> productEntities = productService.findByProductTypeAndIsDeleted(productTypeEntity,Boolean.FALSE);
        if (productEntities.size() > 0) {
            redirectAttributes.addFlashAttribute("error", "删除服务类型" + productTypeEntity.getProductTypeName() + "失败,该服务类型下存在未删除的服务");
            return "redirect:/productType";
        }
        model.addAttribute("fileURLPrefix", fileURLPrefix);
        productTypeEntity.setIsDeleted(Boolean.TRUE);//true 1 删除
        productTypeService.save(productTypeEntity);
        redirectAttributes.addFlashAttribute("message", "删除服务类型" + productTypeEntity.getProductTypeName() + "成功");
        return "redirect:/productType";
    }

    @RequestMapping(value = "batchDel")
    public String delete(@RequestParam(value = "productTypeId", required = false) Long[] productTypeId,
                         Model model, RedirectAttributes redirectAttributes) {
        List<String> stringList = Lists.newArrayList();
        if (productTypeId != null && productTypeId.length > 0) {
            List<ProductTypeEntity> productTypeEntities = productTypeService.getProductTypes(productTypeId);
            for (ProductTypeEntity productTypeEntity : productTypeEntities) {
                List<ProductEntity> productEntities = productService.findByProductTypeAndIsDeleted(productTypeEntity,Boolean.FALSE);
                if (productEntities.size() > 0) {
                    //存在预约单的  保留名字 提示客户哪些失败了
                    stringList.add(productTypeEntity.getProductTypeName());
                } else {
                    productTypeEntity.setIsDeleted(Boolean.TRUE);//true 1 删除
                    productTypeService.save(productTypeEntity);
                }
            }
        }
        if (stringList != null && stringList.size() > 0) {
            redirectAttributes.addFlashAttribute("error", "删除服务类型" + org.springframework.util.StringUtils.collectionToDelimitedString(stringList, ",") + "失败,该服务类型下存在未删除的服务,其他勾选成功删除");
        } else {
            redirectAttributes.addFlashAttribute("message", "删除服务类型成功");
        }
        model.addAttribute("fileURLPrefix", fileURLPrefix);
        return "redirect:/productType";
    }

    @ModelAttribute
    public void getProduct(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
        if (id != -1) {
            model.addAttribute("productType", productTypeService.getProductType(id));
        }
    }
}



jsp:

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springside.org.cn/tags/form" %>
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<html>
<head>
    <title>服务分类维护</title>
    <link href="${ctx}/static/zTree/css/zTreeStyle/zTreeStyle.css" media="screen" rel="stylesheet"/>
    <script type="text/javascript" src="${ctx}/static/zTree/js/jquery.ztree.core-3.5.min.js"></script>
    <script type="text/javascript" src="${ctx}/static/zTree/js/jquery.ztree.excheck-3.5.min.js"></script>
    <script type="text/javascript" src="${ctx}/static/zTree/js/jquery.ztree.exedit-3.5.js"></script>
    <style>

        .addLeaf {
            border: 1px solid #DDD;
            background-color: #F5F5F5;
            color: #ACA899;
        }


    </style>
</head>
<body>

<%--<div  id="activation_city_list" class="ztree"></div>
<input type="hidden" name="cityIds" id="cityIds"/>--%>

[ <a id="addLeaf" href="#" title="增加节点" οnclick="return false;">增加服务分类</a> ]
[ <a id="edit" href="#" title="编辑节点" οnclick="return false;">编辑服务分类</a> ]
[ <a id="info" href="#" title="查看节点" οnclick="return false;">查看服务分类</a> ]
[ <a id="del" href="#" title="删除节点" οnclick="return false;">删除服务分类</a> ]


<div style="float:left;">
    <ul id="treeDemo" class="ztree">
    </ul>
</div>


<!-- 模态框(Modal) -->
<div class="modal hide fade" id="modelSave" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close"
                        data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title">
                    添加
                </h4>
            </div>
            <div class="modal-body" style="max-height: 350px;">
                <%--=======--%>
                <div class="well">
                    <form:form id="edit_custom_form" modelAttribute="productType" action="${ctx}/productType/create"
                               method="post"
                               enctype="multipart/form-data" class="form-horizontal">
                        <input type="hidden" name="id" id="id"/>
                        <input type="hidden" id="pid" name="parentId">
                        <input type="hidden" id="isParent" name="isParent">
                        <fieldset>

                            <div class="ui-state-default">
                                <b>基本信息</b>
                            </div>
                            <div class="well well-small">

                                <div class="control-group">
                                    <label for="productType" class="control-label">服务分类编号:</label>

                                    <div class="controls">
                                        <input id="productType" style="width: 200px" name="productType" type="number"
                                               maxlength="20" class="input-large required"/>
                                        <span style="color: red">*</span>
                                    </div>
                                </div>

                                <div class="control-group">
                                    <label for="productTypeName" class="control-label">服务分类名称:</label>

                                    <div class="controls">
                                        <input id="productTypeName" style="width: 200px" name="productTypeName"
                                               type="text"
                                               maxlength="20" class="input-large required"/>
                                        <span style="color: red">*</span>
                                    </div>
                                </div>

                                <div class="control-group">
                                    <label for="productTypeImage" class="control-label">服务分类图片:</label>

                                    <div class="controls">
                                        <input type="file" id="productTypeImage" name="productTypeImageFile"
                                               class="input-large"/>
                                        <span style="color: red">*</span>
                                    </div>
                                </div>

                                <div class="control-group">
                                    <label for="description" class="control-label">服务分类描述:</label>

                                    <div class="controls">
                                        <input id="description" style="width: 200px" name="description" type="text"
                                               maxlength="20" class="input-large required"/>
                                        <span style="color: red">*</span>
                                    </div>
                                </div>

                                <div class="form-actions">
                                    <input class="btn btn-primary" style="width: 80px;float: left" type="submit"
                                           value="提交"/>
                                </div>
                            </div>
                        </fieldset>
                    </form:form>
                </div>

                <%--=======--%>

            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal -->
</div>


<!-- 模态框(Modal) -->
<%--查看--%>
<div class="modal hide fade" id="modelInfo" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close"
                        data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title">
                    查看
                </h4>
            </div>
            <div class="modal-body" style="max-height: 350px;">
                <%--=======--%>

                <div class="well">
                    <div class="ui-state-default">
                        <b>基本信息</b>
                    </div>
                    <table class="well table">

                        <tr>
                            <th>
                                服务分类编号:
                            </th>
                            <td id="info_productType">
                            </td>
                        </tr>

                        <tr>
                            <th>
                                服务分类名称:
                            </th>
                            <td id="info_productTypeName">
                            </td>
                        </tr>

                        <tr>
                            <th>
                                服务分类图片:
                            </th>
                            <td id="info_imageUrl">

                            </td>
                        </tr>

                        <tr>
                            <th>
                                服务分类描述:
                            </th>
                            <td id="info_description">
                            </td>
                        </tr>

                    </table>
                </div>


                <%--=======--%>

            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal -->
</div>


<script>

//==


var setting = {
    view: {
        selectedMulti: false        //禁止多点选中
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pId",
            rootPId: ""
        }
    },
    callback: {
        onRename: onRename,//编辑后触发,用于操作后台
        beforeDrag: beforeDrag,
        beforeRemove: beforeRemove,
        beforeRename: beforeRename,
        onClick: zTreeOnClick
    }
};

function zTreeOnClick(event, treeId, treeNode) {
    if (treeNode.isParent) {
        //如果是父节点
//        $("#addLeaf").removeClass("addLeaf");
        $("#edit").addClass("addLeaf");
        $("#info").addClass("addLeaf");
//        $("#del").addClass("addLeaf");
    } else {
//        $("#addLeaf").addClass("addLeaf");
        $("#edit").removeClass("addLeaf");
        $("#info").removeClass("addLeaf");
//        $("#del").removeClass("addLeaf");
    }
}
;

var log, className = "dark";
function beforeDrag(treeId, treeNodes) {
    return false;
}
function beforeRemove(treeId, treeNode) {
    className = (className === "dark" ? "" : "dark");
    showLog("[ " + getTime() + " beforeRemove ] " + treeNode.name);
    return confirm("确认删除 节点 -- " + treeNode.name + " 吗?");
}
function onRemove(e, treeId, treeNode) {
    showLog("[ " + getTime() + " onRemove ] " + treeNode.name);
}
function beforeRename(treeId, treeNode, newName) {
    if (newName.length == 0) {
        alert("节点名称不能为空.");
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        setTimeout(function () {
            zTree.editName(treeNode)
        }, 10);
        return false;
    }
    return true;
}
function showLog(str) {
    if (!log) log = $("#log");
    log.append("<li class='" + className + "'>" + str + "</li>");
    if (log.children("li").length > 8) {
        log.get(0).removeChild(log.children("li")[0]);
    }
}
function getTime() {
    var now = new Date(),
            h = now.getHours(),
            m = now.getMinutes(),
            s = now.getSeconds(),
            ms = now.getMilliseconds();
    return (h + ":" + m + ":" + s + " " + ms);
}

var newCount = 1;

function add(e) {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
            isParent = e.data.isParent,
            nodes = zTree.getSelectedNodes(),
            treeNode = nodes[0];
    if (typeof(treeNode) != "undefined") {
        if (treeNode.isParent) {
            $("#pid").val(treeNode.id);//拿到父节点的id填写名称后保存 重新加载
            $("#isParent").val(treeNode.isParent);
            $("#id").val("");
            $("#productType").val("");
            $("#productTypeName").val("");
            $("#description").val("");
            //当点击添加的时候弹出框
            $("#modelSave").modal('show');
            onloadZTree();
        } else {
            //当前选中的节点   treeNode.id  变成父节点 并添加一个他的子节点
            $("#pid").val(treeNode.id);//拿到父节点的id填写名称后保存 重新加载
            $("#id").val("");
            $("#isParent").val(treeNode.isParent);
            $("#productType").val("");
            $("#productTypeName").val("");
            $("#description").val("");
            //当点击添加的时候弹出框
            $("#modelSave").modal('show');

        }
    } else {

    }
}
;

function info(e) {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
            isParent = e.data.isParent,
            nodes = zTree.getSelectedNodes(),
            treeNode = nodes[0];
    if (typeof(treeNode) != "undefined") {

        if (treeNode.isParent) {

        } else {
            //根据id 进行 ajax
            var data = {id: treeNode.id};
            $.ajax({
                cache: false, //是否使用缓存
                type: 'post', //请求方式,post
                data: data,
                dataType: "json", //数据传输格式
                url: "${ctx}/productType/getproductById", //请求链接
                error: function () {
                    alert('加载出错!');
                },
                success: function (data) {
                    if (data != null) {
                        $("#info_productType").text(data.productType);
                        $("#info_productTypeName").text(data.productTypeName);
                        $("#info_imageUrl").html("<img src='${fileURLPrefix}" + data.imageUrl + "' style='width: 66; height: 56px;'>");
                        $("#info_description").text(data.description);
                        $("#modelInfo").modal('show');
                    } else {
                        alert("加载出错");
                    }
                }
            });
        }
    } else {

    }
}

function edit(e) {

    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
            isParent = e.data.isParent,
            nodes = zTree.getSelectedNodes(),
            treeNode = nodes[0];
    if (typeof(treeNode) != "undefined") {

        if (!treeNode.isParent) {

            //根据id 进行 ajax
            var data = {id: treeNode.id};
            $.ajax({
                cache: false, //是否使用缓存
                type: 'post', //请求方式,post
                data: data,
                dataType: "json", //数据传输格式
                url: "${ctx}/productType/getproductById", //请求链接
                error: function () {
                    alert('加载出错!');
                },
                success: function (data) {
                    if (data != null) {
                        $("#id").val(treeNode.id);
                        $("#productType").val(data.productType);
                        $("#productTypeName").val(data.productTypeName);
                        $("#description").val(data.description);
                        $("#modelSave").modal('show');
                    } else {
                        alert("加载出错");
                    }
                }
            });
        }
    }

}

function del(e) {

    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
            isParent = e.data.isParent,
            nodes = zTree.getSelectedNodes(),
            treeNode = nodes[0];
    if (typeof(treeNode) != "undefined") {
           var data;
        if (!treeNode.isParent) {
            //根据id 进行 ajax
            data = {id: treeNode.id, isParent: treeNode.isParent};
        } else {
            data = {id: treeNode.id, isParent: treeNode.isParent};
        }

        $.ajax({
            cache: false, //是否使用缓存
            type: 'post', //请求方式,post
            data: data,
            dataType: "json", //数据传输格式
            url: "${ctx}/productType/delById", //请求链接
            success: function (data) {
                if (data["suc"] != null) {
                    alert(data["suc"]);
                    onloadZTree();
                } else {
                    alert(data["fail"]);
                }
            }
        });
    }
}


function onRename(e, treeId, treeNode, isCancel) {
    //当编辑完成后
    return treeNode.name;
}


//用于捕获分类编辑名称结束(Input 失去焦点 或 按下 Enter 键)之后,更新分类名称数据之前的事件回调函数
function beforeRename(treeId, treeNode, newName) {
    if (newName.length == 0 || newName.indexOf("请输入名称") >= 0) {
        alert('亲,请输入分类名称!');
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        setTimeout(function () {
            zTree.editName(treeNode)
        }, 10);
        return false;
    }
    if (newName.length > 15) {
        alert('亲,分类名称过长!');
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        setTimeout(function () {
            zTree.editName(treeNode)
        }, 10);
        return false;
    }
    native_name = treeNode.name;
    return true;
}
;


//加载ztree
function onloadZTree() {
    var ztreeNodes;
    $.ajax({
        async: true, //是否异步
        cache: false, //是否使用缓存
        type: 'post', //请求方式,post
        dataType: "json", //数据传输格式
        url: "${ctx}/productType/doAjax", //请求链接
        error: function () {
            alert('网络出错!');
        },
        success: function (data) {
            ztreeNodes = data; //将string类型转换成json对象
            var treeObj = $.fn.zTree.init($("#treeDemo"), setting, ztreeNodes);
            treeObj.expandAll(true);
            zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo");
        }
    });
}

//初始化操作
$(document).ready(function () {
    onloadZTree();
    $("#addLeaf").bind("click", {isParent: false}, add);
    $("#info").bind("click", {isParent: false}, info);
    $("#edit").bind("click", {isParent: false}, edit);
    $("#del").bind("click", {isParent: false}, del);
});

</script>

<%--<tags:pagination page="${page}" paginationSize="${pageSize}"/>--%>
</body>
</html>



 

转载于:https://www.cnblogs.com/yaoyao66123/p/4397617.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值