<template>
	<div class="app-container">
		<search-bar
			:formConfigs="formConfig"
			ref="searchBarForm"
			@headBtnClick="buttonClick" />
		<base-table
			v-loading="dataListLoading"
			:table-props="tableProps"
			:page="listQuery.pageNo"
			:limit="listQuery.pageSize"
			:table-data="tableData">
			<method-btn
				v-if="tableBtn.length"
				slot="handleBtn"
				:width="350"
				label="操作"
				:method-list="tableBtn"
				@clickBtn="handleClick" />
		</base-table>
		<pagination
			:limit.sync="listQuery.pageSize"
			:page.sync="listQuery.pageNo"
			:total="listQuery.total"
			@pagination="getDataList" />
		<base-dialog
			:dialogTitle="addOrEditTitle"
			:dialogVisible="addOrUpdateVisible"
			@cancel="handleCancel"
			@confirm="handleConfirm"
			:before-close="handleCancel"
			width="70%">
			<add-work-order
				ref="addOrUpdate"
				@refreshDataList="refreshWorkOrder"></add-work-order>
		</base-dialog>
		<!-- 预使用原料信息 -->
		<add-or-update
			v-if="materialVisible"
			ref="material"
			@refreshDataList="closeDetail"></add-or-update>
			<!-- 分配产量 -->
			<allocation
			v-if="allocationVisible"
			ref="allocation"
			@refreshDataList="getDataList" />
	</div>
</template>

<script>
import AddOrUpdate from './add-or-updata';
import AddWorkOrder from './addWorkOrder'
import Allocation from './allocation.vue';
import basicPage from '../../core/mixins/basic-page';
import { parseTime } from '../../core/mixins/code-filter';
import {
	getCoreWOPage,
	deleteCoreWO,
	statusChange,
	getConOrderList,
	getCoreWOList
} from '@/api/base/coreWorkOrder';


const tableProps = [
	{
		prop: 'createTime',
		label: '创建时间',
		filter: parseTime,
		minWidth: 150,
		showOverflowtooltip: true
	},
	{
		prop: 'name',
		label: '工单名称',
		minWidth: 120,
		showOverflowtooltip: true
	},
	{
		prop: 'code',
		label: '工单编码',
		minWidth: 150,
		showOverflowtooltip: true
	},
	{
		prop: 'workers',
		label: '负责人',
		minWidth: 100,
		showOverflowtooltip: true
	},
	{
		prop: 'priority',
		label: '优先级',
		filter: (val) => ['', '低', '正常', '高'][val]
	},
	{
		prop: 'triggerOrigin',
		label: '来源',
		filter: (val) => ['', 'MES-手动', 'MES-订单下发', 'ERP'][val]
	},
	{
		prop: 'status',
		label: '工单状态',
		filter: (val) => ['', '等待', '激活', '暂停', '完成', '', '', '', '', '作废'][val]
	},
	{
		prop: 'planFinishTime',
		label: '计划完成时间',
		filter: parseTime,
		minWidth: 150,
		showOverflowtooltip: true
	},
	{
		prop: 'planQuantity',
		label: '计划生产数量',
		minWidth: 120,
	},
	{
		prop: 'actualQuantity',
		label: '实际生产数量',
		minWidth: 120,
	}
];

export default {
	mixins: [basicPage],
	components: {
		AddWorkOrder,
		AddOrUpdate,
		Allocation
	},
	data() {
		return {
			urlOptions: {
				getDataListURL: getCoreWOPage,
				deleteURL: deleteCoreWO
			},
			detailVisible: false,
			materialVisible: false,
			allocationVisible: false,
			tableProps,
			tableBtn: [
				this.$auth.hasPermi(`base:core-work-order:material`)
					? {
							type: 'material',
							btnName: '原料信息',
					  }
					: undefined,
					{
						type: 'active',
						btnName: '激活',
						showParam: {
							type: '|',
							data: [
								{
									name: 'status',
									type: 'equal',
									value: 1
								},
								{
									name: 'status',
									type: 'equal',
									value: 3
								}
							]
						}
					},
					{
						type: 'pause',
						btnName: '暂停',
						showParam: {
							type: '|',
							data: [
								{
									name: 'status',
									type: 'equal',
									value: 2
								}
							]
						}
					},
					{
						type: 'nullify',
						btnName: '作废',
						showParam: {
							type: '|',
							data: [
								{
									name: 'status',
									type: 'equal',
									value: 2
								},
								{
									name: 'status',
									type: 'equal',
									value: 3
								},
								{
									name: 'status',
									type: 'equal',
									value: 4
								}
							]
						}
					},
					{
						type: 'finish',
						btnName: '完成',
						showParam: {
							type: '|',
							data: [
								{
									name: 'status',
									type: 'equal',
									value: 2
								},
								{
									name: 'status',
									type: 'equal',
									value: 3
								}
							]
						}
					},
					this.$auth.hasPermi(`base:core-work-order:detail`)
					? {
							type: 'detail',
							btnName: '查看详情',
					  }
					: undefined,
					this.$auth.hasPermi(`base:core-work-order:update`)
					? {
							type: 'edit',
							btnName: '编辑',
							showParam: {
								type: '&',
								data: [
									{
										name: 'status',
										type: 'equal',
										value: 1
									}
								]
							}
					  }
					: undefined,
          this.$auth.hasPermi(`base:core-work-order:delete`)
					? {
							type: 'delete',
							btnName: '删除',
							showParam: {
								type: '|',
								data: [
									{
										name: 'status',
										type: 'equal',
										value: 1
									}
								]
							}
					  }
					: undefined
			].filter((v)=>v),
			tableData: [],
			formConfig: [
				// {
				// 	type: 'select',
				// 	label: '工单名称',
				// 	placeholder: '工单名称',
				// 	param: 'name',
				// 	defaultSelect: '',
				// 	selectOptions: [],
				// 	allowCreate: true,
				// 	filterable: true
				// },
				{
					type: 'input',
					label: '工单名称',
					placeholder: '工单名称',
					param: 'name',
					defaultSelect: ''
				},
				{
          type: 'select',
          label: '状态',
          selectOptions: [
						{ id: 1, name: '等待' },
						{ id: 2, name: '激活' },
						{ id: 3, name: '暂停' },
						{ id: 4, name: '完成' },
						{ id: 9, name: '作废' }
					],
          param: 'status',
          clearable: true
        },
				{
          type: 'datePicker',
          label: '工单实际开始时间',
          dateType: 'datetimerange',
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          rangeSeparator: '-',
          startPlaceholder: '开始时间',
          endPlaceholder: '结束时间',
          width: 350,
          param: 'time'
        },
				{
					type: 'button',
					btnName: '查询',
					name: 'search',
					color: 'primary',
				},
				{
					type: 'separate',
				},
				{
					type: this.$auth.hasPermi('base:core-work-order:create') ? 'button' : '',
					btnName: '新增',
					name: 'add',
					color: 'success',
					plain: true
				},
			],
		};
	},
	mounted() {
		console.log(this.$route.query.workOrderName)
		if (this.$route.query.workOrderName) {
			this.listQuery.name = this.$route.query.workOrderName;
			this.formConfig[0].defaultSelect = this.$route.query.workOrderName;
		}
		// this.getWorkOrder()
		this.getDataList()
	},
	methods: {
		getWorkOrder() {
			getCoreWOList().then(res => {
				this.formConfig[0].selectOptions = res.data.map(item => {
					return {
						name: item.name,
						id: item.name
					}
				})
			})
		},
		refreshWorkOrder(val) {
			console.log(val)
			if (val) {
				// 预使用原料信息
				console.log('预使用原料信息')
				this.handleCancel()
      	this.getDataList()
				this.materialVisible = true;
        this.addOrEditTitle = "预使用主原料信息";
        this.$nextTick(() => {
          this.$refs.material.init(val, true);
        });
			} else {
				this.successSubmit()
			}
		},
		closeDetail() {
			this.detailVisible = false
			this.materialVisible = false
			this.getDataList()
		},
		// 其他方法
		otherMethods(val) {
			if (val.type === 'material') {
				this.materialVisible = true;
        this.addOrEditTitle = "预使用主原料信息";
        this.$nextTick(() => {
          this.$refs.material.init(val.data, true);
        });
			} else if (val.type === 'detail') {
				this.$router.push({
					path: '/produce/core-work-order-detail',
					query:{
						id: val.data.id
					}
				});
				// this.detailVisible = true;
        // this.addOrEditTitle = "详情";
        // this.$nextTick(() => {
        //   this.$refs.detail.init(val.data.id, true);
        // });
			} else {
				const param = {
					id: val.data.id,
					status: undefined
				}
				let opration = ''
				if (val.type === 'active') {
					param.status = 2
					opration = '激活'
				}
				if (val.type === 'pause') {
					param.status = 3
					opration = '暂停'
				}
				if (val.type === 'nullify') {
					param.status = 9
					opration = '报废'
				}
				if (val.type === 'finish') {
					param.status = 4
					opration = '完成'
				}
				console.log('22',val)
				this.$confirm(`确定${opration}${'"工单' + val.data.name + '"'}?`, "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				})
        .then(() => {
					statusChange(param).then(({ data }) => {
						this.$message({
							message: '操作成功！工单状态稍后将会更新！',
							type: 'success',
							duration: 1500,
							onClose: () => {
								this.getDataList();
								// 分配产量
								if (param.status === 4) {
									this.allocationOrder(param);
								}
							},
						});
					});
				})
				.catch(() => { });
			}
		},
		allocationOrder(val) {
			// 获取订单列表
			getConOrderList({
				workOrderId: val.id,
			}).then((response) => {
				if (response.data.length > 0) {
					this.$confirm('工单结束，可分配产量', "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					})
					.then(() => {
						this.allocationVisible = true;
						this.$nextTick(() => {
							this.$refs.allocation.init(val.id, true);
						});
					})
					.catch(() => { });
				}
				// this.listQuery.total = response.data.total;
			});
		},
		buttonClick(val) {
			switch (val.btnName) {
				case 'search':
					this.listQuery.pageNo = 1;
					this.listQuery.pageSize = 10;
					this.listQuery.name = val.name ? val.name : undefined;
					this.listQuery.status = val.status ? val.status : undefined;
					this.listQuery.startProduceTime = val.time ? val.time : undefined
					this.getDataList();
					break;
				case 'reset':
					this.$refs.searchBarForm.resetForm();
					this.listQuery = {
						pageSize: 10,
						pageNo: 1,
						total: 1,
					};
					this.getDataList();
					break;
				case 'add':
					this.addOrEditTitle = '新增';
					this.addOrUpdateVisible = true;
					this.addOrUpdateHandle();
					break;
				case 'export':
					this.handleExport();
					break;
				default:
					console.log(val);
			}
		},
	},
};
</script>
