<template>
	<div class="app-container">
		<!-- 搜索工作栏 -->
		<search-bar
			:formConfigs="formConfig"
			ref="searchBarForm"
			@headBtnClick="buttonClick" />

		<el-table
			:data="list"
			:header-cell-style="{
				background: '#F2F4F9',
				color: '#606266',
			}"
			class="orderTable"
			v-loading="loading"
			border
			style="width: 100%"
			:max-height="tableH"
			:row-class-name="tableRowClassName"
			ref="table"
			row-key="id"
			lazy
			:load="load"
			:tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
			<el-table-column prop="grade" label="订单类型" width="150">
				<template slot-scope="scope">
					{{
						scope.row.grade != null
							? ['一级订单', '二级订单', '三级订单'][scope.row.grade - 1]
							: '-'
					}}
				</template>
			</el-table-column>
			<el-table-column prop="createTime" label="添加时间" width="160">
				<template v-slot="scope">
					<span>{{ parseTime(scope.row.createTime) }}</span>
				</template>
			</el-table-column>
			<el-table-column
				prop="name"
				label="订单名称"
				show-overflow-tooltip
				min-width="120" />
			<el-table-column prop="code" label="订单编码" width="160" />
			<el-table-column
				prop="customerName"
				label="客户"
				show-overflow-tooltip
				min-width="120" />
			<el-table-column prop="status" label="订单状态">
				<template v-slot="scope">
					<span>
						{{ getDictDataLabel(DICT_TYPE.ORDER_STATUS, scope.row.status) }}
					</span>
				</template>
			</el-table-column>
			<el-table-column prop="planQuantity" label="计划加工量" width="100" />
			<el-table-column prop="actualQuantity" label="实际加工量" width="100" />
			<el-table-column
				prop="productName"
				label="产品"
				show-overflow-tooltip
				min-width="120" />
			<el-table-column prop="deliveTime" label="交货时间" width="160">
				<template v-slot="scope">
					<span>{{ parseTime(scope.row.deliveTime) }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="workOrderNum" label="工单数量" width="140">
				<template v-slot="scope">
					<el-button @click="handleRoute" type="text">
						{{ scope.row.workOrderNum }}
					</el-button>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="340">
				<template v-slot="scope">
					<el-button
						type="text"
						:disabled="!(scope.row.status != 5 && scope.row.workOrderNum === 0)"
						@click="handleClick({ data: scope.row, type: 'split' })"
						v-hasPermi="['base:order-manage:split']">
						拆分订单
					</el-button>
					<span style="margin: 0 4px; font-size: 18px; color: #e5e7eb">|</span>
					<el-button
						type="text"
						:disabled="
							!(
								scope.row.status === 1 ||
								scope.row.status === 2 ||
								scope.row.status === 3
							)
						"
						@click="handleClick({ data: scope.row, type: 'bind' })"
						v-hasPermi="['base:order-manage:bindWorkOrder']">
						绑定工单
					</el-button>
          <!-- addWorkOrder -->
					<span style="margin: 0 4px; font-size: 18px; color: #e5e7eb">|</span>
					<el-button
						type="text"
						:disabled="!(scope.row.status === 2 || scope.row.status === 3)"
						@click="handleClick({ data: scope.row, type: 'complete' })"
						v-hasPermi="['base:order-manage:bindWorkOrder']">
						完成
					</el-button>
					<span style="margin: 0 4px; font-size: 18px; color: #e5e7eb">|</span>
					<el-button
						type="text"
						@click="handleClick({ data: scope.row, type: 'detail' })"
						v-hasPermi="['base:order-manage:detail']">
						<span class="iconfont icon-detail primary-color" />
					</el-button>
					<span style="margin: 0 4px; font-size: 18px; color: #e5e7eb">|</span>
					<el-button
						type="text"
						:disabled="
							!(scope.row.status === 1 && scope.row.triggerOrigin === 1)
						"
						@click="handleClick({ data: scope.row, type: 'edit' })"
						v-hasPermi="['base:order-manage:edit']">
						<span
							class="iconfont icon-edit"
							:class="
								!(scope.row.status === 1 && scope.row.triggerOrigin === 1)
									? ''
									: 'primary-color'
							" />
					</el-button>
					<span style="margin: 0 4px; font-size: 18px; color: #e5e7eb">|</span>
					<el-button
						type="text"
						:disabled="scope.row.status != 1"
						@click="handleClick({ data: scope.row, type: 'void' })"
						v-hasPermi="['base:order-manage:delete']">
						作废
					</el-button>
					<span style="margin: 0 4px; font-size: 18px; color: #e5e7eb">|</span>
					<el-button
						type="text"
						@click="handleClick({ data: scope.row, type: 'stop' })"
						v-hasPermi="['base:order-manage:stop']">
						终止
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination
			:page.sync="queryParams.pageNo"
			:limit.sync="queryParams.pageSize"
			:total="total"
			@pagination="getList" />
		<!-- 新增&编辑 -->
		<base-dialog
			:dialogTitle="addOrEditTitle"
			:dialogVisible="centervisible"
			@cancel="handleCancel"
			@confirm="handleConfirm"
			:before-close="handleCancel"
			width="60%">
			<order-add ref="orderAdd" @successSubmit="successSubmit" />
		</base-dialog>
		<!-- 查看详情 -->
		<!-- 新增工单 -->
		<base-dialog
			:dialogTitle="workIssueTitle"
			:dialogVisible="addWorkOrdervisible"
			@cancel="addWorkOrderCancel"
			@confirm="addWorkOrderConfirm"
			:before-close="addWorkOrderCancel"
			width="70%">
			<add-work-order
				ref="addWorkOrder"
				@addWorkOrderSubmit="addWorkOrderSubmit" />
		</base-dialog>
		<base-dialog
			:dialogTitle="splitTitle"
			:dialogVisible="splitWorkOrdervisible"
			@cancel="splitWorkOrderCancel"
			@confirm="splitWorkOrderConfirm"
			:before-close="splitWorkOrderCancel"
			width="70%">
			<order-split
				ref="splitWorkOrder"
				@splitWorkOrderSubmit="splitWorkOrderSubmit" />
		</base-dialog>
	</div>
</template>
<script>
import { parseTime } from '@/utils/ruoyi';
import {
	getOrderPage,
	orderDelete,
	orderAssignmentList,
	orderFinish,
	orderVoid,
	orderStop,
} from '@/api/base/orderManage';
import OrderAdd from './components/orderAdd';
import orderSplit from './components/orderSplit';

import AddWorkOrder from './components/addWorkOrder';

export default {
	name: 'OrderManage',
	data() {
		return {
			formConfig: [
				{
					type: 'input',
					label: '订单名称',
					placeholder: '订单名称',
					param: 'name',
				},
				{
					type: 'select',
					label: '状态',
					selectOptions: this.getDictDatas(this.DICT_TYPE.ORDER_STATUS),
					labelField: 'label',
					valueField: 'value',
					param: 'status',
				},
				{
					type: 'datePicker',
					label: '时间段',
					dateType: 'daterange',
					format: 'yyyy-MM-dd',
					valueFormat: 'yyyy-MM-dd',
					rangeSeparator: '-',
					startPlaceholder: '开始时间',
					endPlaceholder: '结束时间',
					param: 'timeVal',
					defaultSelect: [],
					width: 250,
				},
				{
					type: 'button',
					btnName: '查询',
					name: 'search',
					color: 'primary',
				},
				{
					type: this.$auth.hasPermi('base:order-manage:create')
						? 'separate'
						: '',
				},
				{
					type: this.$auth.hasPermi('base:order-manage:create') ? 'button' : '',
					btnName: '新增',
					name: 'add',
					color: 'success',
					plain: true,
				},
			],
			loading: false,
			splitTitle: '拆分订单',
			splitWorkOrdervisible: false,
			// 查询参数
			queryParams: {
				pageNo: 1,
				pageSize: 20,
				name: null,
				status: null,
				lastIssuedTime: [],
			},
			total: 0,
			list: [],
			tableH: this.tableHeight(260),
			addOrEditTitle: '',
			centervisible: false,
			expandedRowKeys: [],
			priorityList: this.getDictDatas(this.DICT_TYPE.ORDER_PRIORITY),
			workIssueTitle: '',
			addWorkOrdervisible: false,
			orderDetailVisible: false,
		};
	},
	components: { OrderAdd, AddWorkOrder, orderSplit },
	created() {
		window.addEventListener('resize', () => {
			this.tableH = this.tableHeight(260);
		});
		this.getList();
	},
	methods: {
		load(tree, treeNode, resolve) {
			setTimeout(() => {
				getOrderPage({ ...this.queryParams, parentId: tree.id }).then((res) => {
					let arr = res.data.records || [];
					// if (arr.length > 0) {
					// 	arr.forEach((item) => {
					// 		item.hasChildren = true;
					// 	});
					// } else {
					// 	this.$message('该条数据无子订单或工单！');
					// }
					resolve(arr);
				});
			}, 1000);
		},
		// async handleRowClick(row) {
		// 	console.log(row);
		// 	if (!row.children) {
		// 		const queryParams = {
		// 			pageNo: this.queryParams.pageNo,
		// 			pageSize: this.queryParams.pageSize,
		// 			name: this.queryParams.name,
		// 			status: this.queryParams.status,
		// 			lastIssuedTime: this.queryParams.lastIssuedTime,
		// 			parentId: row.id,
		// 		};
		// 		const response = await getOrderPage(queryParams);
		// 		// row.children = response.data.records
		// 		this.list.forEach((ele) => {
		// 			if (ele.id === row.id) {
		// 				this.$set(
		// 					this.list[row._pageIndex - 1],
		// 					'children',
		// 					response.data.records
		// 				); // 展开该行
		// 			}
		// 		});
		// 		row.hasChildren = true;
		// 		this.$set(row, 'expanded', true); // 展开该行
		// 	} else {
		// 		row.expanded = !row.expanded; // 切换展开/折叠状态
		// 	}
		// 	// this.$nextTick(() => {
		// 	//   const tableInstance = this.$refs.table.getTableRef();
		// 	//   tableInstance.toggleRowExpansion(row);
		// 	// })
		// },
		getList() {
			this.loading = true;
			this.list = [];
			getOrderPage({ ...this.queryParams }).then((res) => {
				let arr = res.data.records || [];
				this.total = res.data.total || 0;
				// if (arr.length > 0) {
				//   customerList().then(result => {
				//     let tempData = result.data || []
				//     if (tempData.length > 0) {
				//       arr.map(item => {
				//         for (let i of tempData) {
				//           if (item.customerId === i.id) {
				//             item.customerId = i.name
				//           }
				//         }
				//         item.price = item.price.toFixed(2)
				//       })
				this.list = arr;
				this.loading = false;
				//     }
				//   })
				// }else {
				//   this.list = arr
				// }
			});
		},
		buttonClick(val) {
			if (val.btnName === 'search') {
				this.queryParams.name = val.name;
				this.queryParams.status = val.status;
				if (val.timeVal && val.timeVal.length > 0) {
					this.queryParams.lastIssuedTime[0] = val.timeVal[0] + ' 00:00:00';
					this.queryParams.lastIssuedTime[1] = val.timeVal[1] + ' 23:59:59';
				} else {
					this.queryParams.lastIssuedTime = [];
				}
				this.getList();
			} else {
				this.addOrEditTitle = '新增';
				this.centervisible = true;
				this.$nextTick(() => {
					this.$refs.orderAdd.init();
				});
			}
		},
		handleClick(val) {
			console.log(val);
			switch (val.type) {
				case 'edit':
					this.addOrEditTitle = '编辑';
					this.centervisible = true;
					this.$nextTick(() => {
						this.$refs.orderAdd.init(val.data.id);
					});
					break;
				case 'delete':
					this.handleDelete(val.data);
					break;
				case 'detail':
					this.$router.push({
						path: 'order-detail-data?orderId=' + val.data.id,
					});
					break;
				case 'add':
					this.workIssueTitle = '新增工单';
					this.addWorkOrdervisible = true;
					this.$nextTick(() => {
						this.$refs.addWorkOrder.init(val.data, 'add');
					});
					break;
				case 'void':
					orderVoid({ id: val.data.id }).then((res) => {
						console.log(res);
					});
					break;
				case 'split':
					this.splitTitle = '拆分订单';
					this.splitWorkOrdervisible = true;
					this.$nextTick(() => {
						this.$refs.splitWorkOrder.init(val.data);
					});
					// orderVoid({ id: val.data.id }).then((res) => {
					//   console.log(res)
					// })
					break;
				case 'bind':
					this.workIssueTitle = '绑定工单';
					this.addWorkOrdervisible = true;
					this.$nextTick(() => {
						this.$refs.addWorkOrder.init(val.data, 'bind');
					});
					break;
				case 'complete':
					this.handleComplete(val.data);
					break;
				case 'stop':
					orderStop({ id: val.data.id }).then((res) => {
						this.getList();
					});
					break;
				default:
			}
		},
		// 删除
		handleDelete(val) {
			this.$modal
				.confirm('是否确认删除"' + val.name + '"的数据项?')
				.then(function () {
					return orderDelete({ id: val.id });
				})
				.then(() => {
					this.getList();
					this.$modal.msgSuccess('操作成功');
				})
				.catch(() => {});
		},
		// 完成
		handleComplete(val) {
			this.$modal
				.confirm('是否确认完成订单"' + val.name + '"?')
				.then(function () {
					return orderFinish({ id: val.id });
				})
				.then(() => {
					this.getList();
					this.$modal.msgSuccess('操作成功');
				})
				.catch(() => {});
		},
		// 新增
		handleCancel() {
			this.$refs.orderAdd.formClear();
			this.centervisible = false;
			this.addOrEditTitle = '';
		},
		handleConfirm() {
			this.$refs.orderAdd.submitForm();
		},
		successSubmit() {
			this.handleCancel();
			this.getList();
		},
		// 下发新增
		addWorkOrderCancel() {
			this.$refs.addWorkOrder.formClear();
			this.addWorkOrdervisible = false;
		},
		addWorkOrderConfirm() {
			this.$refs.addWorkOrder.addWorkOrderSubmit();
		},
		addWorkOrderSubmit() {
			this.addWorkOrderCancel();
			this.getList();
		},
		splitWorkOrderCancel() {
			this.$refs.splitWorkOrder.formClear();
			this.splitWorkOrdervisible = false;
		},
		splitWorkOrderConfirm() {
			this.$refs.splitWorkOrder.submitForm();
		},
		splitWorkOrderSubmit() {
			this.splitWorkOrderCancel();
			this.getList();
		},
		async handleRoute() {
			const res = await orderAssignmentList({
				orderIdList: [this.injectData.id],
			});
			console.log(res.data);
			let arr = [];
			res.data[this.injectData.id].forEach((ele) => {
				arr.push(ele.workOrderId);
			});
			let woIdString = arr.join(',');
			console.log(woIdString);

			this.$router.push({
				path: '/produce/core-work-order-detail?woIdString=' + woIdString,
			});
		},
		tableRowClassName({ row, rowIndex }) {
			if (row.grade === 2) {
				return 'warning-row';
			} else if (row.grade === 3) {
				return 'success-row';
			}
			return '';
		},
		// bindWorkOrderCancel() {
		//   this.$refs.bindWorkOrder.formClear()
		//   this.bindWorkOrdervisible = false
		// },
		// bindWorkOrderConfirm() {
		//   this.$refs.bindWorkOrder.bindWorkOrderSubmit()
		// },
		// bindWorkOrderSubmit() {
		//   this.bindWorkOrderCancel()
		//   this.getList()
		// }
	},
};
</script>

<style scoped>
.iconfont {
	font-family: 'iconfont' !important;
	font-size: 16px;
	font-style: normal;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}
.delete-color {
	color: #ff5454;
}
.primary-color {
	color: #0b58ff;
}
.icon-detail:before {
	content: '\e601';
}

.icon-edit:before {
	content: '\e602';
}

.orderTable >>> .warning-row {
	background: oldlace;
}

.orderTable >>> .success-row {
	background: #f0f9eb;
}
.orderTable >>> tbody tr:hover > td {
	background-color: unset !important;
}
</style>
