<template>
	<el-container>
		<el-header style="height: 50%; padding: 0">
			<el-container>
				<el-header>
					<div class="'left-panel'">
						<el-button
							type="primary"
							icon="el-icon-plus"
							@click="utaskCreate"
							v-auth="'utask.create'"
							>新增任务</el-button
						>
						<el-button
							type="primary"
							@click="utaskBreak"
							v-loading="isBreakLoading"
							v-auth="'utask.assgin'"
							:disabled="!canBreak"
							>任务分解</el-button
						>
						<el-button
							type="primary"
							@click="utaskDepuse"
							v-loading="isLoading"
							v-auth="'utask.assgin'"
							:disabled="!canDepuse"
							>任务下达</el-button
						>
					</div>
					<div class="'right-panel'">
						<el-date-picker
							v-model="dateValue"
							type="daterange"
							range-separator="至"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							value-format="YYYY-MM-DD"
							style="vertical-align: middle; margin-right: 6px"
						/>
						<el-button
							type="primary"
							@click="utaskSearch"
							v-loading="isLoading"
							>搜索</el-button
						>
					</div>
				</el-header>
				<el-main class="nopadding">
					<scTable
						ref="table"
						:apiObj="apiUtask"
						row-key="id"
						stripe
						:params="paramsUtask"
						@row-click="rowclick"
						@selection-change="handleSelectionChange"
						@dataChange="updateCount"
					>
						<el-table-column type="selection" width="40" />
						<el-table-column type="index" width="40" />
						<el-table-column
							label="任务编号"
							prop="number"
							min-width="160"
							show-overflow-tooltip
						>
						</el-table-column>
						<el-table-column
							label="产品名称"
							prop="material_"
							min-width="150"
							show-overflow-tooltip
						>
							<template #default="scope">
								{{ scope.row.material_.name }}
							</template>
						</el-table-column>
						<el-table-column label="规格" prop="material_">
							<template #default="scope">
								{{ scope.row.material_.specification }}
							</template>
						</el-table-column>
						<el-table-column label="型号" prop="material_">
							<template #default="scope">
								{{ scope.row.material_.model }}
							</template>
						</el-table-column>
						<el-table-column label="任务状态" prop="state">
							<template #default="scope">
								<el-tag
									v-if="scope.row.state == 40"
									type="success"
								>
									{{ state_[scope.row.state] }}
								</el-tag>
								<el-tag
									v-else-if="scope.row.state == 34"
									type="danger"
								>
									{{ state_[scope.row.state] }}
								</el-tag>
								<el-tag v-else>
									{{ state_[scope.row.state] }}
								</el-tag>
							</template>
						</el-table-column>
						<el-table-column label="任务类型" prop="type">
							<template #default="scope">
								<el-link
									v-if="scope.row.type == 'mass'"
									type="primary"
									>量产</el-link
								>
								<el-link v-else type="success">中试</el-link>
							</template>
						</el-table-column>
						<el-table-column label="任务量" prop="count">
						</el-table-column>
						<el-table-column label="计划量" prop="count">
						</el-table-column>
						<el-table-column label="日均产量" prop="count_day">
						</el-table-column>
						<el-table-column
							label="计划开工时间"
							prop="start_date"
							width="120"
						>
						</el-table-column>
						<el-table-column
							label="计划完工时间"
							prop="end_date"
							width="120"
						>
						</el-table-column>
						<el-table-column label="合格数" prop="count_ok">
						</el-table-column>
						<el-table-column label="完成率" prop="count">
							<template #default="scope">
								<span
									v-if="
										scope.row.count != 0 &&
										scope.row.count_ok != 0
									"
									>{{
										Math.round(
											(scope.row.count_ok /
												scope.row.count) *
												100
										)
									}}%</span
								>
								<span v-else>0</span>
							</template>
						</el-table-column>
						<el-table-column label="操作" fixed="right" width="150">
							<template #default="scope">
								<el-button
									link
									type="primary"
									@click.stop="table_show(scope.row)"
								>
									查看
								</el-button>
								<el-button
									link
									type="primary"
									@click.stop="table_edit(scope.row)"
									v-if="scope.row.state == 10"
									v-auth="'utask.update'"
								>
									编辑
								</el-button>
								<el-popconfirm
									title="确定删除吗？"
									@confirm.stop="table_del(scope.row)"
									v-if="
										scope.row.state == 10 ||
										scope.row.state == 14 ||
										scope.row.state == 20
									"
									v-auth="'utask.delete'"
								>
									<template #reference>
										<el-button link type="danger"
											>删除</el-button
										>
									</template>
								</el-popconfirm>
								<el-popconfirm
									title="确定停止/恢复该任务吗？"
									@confirm.stop="table_toggle(scope.row)"
									v-if="scope.row.state == 30 || scope.row.state == 34"
									v-auth="'utask.toggle'"
								>
									<template #reference>
										<el-button link type="danger"
											>停/复</el-button
										>
									</template>
								</el-popconfirm>
							</template>
						</el-table-column>
					</scTable>
				</el-main>
			</el-container>
		</el-header>
		<el-main class="nopadding">
			<GanttComponent
				class="left-container"
				v-if="ganntVisit"
				:tasks="tasks"
				:key="timeStamp"
				:start_date="start_date"
			>
			</GanttComponent>
		</el-main>
	</el-container>
	<showDrawer
		ref="showDrawer"
		v-if="visibleDrawer"
		:utaskId="utaskId"
		@closed="visibleDrawer = false"
	>
	</showDrawer>
	<save-dialog
		v-if="dialog.save"
		ref="saveDialog"
		:activeDept="currentDept.id"
		@success="handleSaveSuccess"
		@closed="dialog.save = false"
	></save-dialog>
</template>
<script>
import saveDialog from "./utask_form.vue";
import showDrawer from "./mtask_drawer.vue";
import GanttComponent from "@/components/GanttComponent.vue";
export default {
	name: "utask_dept10",
	components: {
		saveDialog,
		showDrawer,
		GanttComponent,
	},
	data() {
		return {
			utaskId: "",
			canBreak:true,
			canDepuse:true,
			isBreakLoading: false,
			visibleDrawer: false,
			isLoading: false,
			selectedIds: [],
			dialog: {
				save: false,
			},
			tasks: {
				data: [],
			},
			dateValue: "",
			apiUtask: null,
			apiObj: null,
			timeStamp: "",
			ganntVisit: true,
			visibleRecord: false,
			currentDept: { id: 0 },
			paramsUtask: {},
			paramsObj: {},
			utaskList: [],
			selection:[],
			state_: {
				10: "创建中",
				14: "已分解",
				20: "已下达",
				30: "生产中",
				34: "终止",
				40: "已提交",
			},
			start_date: "",
		};
	},
	mounted() {
		this.initDept();
	},
	methods: {
		initDept() {
			let that = this;
			that.$API.system.dept.list
				.req({ page: 0, name: "10车间" })
				.then((res) => {
					if (res.length == 1) {
						that.currentDept = res[0];
						that.paramsUtask.belong_dept = that.currentDept.id;
						that.apiUtask = that.$API.pm.utask.list;
						that.getGantt();
					} else {
						that.$message.error("未找到车间");
					}
				});
		},
		updateCount(res, tableData) {
			let that = this;
			this.count = res.count;
			let data = [];
			that.ganntVisit = false;
			that.tasks.data = [];
			let date = new Date();
			that.timeStamp = date.getTime();
			if (tableData.length > 0) {
				tableData.forEach((item) => {
					let start_date = item.start_date;
					let end_date = item.end_date;
					let objItem = {};
					objItem.id = item.id;
					objItem.type = "utask";
					objItem.number = item.number;
					objItem.count = item.count;
					objItem.text = item.number;
					objItem.material_name = item.material_.name;
					objItem.material_specification =
						item.material_.specification;
					objItem.material_model = item.material_.model;
					objItem.progress = item.count_real / item.count;
					objItem.count_ok = item.count_ok;
					objItem.count_real = item.count_real;
					objItem.count_notok = item.count_notok;
					objItem.state = item.state;
					objItem.start_date = start_date;
					objItem.utaskType = item.type;
					objItem.mgroup_name = item.mgroup_name;
					objItem.open = true;
					let oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
					let firstDate = new Date(start_date);
					let secondDate = new Date(end_date);
					let timeDiff = Math.abs(
						secondDate.getTime() - firstDate.getTime()
					);
					let daysDiff = Math.ceil(timeDiff / oneDay);
					objItem.duration = daysDiff + 1;
					data.push(objItem);
					that.start_date = start_date;
				});
			}
			that.tasks.data = data;
			that.ganntVisit = true;
			gantt.parse(that.tasks);
			gantt.refreshData();
		},
		getGantt() {
			let that = this;
			that.$API.pm.utask.list.req(that.paramsUtask).then((res) => {
				let list = res.results;
				let data = [];
				list.forEach((item) => {
					let start_date = item.start_date;
					let end_date = item.end_date;
					let objItem = {};
					objItem.id = item.id;
					objItem.type = "utask";
					objItem.number = item.number;
					objItem.count = item.count;
					objItem.text = item.number;
					objItem.material_name = item.material_.name;
					objItem.material_specification =
						item.material_.specification;
					objItem.material_model = item.material_.model;
					objItem.progress = item.count_real / item.count;
					objItem.count_ok = item.count_ok;
					objItem.count_real = item.count_real;
					objItem.count_notok = item.count_notok;
					objItem.state = item.state;
					objItem.start_date = start_date;
					objItem.utaskType = item.type;
					objItem.mgroup_name = item.mgroup_name;
					objItem.open = true;
					let oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
					let firstDate = new Date(start_date);
					let secondDate = new Date(end_date);
					let timeDiff = Math.abs(
						secondDate.getTime() - firstDate.getTime()
					);
					let daysDiff = Math.ceil(timeDiff / oneDay);
					objItem.duration = daysDiff + 1;
					data.push(objItem);
					that.start_date = start_date;
					console.log("objItemduration", objItem.duration);
				});
				that.tasks.data = data;

				gantt.parse(that.tasks);
				// 刷新数据
				gantt.refreshData();
			});
		},
		utaskBreak() {
			let that = this;
			if (that.selectedIds.length > 0) {
				let ids = that.selectedIds;
				that.isBreakLoading = true;
				that.$API.pm.utask.scheduemtasks.req({ ids: ids }).then((res) => {
					that.$message.success("任务分解成功");
					that.isBreakLoading = false;
					that.$refs.table.refresh();
				}).catch(() => {
					that.isBreakLoading = false;
				});
			} else {
				this.$message.error("未选择任何任务");
			}
		},
		utaskDepuse() {
			let that = this;
			if (that.selectedIds.length > 0) {
				let ids = that.selectedIds;
				that.isLoading = true;
				that.$API.pm.utask.assgin.req({ ids: ids }).then((res) => {
					that.$message.success("下达任务成功");
					that.isLoading = false;
					that.$refs.table.refresh();
				}).catch(() => {
					that.isLoading = false;
				});
			} else {
				this.$message.error("未选择任何任务");
			}
		},
		handleSelectionChange(selection) {
			this.selectedIds = [];
			this.selection= selection;
			if(selection.length>0){
				selection.forEach((item) => {
					this.selectedIds.push(item.id);
					if(item.state == 10){//创建中
						this.canBreak = true;
						this.canDepuse = false;
					}else if(item.state == 14){//已分解
						this.canDepuse = true;
						this.canBreak = false;
					}else{
						this.canBreak = false;
						this.canDepuse = false;
					}
				});
			}else{
				this.canBreak = true;
				this.canDepuse = true;
			}
			
		},
		utaskCreate() {
			this.dialog.save = true;
			this.$nextTick(() => {
				this.$refs.saveDialog.open("add");
			});
		},
		table_edit(row) {
			this.dialog.save = true;
			this.$nextTick(() => {
				this.$refs.saveDialog.open("edit").setData(row);
			});
		},
		table_del(row) {
			this.$API.pm.utask.delete
				.req(row.id)
				.then((res) => {
					this.$message.success("删除成功");
					this.$refs.table.refresh();
					return res;
				})
				.catch((err) => {
					return err;
				});
		},
		table_toggle(row) {
			this.$API.pm.utask.toggle
				.req(row.id)
				.then((res) => {
					this.$message.success("操作成功");
					this.$refs.table.refresh();
					return res;
				})
				.catch((err) => {
					return err;
				});
		},
		bindClass(item) {
			let classInfo = {
				countBlock: true,
				redColor: false,
				greenColor: false,
				orangeColor: false,
			};
			if (item.state != 40) {
				classInfo.orangeColor = true;
			} else {
				if (item.count_ok >= item.count) {
					classInfo.greenColor = true;
				} else {
					classInfo.redColor = true;
				}
			}

			return classInfo;
		},
		table_show(row) {
			this.utaskId = row.id;
			this.visibleDrawer = true;
			this.$nextTick(() => {
				this.$refs.showDrawer.open();
			});
		},
		// rowclick(val) {
		//     let utask = val.id;
		//     this.$API.pm.mtask.list.req({ utask: utask, page: 0 }).then((res) => {
		//         let columList = [];
		//         res.forEach((item) => {
		//             let obj = {};
		//             obj.id = item.id
		//             obj.state = item.state;
		//             obj.count_b = 0
		//             obj.count_y = 0
		//             item.mlogs.forEach((item2) => {
		//                 if (item2.shift_name.indexOf('白班')) {
		//                     obj.count_b = item2.count_ok
		//                 }
		//                 else if (item2.shift_name.indexOf('夜班')) {
		//                     obj.count_y = item2.count_ok
		//                 }
		//             })
		//             obj.count_ok = item.count_ok
		//             obj.count = item.count;
		//             obj.start_date = item.start_date;
		//             columList.push(obj);
		//         });
		//         this.mtaskList = columList
		//         this.utaskList = [val]
		//     });
		// },
		handleSaveSuccess(data, mode) {
			this.$refs.table.refresh();
		},
		utaskSearch() {
			this.ganntVisit = false;
			if (this.dateValue && this.dateValue.length > 0) {
				let start_date = this.dateValue[0];
				let end_date = this.dateValue[1];
				this.paramsUtask.start_date__gte = start_date;
				this.paramsUtask.end_date__lte = end_date;
			} else {
				this.paramsUtask.start_date__gte = "";
				this.paramsUtask.end_date__lte = "";
			}
			this.$refs.table.refresh();
		},
	},
};
</script>
<style scoped>
.countBlock {
	width: 80px;
	color: #ffffff;
	text-align: center;
}
.redColor {
	background-color: brown;
}

.greenColor {
	background-color: green;
}

.orangeColor {
	background-color: orange;
}
</style>
