使用dhtmlxgantt制作任务进度表

记录一下

一.下载所需资料

二.前端代码

<html>
<head>
	<meta http-equiv="Content-type" content="text/html; charset=utf-8">
	<title>甘特图</title>
	<script src="${ctxPath}/assets/codebase/dhtmlxgantt.js"></script>
	<link rel="stylesheet" href="${ctxPath}/assets/codebase/skins/dhtmlxgantt_terrace.css">
	<link rel="stylesheet" href="${ctxPath}/assets/codebase/dhtmlxgantt.css">
	<link rel="stylesheet" href="${ctxPath}/assets/common/libs/layui/css/layui.css?v=${constants.getReleaseVersion()}"/>
	<script src="${ctxPath}/assets/common/libs/jquery/jquery-3.2.1.min.js"></script>
	<script src="${ctxPath}/assets/codebase/common/testdata.js"></script>//gantt自带的数据
	<script src="${ctxPath}/assets/codebase/chosen.jquery.js"></script> //下拉框所需js
	<link rel="stylesheet"href="${ctxPath}/assets/codebase/chosen.css">	//下拉框所需js
	<style>
		 html, body {
			 padding: 0px;
			 margin: 0px;
			 height: 100%;
		 }

		#gantt_here {
			width:100%;
			height:100%;
		}

		.gantt_grid_scale .gantt_grid_head_cell,
		.gantt_task .gantt_task_scale .gantt_scale_cell {
			font-weight: bold;
			font-size: 14px;
			color: rgba(0, 0, 0, 0.7);
		}
		.owner-label{
			width: 20px;
			height: 20px;
			line-height: 20px;
			font-size: 12px;
			display: inline-block;
			border: 1px solid #cccccc;
			border-radius: 25px;
			background: #e6e6e6;
			color: #6f6f6f;
			margin: 6px 3px;
			font-weight: bold;
		}
		.gantt_cal_larea{
			overflow:visible;
		}
		.gantt_cal_chosen,
		.gantt_cal_chosen select{
			width: 400px;
		}
	</style>
</head>
<body>
<div id="gantt_here" style='width:100%; height:100%;'>
	<input type="hidden" id="projectId" value="${projectId}">
</div>
<script>
    // 自定义日期语言
    gantt.locale={
        date: {
            month_full: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            month_short: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
            day_full: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
            day_short: ["日", "一", "二", "三", "四", "五", "六"]
        },
        labels: {
			month_tab: "月",
            week_tab: "周",
			day_tab: "日",
			dhx_cal_today_button: "今天",
			new_event: "新建日程",
            icon_save: "保存",
            icon_cancel: "关闭",
            icon_details: "详细",
            icon_edit: "编辑",
            icon_delete: "删除",
            confirm_closing: "请确认是否撤销修改!", //Your changes will be lost, are your sure?
            confirm_deleting: "是否删除日程?",
            section_description: "描述",
            section_time: "时间范围",
            section_type: "类型",


            /* grid columns */
            column_text: "任务名",
            column_start_date: "开始时间",
            column_duration: "持续时间",
            column_add: "",

            /* link confirmation */
            link: "关联",
            confirm_link_deleting: "将被删除",
            link_start: " (开始)",
            link_end: " (结束)",

            type_task: "任务",
            type_project: "项目",
            type_milestone: "里程碑",

			years: "年",
			months: "月",
			days: "天",
			weeks: "周",
			hours: "小时",
			minutes: "分钟"
        }
    };

    var textEditor = {type: "text", map_to: "text"};

	// 定义lightbox弹出框
	gantt.form_blocks["multiselect"] = {
		render: function (sns) {
			var height = (sns.height || "23") + "px";
			var html = "<div class='gantt_cal_ltext gantt_cal_chosen gantt_cal_multiselect' style='height:" + height + ";'><select data-placeholder='...' class='chosen-select' multiple>";
			if (sns.options) {
				for (var i = 0; i < sns.options.length; i++) {
					if(sns.unassigned_value !== undefined && sns.options[i].key == sns.unassigned_value){
						continue;
					}
					html += "<option value='" + sns.options[i].key + "'>" + sns.options[i].label + "</option>";
				}
			}
			html += "</select></div>";
			return html;
		},
		set_value: function (node, value, ev, sns) {
			node.style.overflow = "visible";
			node.parentNode.style.overflow = "visible";
			node.style.display = "inline-block";
			var select = $(node.firstChild);

			if (value) {
				value = (value + "").split(",");
				select.val(value);
			}else {
				select.val([]);
			}

			select.chosen();
			if(sns.onchange){
				select.change(function(){
					sns.onchange.call(this);
				})
			}
			select.trigger('chosen:updated');
			select.trigger("change");
		},
		get_value: function (node, ev) {
			var value = $(node.firstChild).val();
			return value;
		},
		focus: function (node) {
			$(node.firstChild).focus();
		}
	};
	//获取所有参与人
	var arr=[]
	$.post("/mgr/all",function(data){
		for (var i = 0; i < data.length; i++) {
			var arrs= {
				key :data[i].userId,
				label : data[i].name,
			}
			arr.push(arrs);
		}
	});
	//回显参与人名称
	function findUser(id){
		for(var i = 0; i < arr.length; i++){
			if(arr[i].key == id){
				return arr[i];
			}
		}
		return null;
	}
	gantt.config.columns = [
		{name: "id", label: "序号",align: "center",width: 40, template: gantt.getWBSCode, resize:true},
		{name: "text", label: "名称",  align: "center", tree: true,width: 180,editor: textEditor, resize:true},
		{name: "start_date", label:"开始时间",align: "center", width: 90,resize:true},
		{name: "end_date", label:"结束时间",align: "center",width: 90, template: function(task){
				return gantt.templates.date_grid(task.end_date, task);
			}, resize:true},
        {name: "users", label: "参与人",align: "center",width: 180,template: function (task) {
				if (task.type == gantt.config.types.project) {
					return "";
				}
				var result = "";
				var users =task.users;
				/*var users = ["1","118"];*/
				if (!users || !users.length) {
					return "Unassigned";
				}
				if(users.length == 1){
					return findUser(users[0]).label;
				}
				$.each(users, function(i,val){
					var user = findUser(val);
					if (!user)return;
					result += "<div class='owner-label' title='" + user.label + "'>" + user.label.substr(0, 1)  + "</div>";
				});
				return result;
			},resize:true},
		{name: "duration", label: "<h4 style='font-weight:bold;color: #7e7e7e'>天数</h4>",align: "center",width: 80,resize:true},
		{name: "add", width: 44}
	];
	gantt.config.scale_unit = "day";
    gantt.config.scale_height = 20*2;//设置甘特图的表头高度
    gantt.config.min_column_width = 80;//设置甘特图的表头高度
    // 行高
    // gantt.config.row_height=200;
    
    // 月份横坐标
    gantt.config.subscales = [{ unit:"month", step:1, date:"%Y ,%M"	}];
    gantt.config.date_scale = "%d 日";

    gantt.config.layout = {
        css: "gantt_container",
        cols: [
            {
                width:500,
                min_width: 300,
                rows:[
                    {view: "grid", scrollX: "gridScroll", scrollable: true, scrollY: "scrollVer",width:500},
                    {view: "scrollbar", id: "gridScroll", group:"horizontal"}
                ]
            },
            {resizer: true, width: 1},
            {
                rows:[
                    {view: "timeline", scrollX: "scrollHor", scrollY: "scrollVer"},
                    {view: "scrollbar", id: "scrollHor", group:"horizontal"}
                ]
            },
            {view: "scrollbar", id: "scrollVer"}
        ]
    };


	// 当task的长度改变时,自动调整图表坐标轴区间用于适配task的长度
	gantt.config.fit_tasks = true;

	//自定义弹框
	gantt.locale.labels.section_users = "参与人";
	gantt.config.lightbox.sections = [
		{name: "description", height: 70, map_to: "text", type: "textarea", focus: true},
		{name:"users",height:70, type:"multiselect", options:arr,
			map_to:"users", unassigned_value:10},
		{name: "time", height: 40, type: "time", map_to: "auto", time_format: ["%Y", "%m", "%d"]}/*按开始日期-结束日期显示*/
	];

    /*// 计算日期
    gantt.attachEvent("onParse", function() {
        gantt.eachTask(function(task) {
            // fill 'task.user' field with random data
            //console.dir( gantt.config.columns);
            task.user = Math.round(Math.random()*3);
            //
            if (gantt.hasChild(task.id))
                task.type = gantt.config.types.project
        });
    });*/

	var tasks={
		data:[],
		links:[]
	};
	var projectId=$("#projectId").val();
	init=function (){
		$.get("/ganttTasks/detail",{ projectId:projectId},function(json){
			for(var i = 0;i<json.data.length;i++){
				var user=json.data[i].users.split(',');
				tasks.data.push({
					id: json.data[i].ganttId,
					ganttId:json.data[i].ganttId,
					text: json.data[i].text,
					start_date: json.data[i].startDate.substring(0,10).split('-').reverse().join('-') ,//转成可识别的日期
					duration:json.data[i].duration,
					users:user,
					progress: json.data[i].progress,
					parent: json.data[i].parent,
					open:true
				});
			}
			gantt.parse(tasks);
		});
	}
	init(); //加载数据

	// 为任务save保存之后事件,点击+按钮即可添加数据
	gantt.attachEvent('onBeforeTaskAdd', function (id, item) {
		$.post("/ganttTasks/addItem",{"projectId":projectId,"data":JSON.stringify(item)},function(json){
			location.reload();//刷新当前页面,重新渲染表单
		},"json");
	});
	// 修改任务之后的事件
	gantt.attachEvent("onAfterTaskUpdate", function (id, item) {
		var d = new Date(item.start_date);
		item.update_date = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() ;//+ ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
		$.post("/ganttTasks/editItem",{"data":JSON.stringify(item)},function(json){
		},"json");
	});

	// 删除任务事件
	gantt.attachEvent("onAfterTaskDelete", function (id, item) {
		$.post("/ganttTasks/delete",{"id":item.id},function(json){
		},"json");
	});
	gantt.init("gantt_here");
</script>

</body>
</html>

三.后端代码

	/**
     * 新增接口
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(String data,String projectId) {
        GanttTasksParam ganttTasks=JSON.parseObject(data, GanttTasksParam.class);//转成对象
        ganttTasks.setProjectId(projectId);
        this.ganttTasksService.add(ganttTasks);
        return ResponseData.success(200,"成功",null);
    }

@Override
    public void add(GanttTasksParam param) {
        GanttTasks oldEntity = getEntity(param);
        //计算天数 
        int days = (int) DateUtil.betweenDay((oldEntity.getStartDate()), oldEntity.getEndDate(), false);
        oldEntity.setDuration(days);//天数
        oldEntity.setProgress(0.0);//任务完成度 0到1
        oldEntity.setGanttId(null);//id 自增长

        //收到的参与人数据是 "["1","2","3"]" 要转成 “1,2,3”
        String [] a=oldEntity.getUsers().replaceAll("\\[","").replaceAll("\\]","").split(",");
        String as=null;
        for (int i = 0; i < a.length; i++) {
            if (as!=null){
                String  ass=a[i].replace("\"","");
                as=as+","+ass;
            }else {
                as=a[i].replace("\"","");
            }
        }
        oldEntity.setUsers(as);
        this.save(oldEntity);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值